PageRenderTime 79ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 3ms

/lib/moodlelib.php

https://github.com/glovenone/moodle
PHP | 9965 lines | 5787 code | 1274 blank | 2904 comment | 1353 complexity | 45dc033818c0dcbdeda38730183a6082 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

Large files files are truncated, but you can click here to view the full file

  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. * moodlelib.php - Moodle main library
  18. *
  19. * Main library file of miscellaneous general-purpose Moodle functions.
  20. * Other main libraries:
  21. * - weblib.php - functions that produce web output
  22. * - datalib.php - functions that access the database
  23. *
  24. * @package core
  25. * @subpackage lib
  26. * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
  27. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  28. */
  29. defined('MOODLE_INTERNAL') || die();
  30. /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
  31. /// Date and time constants ///
  32. /**
  33. * Time constant - the number of seconds in a year
  34. */
  35. define('YEARSECS', 31536000);
  36. /**
  37. * Time constant - the number of seconds in a week
  38. */
  39. define('WEEKSECS', 604800);
  40. /**
  41. * Time constant - the number of seconds in a day
  42. */
  43. define('DAYSECS', 86400);
  44. /**
  45. * Time constant - the number of seconds in an hour
  46. */
  47. define('HOURSECS', 3600);
  48. /**
  49. * Time constant - the number of seconds in a minute
  50. */
  51. define('MINSECS', 60);
  52. /**
  53. * Time constant - the number of minutes in a day
  54. */
  55. define('DAYMINS', 1440);
  56. /**
  57. * Time constant - the number of minutes in an hour
  58. */
  59. define('HOURMINS', 60);
  60. /// Parameter constants - every call to optional_param(), required_param() ///
  61. /// or clean_param() should have a specified type of parameter. //////////////
  62. /**
  63. * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
  64. */
  65. define('PARAM_ALPHA', 'alpha');
  66. /**
  67. * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
  68. * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
  69. */
  70. define('PARAM_ALPHAEXT', 'alphaext');
  71. /**
  72. * PARAM_ALPHANUM - expected numbers and letters only.
  73. */
  74. define('PARAM_ALPHANUM', 'alphanum');
  75. /**
  76. * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
  77. */
  78. define('PARAM_ALPHANUMEXT', 'alphanumext');
  79. /**
  80. * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
  81. */
  82. define('PARAM_AUTH', 'auth');
  83. /**
  84. * PARAM_BASE64 - Base 64 encoded format
  85. */
  86. define('PARAM_BASE64', 'base64');
  87. /**
  88. * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
  89. */
  90. define('PARAM_BOOL', 'bool');
  91. /**
  92. * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
  93. * checked against the list of capabilities in the database.
  94. */
  95. define('PARAM_CAPABILITY', 'capability');
  96. /**
  97. * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
  98. */
  99. define('PARAM_CLEANHTML', 'cleanhtml');
  100. /**
  101. * PARAM_EMAIL - an email address following the RFC
  102. */
  103. define('PARAM_EMAIL', 'email');
  104. /**
  105. * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
  106. */
  107. define('PARAM_FILE', 'file');
  108. /**
  109. * PARAM_FLOAT - a real/floating point number.
  110. */
  111. define('PARAM_FLOAT', 'float');
  112. /**
  113. * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
  114. */
  115. define('PARAM_HOST', 'host');
  116. /**
  117. * PARAM_INT - integers only, use when expecting only numbers.
  118. */
  119. define('PARAM_INT', 'int');
  120. /**
  121. * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
  122. */
  123. define('PARAM_LANG', 'lang');
  124. /**
  125. * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
  126. */
  127. define('PARAM_LOCALURL', 'localurl');
  128. /**
  129. * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
  130. */
  131. define('PARAM_NOTAGS', 'notags');
  132. /**
  133. * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
  134. * note: the leading slash is not removed, window drive letter is not allowed
  135. */
  136. define('PARAM_PATH', 'path');
  137. /**
  138. * PARAM_PEM - Privacy Enhanced Mail format
  139. */
  140. define('PARAM_PEM', 'pem');
  141. /**
  142. * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
  143. */
  144. define('PARAM_PERMISSION', 'permission');
  145. /**
  146. * PARAM_RAW specifies a parameter that is not cleaned/processed in any way
  147. */
  148. define('PARAM_RAW', 'raw');
  149. /**
  150. * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
  151. */
  152. define('PARAM_RAW_TRIMMED', 'raw_trimmed');
  153. /**
  154. * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
  155. */
  156. define('PARAM_SAFEDIR', 'safedir');
  157. /**
  158. * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
  159. */
  160. define('PARAM_SAFEPATH', 'safepath');
  161. /**
  162. * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
  163. */
  164. define('PARAM_SEQUENCE', 'sequence');
  165. /**
  166. * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
  167. */
  168. define('PARAM_TAG', 'tag');
  169. /**
  170. * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
  171. */
  172. define('PARAM_TAGLIST', 'taglist');
  173. /**
  174. * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
  175. */
  176. define('PARAM_TEXT', 'text');
  177. /**
  178. * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
  179. */
  180. define('PARAM_THEME', 'theme');
  181. /**
  182. * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
  183. */
  184. define('PARAM_URL', 'url');
  185. /**
  186. * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
  187. */
  188. define('PARAM_USERNAME', 'username');
  189. /**
  190. * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
  191. */
  192. define('PARAM_STRINGID', 'stringid');
  193. ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
  194. /**
  195. * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
  196. * It was one of the first types, that is why it is abused so much ;-)
  197. * @deprecated since 2.0
  198. */
  199. define('PARAM_CLEAN', 'clean');
  200. /**
  201. * PARAM_INTEGER - deprecated alias for PARAM_INT
  202. */
  203. define('PARAM_INTEGER', 'int');
  204. /**
  205. * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
  206. */
  207. define('PARAM_NUMBER', 'float');
  208. /**
  209. * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
  210. * NOTE: originally alias for PARAM_APLHA
  211. */
  212. define('PARAM_ACTION', 'alphanumext');
  213. /**
  214. * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
  215. * NOTE: originally alias for PARAM_APLHA
  216. */
  217. define('PARAM_FORMAT', 'alphanumext');
  218. /**
  219. * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
  220. */
  221. define('PARAM_MULTILANG', 'text');
  222. /**
  223. * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
  224. */
  225. define('PARAM_CLEANFILE', 'file');
  226. /// Web Services ///
  227. /**
  228. * VALUE_REQUIRED - if the parameter is not supplied, there is an error
  229. */
  230. define('VALUE_REQUIRED', 1);
  231. /**
  232. * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
  233. */
  234. define('VALUE_OPTIONAL', 2);
  235. /**
  236. * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
  237. */
  238. define('VALUE_DEFAULT', 0);
  239. /**
  240. * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
  241. */
  242. define('NULL_NOT_ALLOWED', false);
  243. /**
  244. * NULL_ALLOWED - the parameter can be set to null in the database
  245. */
  246. define('NULL_ALLOWED', true);
  247. /// Page types ///
  248. /**
  249. * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
  250. */
  251. define('PAGE_COURSE_VIEW', 'course-view');
  252. /** Get remote addr constant */
  253. define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
  254. /** Get remote addr constant */
  255. define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
  256. /// Blog access level constant declaration ///
  257. define ('BLOG_USER_LEVEL', 1);
  258. define ('BLOG_GROUP_LEVEL', 2);
  259. define ('BLOG_COURSE_LEVEL', 3);
  260. define ('BLOG_SITE_LEVEL', 4);
  261. define ('BLOG_GLOBAL_LEVEL', 5);
  262. ///Tag constants///
  263. /**
  264. * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
  265. * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
  266. * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
  267. *
  268. * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
  269. */
  270. define('TAG_MAX_LENGTH', 50);
  271. /// Password policy constants ///
  272. define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
  273. define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  274. define ('PASSWORD_DIGITS', '0123456789');
  275. define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
  276. /// Feature constants ///
  277. // Used for plugin_supports() to report features that are, or are not, supported by a module.
  278. /** True if module can provide a grade */
  279. define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
  280. /** True if module supports outcomes */
  281. define('FEATURE_GRADE_OUTCOMES', 'outcomes');
  282. /** True if module has code to track whether somebody viewed it */
  283. define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
  284. /** True if module has custom completion rules */
  285. define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
  286. /** True if module has no 'view' page (like label) */
  287. define('FEATURE_NO_VIEW_LINK', 'viewlink');
  288. /** True if module supports outcomes */
  289. define('FEATURE_IDNUMBER', 'idnumber');
  290. /** True if module supports groups */
  291. define('FEATURE_GROUPS', 'groups');
  292. /** True if module supports groupings */
  293. define('FEATURE_GROUPINGS', 'groupings');
  294. /** True if module supports groupmembersonly */
  295. define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
  296. /** Type of module */
  297. define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
  298. /** True if module supports intro editor */
  299. define('FEATURE_MOD_INTRO', 'mod_intro');
  300. /** True if module has default completion */
  301. define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
  302. define('FEATURE_COMMENT', 'comment');
  303. define('FEATURE_RATE', 'rate');
  304. /** True if module supports backup/restore of moodle2 format */
  305. define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
  306. /** Unspecified module archetype */
  307. define('MOD_ARCHETYPE_OTHER', 0);
  308. /** Resource-like type module */
  309. define('MOD_ARCHETYPE_RESOURCE', 1);
  310. /** Assignment module archetype */
  311. define('MOD_ARCHETYPE_ASSIGNMENT', 2);
  312. /**
  313. * Security token used for allowing access
  314. * from external application such as web services.
  315. * Scripts do not use any session, performance is relatively
  316. * low because we need to load access info in each request.
  317. * Scripts are executed in parallel.
  318. */
  319. define('EXTERNAL_TOKEN_PERMANENT', 0);
  320. /**
  321. * Security token used for allowing access
  322. * of embedded applications, the code is executed in the
  323. * active user session. Token is invalidated after user logs out.
  324. * Scripts are executed serially - normal session locking is used.
  325. */
  326. define('EXTERNAL_TOKEN_EMBEDDED', 1);
  327. /**
  328. * The home page should be the site home
  329. */
  330. define('HOMEPAGE_SITE', 0);
  331. /**
  332. * The home page should be the users my page
  333. */
  334. define('HOMEPAGE_MY', 1);
  335. /**
  336. * The home page can be chosen by the user
  337. */
  338. define('HOMEPAGE_USER', 2);
  339. /**
  340. * Hub directory url (should be moodle.org)
  341. */
  342. define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
  343. /**
  344. * Moodle.org url (should be moodle.org)
  345. */
  346. define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
  347. /// PARAMETER HANDLING ////////////////////////////////////////////////////
  348. /**
  349. * Returns a particular value for the named variable, taken from
  350. * POST or GET. If the parameter doesn't exist then an error is
  351. * thrown because we require this variable.
  352. *
  353. * This function should be used to initialise all required values
  354. * in a script that are based on parameters. Usually it will be
  355. * used like this:
  356. * $id = required_param('id', PARAM_INT);
  357. *
  358. * Please note the $type parameter is now required,
  359. * for now PARAM_CLEAN is used for backwards compatibility only.
  360. *
  361. * @param string $parname the name of the page parameter we want
  362. * @param string $type expected type of parameter
  363. * @return mixed
  364. */
  365. function required_param($parname, $type) {
  366. if (!isset($type)) {
  367. debugging('required_param() requires $type to be specified.');
  368. $type = PARAM_CLEAN; // for now let's use this deprecated type
  369. }
  370. if (isset($_POST[$parname])) { // POST has precedence
  371. $param = $_POST[$parname];
  372. } else if (isset($_GET[$parname])) {
  373. $param = $_GET[$parname];
  374. } else {
  375. print_error('missingparam', '', '', $parname);
  376. }
  377. return clean_param($param, $type);
  378. }
  379. /**
  380. * Returns a particular value for the named variable, taken from
  381. * POST or GET, otherwise returning a given default.
  382. *
  383. * This function should be used to initialise all optional values
  384. * in a script that are based on parameters. Usually it will be
  385. * used like this:
  386. * $name = optional_param('name', 'Fred', PARAM_TEXT);
  387. *
  388. * Please note $default and $type parameters are now required,
  389. * for now PARAM_CLEAN is used for backwards compatibility only.
  390. *
  391. * @param string $parname the name of the page parameter we want
  392. * @param mixed $default the default value to return if nothing is found
  393. * @param string $type expected type of parameter
  394. * @return mixed
  395. */
  396. function optional_param($parname, $default, $type) {
  397. if (!isset($type)) {
  398. debugging('optional_param() requires $default and $type to be specified.');
  399. $type = PARAM_CLEAN; // for now let's use this deprecated type
  400. }
  401. if (!isset($default)) {
  402. $default = null;
  403. }
  404. if (isset($_POST[$parname])) { // POST has precedence
  405. $param = $_POST[$parname];
  406. } else if (isset($_GET[$parname])) {
  407. $param = $_GET[$parname];
  408. } else {
  409. return $default;
  410. }
  411. return clean_param($param, $type);
  412. }
  413. /**
  414. * Strict validation of parameter values, the values are only converted
  415. * to requested PHP type. Internally it is using clean_param, the values
  416. * before and after cleaning must be equal - otherwise
  417. * an invalid_parameter_exception is thrown.
  418. * Objects and classes are not accepted.
  419. *
  420. * @param mixed $param
  421. * @param int $type PARAM_ constant
  422. * @param bool $allownull are nulls valid value?
  423. * @param string $debuginfo optional debug information
  424. * @return mixed the $param value converted to PHP type or invalid_parameter_exception
  425. */
  426. function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
  427. if (is_null($param)) {
  428. if ($allownull == NULL_ALLOWED) {
  429. return null;
  430. } else {
  431. throw new invalid_parameter_exception($debuginfo);
  432. }
  433. }
  434. if (is_array($param) or is_object($param)) {
  435. throw new invalid_parameter_exception($debuginfo);
  436. }
  437. $cleaned = clean_param($param, $type);
  438. if ((string)$param !== (string)$cleaned) {
  439. // conversion to string is usually lossless
  440. throw new invalid_parameter_exception($debuginfo);
  441. }
  442. return $cleaned;
  443. }
  444. /**
  445. * Used by {@link optional_param()} and {@link required_param()} to
  446. * clean the variables and/or cast to specific types, based on
  447. * an options field.
  448. * <code>
  449. * $course->format = clean_param($course->format, PARAM_ALPHA);
  450. * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
  451. * </code>
  452. *
  453. * @param mixed $param the variable we are cleaning
  454. * @param int $type expected format of param after cleaning.
  455. * @return mixed
  456. */
  457. function clean_param($param, $type) {
  458. global $CFG;
  459. if (is_array($param)) { // Let's loop
  460. $newparam = array();
  461. foreach ($param as $key => $value) {
  462. $newparam[$key] = clean_param($value, $type);
  463. }
  464. return $newparam;
  465. }
  466. switch ($type) {
  467. case PARAM_RAW: // no cleaning at all
  468. return $param;
  469. case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
  470. return trim($param);
  471. case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
  472. // this is deprecated!, please use more specific type instead
  473. if (is_numeric($param)) {
  474. return $param;
  475. }
  476. return clean_text($param); // Sweep for scripts, etc
  477. case PARAM_CLEANHTML: // clean html fragment
  478. $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
  479. return trim($param);
  480. case PARAM_INT:
  481. return (int)$param; // Convert to integer
  482. case PARAM_FLOAT:
  483. case PARAM_NUMBER:
  484. return (float)$param; // Convert to float
  485. case PARAM_ALPHA: // Remove everything not a-z
  486. return preg_replace('/[^a-zA-Z]/i', '', $param);
  487. case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
  488. return preg_replace('/[^a-zA-Z_-]/i', '', $param);
  489. case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
  490. return preg_replace('/[^A-Za-z0-9]/i', '', $param);
  491. case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
  492. return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
  493. case PARAM_SEQUENCE: // Remove everything not 0-9,
  494. return preg_replace('/[^0-9,]/i', '', $param);
  495. case PARAM_BOOL: // Convert to 1 or 0
  496. $tempstr = strtolower($param);
  497. if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
  498. $param = 1;
  499. } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
  500. $param = 0;
  501. } else {
  502. $param = empty($param) ? 0 : 1;
  503. }
  504. return $param;
  505. case PARAM_NOTAGS: // Strip all tags
  506. return strip_tags($param);
  507. case PARAM_TEXT: // leave only tags needed for multilang
  508. // if the multilang syntax is not correct we strip all tags
  509. // because it would break xhtml strict which is required for accessibility standards
  510. // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
  511. do {
  512. if (strpos($param, '</lang>') !== false) {
  513. // old and future mutilang syntax
  514. $param = strip_tags($param, '<lang>');
  515. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  516. break;
  517. }
  518. $open = false;
  519. foreach ($matches[0] as $match) {
  520. if ($match === '</lang>') {
  521. if ($open) {
  522. $open = false;
  523. continue;
  524. } else {
  525. break 2;
  526. }
  527. }
  528. if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
  529. break 2;
  530. } else {
  531. $open = true;
  532. }
  533. }
  534. if ($open) {
  535. break;
  536. }
  537. return $param;
  538. } else if (strpos($param, '</span>') !== false) {
  539. // current problematic multilang syntax
  540. $param = strip_tags($param, '<span>');
  541. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  542. break;
  543. }
  544. $open = false;
  545. foreach ($matches[0] as $match) {
  546. if ($match === '</span>') {
  547. if ($open) {
  548. $open = false;
  549. continue;
  550. } else {
  551. break 2;
  552. }
  553. }
  554. if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
  555. break 2;
  556. } else {
  557. $open = true;
  558. }
  559. }
  560. if ($open) {
  561. break;
  562. }
  563. return $param;
  564. }
  565. } while (false);
  566. // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
  567. return strip_tags($param);
  568. case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
  569. return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
  570. case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
  571. return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
  572. case PARAM_FILE: // Strip all suspicious characters from filename
  573. $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
  574. $param = preg_replace('~\.\.+~', '', $param);
  575. if ($param === '.') {
  576. $param = '';
  577. }
  578. return $param;
  579. case PARAM_PATH: // Strip all suspicious characters from file path
  580. $param = str_replace('\\', '/', $param);
  581. $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
  582. $param = preg_replace('~\.\.+~', '', $param);
  583. $param = preg_replace('~//+~', '/', $param);
  584. return preg_replace('~/(\./)+~', '/', $param);
  585. case PARAM_HOST: // allow FQDN or IPv4 dotted quad
  586. $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
  587. // match ipv4 dotted quad
  588. if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
  589. // confirm values are ok
  590. if ( $match[0] > 255
  591. || $match[1] > 255
  592. || $match[3] > 255
  593. || $match[4] > 255 ) {
  594. // hmmm, what kind of dotted quad is this?
  595. $param = '';
  596. }
  597. } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
  598. && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
  599. && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
  600. ) {
  601. // all is ok - $param is respected
  602. } else {
  603. // all is not ok...
  604. $param='';
  605. }
  606. return $param;
  607. case PARAM_URL: // allow safe ftp, http, mailto urls
  608. include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
  609. if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
  610. // all is ok, param is respected
  611. } else {
  612. $param =''; // not really ok
  613. }
  614. return $param;
  615. case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
  616. $param = clean_param($param, PARAM_URL);
  617. if (!empty($param)) {
  618. if (preg_match(':^/:', $param)) {
  619. // root-relative, ok!
  620. } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
  621. // absolute, and matches our wwwroot
  622. } else {
  623. // relative - let's make sure there are no tricks
  624. if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
  625. // looks ok.
  626. } else {
  627. $param = '';
  628. }
  629. }
  630. }
  631. return $param;
  632. case PARAM_PEM:
  633. $param = trim($param);
  634. // PEM formatted strings may contain letters/numbers and the symbols
  635. // forward slash: /
  636. // plus sign: +
  637. // equal sign: =
  638. // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
  639. if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
  640. list($wholething, $body) = $matches;
  641. unset($wholething, $matches);
  642. $b64 = clean_param($body, PARAM_BASE64);
  643. if (!empty($b64)) {
  644. return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
  645. } else {
  646. return '';
  647. }
  648. }
  649. return '';
  650. case PARAM_BASE64:
  651. if (!empty($param)) {
  652. // PEM formatted strings may contain letters/numbers and the symbols
  653. // forward slash: /
  654. // plus sign: +
  655. // equal sign: =
  656. if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
  657. return '';
  658. }
  659. $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
  660. // Each line of base64 encoded data must be 64 characters in
  661. // length, except for the last line which may be less than (or
  662. // equal to) 64 characters long.
  663. for ($i=0, $j=count($lines); $i < $j; $i++) {
  664. if ($i + 1 == $j) {
  665. if (64 < strlen($lines[$i])) {
  666. return '';
  667. }
  668. continue;
  669. }
  670. if (64 != strlen($lines[$i])) {
  671. return '';
  672. }
  673. }
  674. return implode("\n",$lines);
  675. } else {
  676. return '';
  677. }
  678. case PARAM_TAG:
  679. // Please note it is not safe to use the tag name directly anywhere,
  680. // it must be processed with s(), urlencode() before embedding anywhere.
  681. // remove some nasties
  682. $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
  683. //convert many whitespace chars into one
  684. $param = preg_replace('/\s+/', ' ', $param);
  685. $textlib = textlib_get_instance();
  686. $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
  687. return $param;
  688. case PARAM_TAGLIST:
  689. $tags = explode(',', $param);
  690. $result = array();
  691. foreach ($tags as $tag) {
  692. $res = clean_param($tag, PARAM_TAG);
  693. if ($res !== '') {
  694. $result[] = $res;
  695. }
  696. }
  697. if ($result) {
  698. return implode(',', $result);
  699. } else {
  700. return '';
  701. }
  702. case PARAM_CAPABILITY:
  703. if (get_capability_info($param)) {
  704. return $param;
  705. } else {
  706. return '';
  707. }
  708. case PARAM_PERMISSION:
  709. $param = (int)$param;
  710. if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
  711. return $param;
  712. } else {
  713. return CAP_INHERIT;
  714. }
  715. case PARAM_AUTH:
  716. $param = clean_param($param, PARAM_SAFEDIR);
  717. if (exists_auth_plugin($param)) {
  718. return $param;
  719. } else {
  720. return '';
  721. }
  722. case PARAM_LANG:
  723. $param = clean_param($param, PARAM_SAFEDIR);
  724. if (get_string_manager()->translation_exists($param)) {
  725. return $param;
  726. } else {
  727. return ''; // Specified language is not installed or param malformed
  728. }
  729. case PARAM_THEME:
  730. $param = clean_param($param, PARAM_SAFEDIR);
  731. if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
  732. return $param;
  733. } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
  734. return $param;
  735. } else {
  736. return ''; // Specified theme is not installed
  737. }
  738. case PARAM_USERNAME:
  739. $param = str_replace(" " , "", $param);
  740. $param = moodle_strtolower($param); // Convert uppercase to lowercase MDL-16919
  741. if (empty($CFG->extendedusernamechars)) {
  742. // regular expression, eliminate all chars EXCEPT:
  743. // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
  744. $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
  745. }
  746. return $param;
  747. case PARAM_EMAIL:
  748. if (validate_email($param)) {
  749. return $param;
  750. } else {
  751. return '';
  752. }
  753. case PARAM_STRINGID:
  754. if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
  755. return $param;
  756. } else {
  757. return '';
  758. }
  759. default: // throw error, switched parameters in optional_param or another serious problem
  760. print_error("unknownparamtype", '', '', $type);
  761. }
  762. }
  763. /**
  764. * Return true if given value is integer or string with integer value
  765. *
  766. * @param mixed $value String or Int
  767. * @return bool true if number, false if not
  768. */
  769. function is_number($value) {
  770. if (is_int($value)) {
  771. return true;
  772. } else if (is_string($value)) {
  773. return ((string)(int)$value) === $value;
  774. } else {
  775. return false;
  776. }
  777. }
  778. /**
  779. * Returns host part from url
  780. * @param string $url full url
  781. * @return string host, null if not found
  782. */
  783. function get_host_from_url($url) {
  784. preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
  785. if ($matches) {
  786. return $matches[1];
  787. }
  788. return null;
  789. }
  790. /**
  791. * Tests whether anything was returned by text editor
  792. *
  793. * This function is useful for testing whether something you got back from
  794. * the HTML editor actually contains anything. Sometimes the HTML editor
  795. * appear to be empty, but actually you get back a <br> tag or something.
  796. *
  797. * @param string $string a string containing HTML.
  798. * @return boolean does the string contain any actual content - that is text,
  799. * images, objects, etc.
  800. */
  801. function html_is_blank($string) {
  802. return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
  803. }
  804. /**
  805. * Set a key in global configuration
  806. *
  807. * Set a key/value pair in both this session's {@link $CFG} global variable
  808. * and in the 'config' database table for future sessions.
  809. *
  810. * Can also be used to update keys for plugin-scoped configs in config_plugin table.
  811. * In that case it doesn't affect $CFG.
  812. *
  813. * A NULL value will delete the entry.
  814. *
  815. * @global object
  816. * @global object
  817. * @param string $name the key to set
  818. * @param string $value the value to set (without magic quotes)
  819. * @param string $plugin (optional) the plugin scope, default NULL
  820. * @return bool true or exception
  821. */
  822. function set_config($name, $value, $plugin=NULL) {
  823. global $CFG, $DB;
  824. if (empty($plugin)) {
  825. if (!array_key_exists($name, $CFG->config_php_settings)) {
  826. // So it's defined for this invocation at least
  827. if (is_null($value)) {
  828. unset($CFG->$name);
  829. } else {
  830. $CFG->$name = (string)$value; // settings from db are always strings
  831. }
  832. }
  833. if ($DB->get_field('config', 'name', array('name'=>$name))) {
  834. if ($value === null) {
  835. $DB->delete_records('config', array('name'=>$name));
  836. } else {
  837. $DB->set_field('config', 'value', $value, array('name'=>$name));
  838. }
  839. } else {
  840. if ($value !== null) {
  841. $config = new stdClass();
  842. $config->name = $name;
  843. $config->value = $value;
  844. $DB->insert_record('config', $config, false);
  845. }
  846. }
  847. } else { // plugin scope
  848. if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
  849. if ($value===null) {
  850. $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
  851. } else {
  852. $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
  853. }
  854. } else {
  855. if ($value !== null) {
  856. $config = new stdClass();
  857. $config->plugin = $plugin;
  858. $config->name = $name;
  859. $config->value = $value;
  860. $DB->insert_record('config_plugins', $config, false);
  861. }
  862. }
  863. }
  864. return true;
  865. }
  866. /**
  867. * Get configuration values from the global config table
  868. * or the config_plugins table.
  869. *
  870. * If called with one parameter, it will load all the config
  871. * variables for one plugin, and return them as an object.
  872. *
  873. * If called with 2 parameters it will return a string single
  874. * value or false if the value is not found.
  875. *
  876. * @param string $plugin full component name
  877. * @param string $name default NULL
  878. * @return mixed hash-like object or single value, return false no config found
  879. */
  880. function get_config($plugin, $name = NULL) {
  881. global $CFG, $DB;
  882. // normalise component name
  883. if ($plugin === 'moodle' or $plugin === 'core') {
  884. $plugin = NULL;
  885. }
  886. if (!empty($name)) { // the user is asking for a specific value
  887. if (!empty($plugin)) {
  888. if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
  889. // setting forced in config file
  890. return $CFG->forced_plugin_settings[$plugin][$name];
  891. } else {
  892. return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
  893. }
  894. } else {
  895. if (array_key_exists($name, $CFG->config_php_settings)) {
  896. // setting force in config file
  897. return $CFG->config_php_settings[$name];
  898. } else {
  899. return $DB->get_field('config', 'value', array('name'=>$name));
  900. }
  901. }
  902. }
  903. // the user is after a recordset
  904. if ($plugin) {
  905. $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
  906. if (isset($CFG->forced_plugin_settings[$plugin])) {
  907. foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
  908. if (is_null($v) or is_array($v) or is_object($v)) {
  909. // we do not want any extra mess here, just real settings that could be saved in db
  910. unset($localcfg[$n]);
  911. } else {
  912. //convert to string as if it went through the DB
  913. $localcfg[$n] = (string)$v;
  914. }
  915. }
  916. }
  917. if ($localcfg) {
  918. return (object)$localcfg;
  919. } else {
  920. return null;
  921. }
  922. } else {
  923. // this part is not really used any more, but anyway...
  924. $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
  925. foreach($CFG->config_php_settings as $n=>$v) {
  926. if (is_null($v) or is_array($v) or is_object($v)) {
  927. // we do not want any extra mess here, just real settings that could be saved in db
  928. unset($localcfg[$n]);
  929. } else {
  930. //convert to string as if it went through the DB
  931. $localcfg[$n] = (string)$v;
  932. }
  933. }
  934. return (object)$localcfg;
  935. }
  936. }
  937. /**
  938. * Removes a key from global configuration
  939. *
  940. * @param string $name the key to set
  941. * @param string $plugin (optional) the plugin scope
  942. * @global object
  943. * @return boolean whether the operation succeeded.
  944. */
  945. function unset_config($name, $plugin=NULL) {
  946. global $CFG, $DB;
  947. if (empty($plugin)) {
  948. unset($CFG->$name);
  949. $DB->delete_records('config', array('name'=>$name));
  950. } else {
  951. $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
  952. }
  953. return true;
  954. }
  955. /**
  956. * Remove all the config variables for a given plugin.
  957. *
  958. * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
  959. * @return boolean whether the operation succeeded.
  960. */
  961. function unset_all_config_for_plugin($plugin) {
  962. global $DB;
  963. $DB->delete_records('config_plugins', array('plugin' => $plugin));
  964. $DB->delete_records_select('config', 'name LIKE ?', array($plugin . '_%'));
  965. return true;
  966. }
  967. /**
  968. * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
  969. *
  970. * All users are verified if they still have the necessary capability.
  971. *
  972. * @param string $value the value of the config setting.
  973. * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
  974. * @param bool $include admins, include administrators
  975. * @return array of user objects.
  976. */
  977. function get_users_from_config($value, $capability, $includeadmins = true) {
  978. global $CFG, $DB;
  979. if (empty($value) or $value === '$@NONE@$') {
  980. return array();
  981. }
  982. // we have to make sure that users still have the necessary capability,
  983. // it should be faster to fetch them all first and then test if they are present
  984. // instead of validating them one-by-one
  985. $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
  986. if ($includeadmins) {
  987. $admins = get_admins();
  988. foreach ($admins as $admin) {
  989. $users[$admin->id] = $admin;
  990. }
  991. }
  992. if ($value === '$@ALL@$') {
  993. return $users;
  994. }
  995. $result = array(); // result in correct order
  996. $allowed = explode(',', $value);
  997. foreach ($allowed as $uid) {
  998. if (isset($users[$uid])) {
  999. $user = $users[$uid];
  1000. $result[$user->id] = $user;
  1001. }
  1002. }
  1003. return $result;
  1004. }
  1005. /**
  1006. * Invalidates browser caches and cached data in temp
  1007. * @return void
  1008. */
  1009. function purge_all_caches() {
  1010. global $CFG;
  1011. reset_text_filters_cache();
  1012. js_reset_all_caches();
  1013. theme_reset_all_caches();
  1014. get_string_manager()->reset_caches();
  1015. // purge all other caches: rss, simplepie, etc.
  1016. remove_dir($CFG->dataroot.'/cache', true);
  1017. // make sure cache dir is writable, throws exception if not
  1018. make_upload_directory('cache');
  1019. clearstatcache();
  1020. }
  1021. /**
  1022. * Get volatile flags
  1023. *
  1024. * @param string $type
  1025. * @param int $changedsince default null
  1026. * @return records array
  1027. */
  1028. function get_cache_flags($type, $changedsince=NULL) {
  1029. global $DB;
  1030. $params = array('type'=>$type, 'expiry'=>time());
  1031. $sqlwhere = "flagtype = :type AND expiry >= :expiry";
  1032. if ($changedsince !== NULL) {
  1033. $params['changedsince'] = $changedsince;
  1034. $sqlwhere .= " AND timemodified > :changedsince";
  1035. }
  1036. $cf = array();
  1037. if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
  1038. foreach ($flags as $flag) {
  1039. $cf[$flag->name] = $flag->value;
  1040. }
  1041. }
  1042. return $cf;
  1043. }
  1044. /**
  1045. * Get volatile flags
  1046. *
  1047. * @param string $type
  1048. * @param string $name
  1049. * @param int $changedsince default null
  1050. * @return records array
  1051. */
  1052. function get_cache_flag($type, $name, $changedsince=NULL) {
  1053. global $DB;
  1054. $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
  1055. $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
  1056. if ($changedsince !== NULL) {
  1057. $params['changedsince'] = $changedsince;
  1058. $sqlwhere .= " AND timemodified > :changedsince";
  1059. }
  1060. return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
  1061. }
  1062. /**
  1063. * Set a volatile flag
  1064. *
  1065. * @param string $type the "type" namespace for the key
  1066. * @param string $name the key to set
  1067. * @param string $value the value to set (without magic quotes) - NULL will remove the flag
  1068. * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
  1069. * @return bool Always returns true
  1070. */
  1071. function set_cache_flag($type, $name, $value, $expiry=NULL) {
  1072. global $DB;
  1073. $timemodified = time();
  1074. if ($expiry===NULL || $expiry < $timemodified) {
  1075. $expiry = $timemodified + 24 * 60 * 60;
  1076. } else {
  1077. $expiry = (int)$expiry;
  1078. }
  1079. if ($value === NULL) {
  1080. unset_cache_flag($type,$name);
  1081. return true;
  1082. }
  1083. if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
  1084. if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
  1085. return true; //no need to update; helps rcache too
  1086. }
  1087. $f->value = $value;
  1088. $f->expiry = $expiry;
  1089. $f->timemodified = $timemodified;
  1090. $DB->update_record('cache_flags', $f);
  1091. } else {
  1092. $f = new stdClass();
  1093. $f->flagtype = $type;
  1094. $f->name = $name;
  1095. $f->value = $value;
  1096. $f->expiry = $expiry;
  1097. $f->timemodified = $timemodified;
  1098. $DB->insert_record('cache_flags', $f);
  1099. }
  1100. return true;
  1101. }
  1102. /**
  1103. * Removes a single volatile flag
  1104. *
  1105. * @global object
  1106. * @param string $type the "type" namespace for the key
  1107. * @param string $name the key to set
  1108. * @return bool
  1109. */
  1110. function unset_cache_flag($type, $name) {
  1111. global $DB;
  1112. $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
  1113. return true;
  1114. }
  1115. /**
  1116. * Garbage-collect volatile flags
  1117. *
  1118. * @return bool Always returns true
  1119. */
  1120. function gc_cache_flags() {
  1121. global $DB;
  1122. $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
  1123. return true;
  1124. }
  1125. /// FUNCTIONS FOR HANDLING USER PREFERENCES ////////////////////////////////////
  1126. /**
  1127. * Refresh user preference cache. This is used most often for $USER
  1128. * object that is stored in session, but it also helps with performance in cron script.
  1129. *
  1130. * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
  1131. *
  1132. * @param stdClass $user user object, preferences are preloaded into ->preference property
  1133. * @param int $cachelifetime cache life time on the current page (ins seconds)
  1134. * @return void
  1135. */
  1136. function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
  1137. global $DB;
  1138. static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
  1139. if (!isset($user->id)) {
  1140. throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
  1141. }
  1142. if (empty($user->id) or isguestuser($user->id)) {
  1143. // No permanent storage for not-logged-in users and guest
  1144. if (!isset($user->preference)) {
  1145. $user->preference = array();
  1146. }
  1147. return;
  1148. }
  1149. $timenow = time();
  1150. if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
  1151. // Already loaded at least once on this page. Are we up to date?
  1152. if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
  1153. // no need to reload - we are on the same page and we loaded prefs just a moment ago
  1154. return;
  1155. } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
  1156. // no change since the lastcheck on this page
  1157. $user->preference['_lastloaded'] = $timenow;
  1158. return;
  1159. }
  1160. }
  1161. // OK, so we have to reload all preferences
  1162. $loadedusers[$user->id] = true;
  1163. $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
  1164. $user->preference['_lastloaded'] = $timenow;
  1165. }
  1166. /**
  1167. * Called from set/delete_user_preferences, so that the prefs can
  1168. * be correctly reloaded in different sessions.
  1169. *
  1170. * NOTE: internal function, do not call from other code.
  1171. *
  1172. * @param integer $userid the user whose prefs were changed.
  1173. * @return void
  1174. */
  1175. function mark_user_preferences_changed($userid) {
  1176. global $CFG;
  1177. if (empty($userid) or isguestuser($userid)) {
  1178. // no cache flags for guest and not-logged-in users
  1179. return;
  1180. }
  1181. set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
  1182. }
  1183. /**
  1184. * Sets a preference for the specified user.
  1185. *
  1186. * If user object submitted, 'preference' property contains the preferences cache.
  1187. *
  1188. * @param string $name The key to set as preference for the specified user
  1189. * @param string $value The value to set for the $name key in the specified user's record,
  1190. * null means delete current value
  1191. * @param stdClass|int $user A moodle user object or id, null means current user
  1192. * @return bool always true or exception
  1193. */
  1194. function set_user_preference($name, $value, $user = null) {
  1195. global $USER, $DB;
  1196. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1197. throw new coding_exception('Invalid preference name in set_user_preference() call');
  1198. }
  1199. if (is_null($value)) {
  1200. // null means delete current
  1201. return unset_user_preference($name, $user);
  1202. } else if (is_object($value)) {
  1203. throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
  1204. } else if (is_array($value)) {
  1205. throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
  1206. }
  1207. $value = (string)$value;
  1208. if (is_null($user)) {
  1209. $user = $USER;
  1210. } else if (isset($user->id)) {
  1211. // $user is valid object
  1212. } else if (is_numeric($user)) {
  1213. $user = (object)array('id'=>(int)$user);
  1214. } else {
  1215. throw new coding_exception('Invalid $user parameter in set_user_preference() call');
  1216. }
  1217. check_user_preferences_loaded($user);
  1218. if (empty($user->id) or isguestuser($user->id)) {
  1219. // no permanent storage for not-logged-in users and guest
  1220. $user->preference[$name] = $value;
  1221. return true;
  1222. }
  1223. if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
  1224. if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
  1225. // preference already set to this value
  1226. return true;
  1227. }
  1228. $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
  1229. } else {
  1230. $preference = new stdClass();
  1231. $preference->userid = $user->id;
  1232. $preference->name = $name;
  1233. $preference->value = $value;
  1234. $DB->insert_record('user_preferences', $preference);
  1235. }
  1236. // update value in cache
  1237. $user->preference[$name] = $value;
  1238. // set reload flag for other sessions
  1239. mark_user_preferences_changed($user->id);
  1240. return true;
  1241. }
  1242. /**
  1243. * Sets a whole array of preferences for the current user
  1244. *
  1245. * If user object submitted, 'preference' property contains the preferences cache.
  1246. *
  1247. * @param array $prefarray An array of key/value pairs to be set
  1248. * @param stdClass|int $user A moodle user object or id, null means current user
  1249. * @return bool always true or exception
  1250. */
  1251. function set_user_preferences(array $prefarray, $user = null) {
  1252. foreach ($prefarray as $name => $value) {
  1253. set_user_preference($name, $value, $user);
  1254. }
  1255. return true;
  1256. }
  1257. /**
  1258. * Unsets a preference completely by deleting it from the database
  1259. *
  1260. * If user object submitted, 'preference' property contains the preferences cache.
  1261. *
  1262. * @param string $name The key to unset as preference for the specified user
  1263. * @param stdClass|int $user A moodle user object or id, null means current user
  1264. * @return bool always true or exception
  1265. */
  1266. function unset_user_preference($name, $user = null) {
  1267. global $USER, $DB;
  1268. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1269. throw new coding_exception('Invalid preference name in unset_user_preference() call');
  1270. }
  1271. if (is_null($user)) {
  1272. $user = $USER;
  1273. } else if (isset($user->id)) {
  1274. // $user is valid object
  1275. } else if (is_numeric($user)) {
  1276. $user = (object)array('id'=>(int)$user);
  1277. } else {
  1278. throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
  1279. }
  1280. check_user_preferences_loaded($user);
  1281. if (empty($user->id) or isguestuser($user->id)) {
  1282. // no permanent storage for not-logged-in user and guest
  1283. unset($user->preference[$name]);
  1284. return true;
  1285. }
  1286. // delete from DB
  1287. $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
  1288. // delete the preference from cache
  1289. unset($user->preference[$name]);
  1290. // set reload flag for other sessions
  1291. mark_user_preferences_changed($use

Large files files are truncated, but you can click here to view the full file