PageRenderTime 128ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 2ms

/lib/moodlelib.php

https://bitbucket.org/moodle/moodle
PHP | 10722 lines | 6058 code | 1310 blank | 3354 comment | 1502 complexity | d3e5e3d3d096cdb3330a62ef72daf1d7 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.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. * 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 (English ascii letters [a-zA-Z]) 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 0-9 and English ascii letters [a-zA-Z] only.
  73. */
  74. define('PARAM_ALPHANUM', 'alphanum');
  75. /**
  76. * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
  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. Note that you almost never want
  98. * to use this. The normal mode of operation is to use PARAM_RAW when receiving
  99. * the input (required/optional_param or formslib) and then sanitise the HTML
  100. * using format_text on output. This is for the rare cases when you want to
  101. * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
  102. */
  103. define('PARAM_CLEANHTML', 'cleanhtml');
  104. /**
  105. * PARAM_EMAIL - an email address following the RFC
  106. */
  107. define('PARAM_EMAIL', 'email');
  108. /**
  109. * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
  110. */
  111. define('PARAM_FILE', 'file');
  112. /**
  113. * PARAM_FLOAT - a real/floating point number.
  114. *
  115. * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
  116. * It does not work for languages that use , as a decimal separator.
  117. * Use PARAM_LOCALISEDFLOAT instead.
  118. */
  119. define('PARAM_FLOAT', 'float');
  120. /**
  121. * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
  122. * This is preferred over PARAM_FLOAT for numbers typed in by the user.
  123. * Cleans localised numbers to computer readable numbers; false for invalid numbers.
  124. */
  125. define('PARAM_LOCALISEDFLOAT', 'localisedfloat');
  126. /**
  127. * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
  128. */
  129. define('PARAM_HOST', 'host');
  130. /**
  131. * PARAM_INT - integers only, use when expecting only numbers.
  132. */
  133. define('PARAM_INT', 'int');
  134. /**
  135. * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
  136. */
  137. define('PARAM_LANG', 'lang');
  138. /**
  139. * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
  140. * others! Implies PARAM_URL!)
  141. */
  142. define('PARAM_LOCALURL', 'localurl');
  143. /**
  144. * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
  145. */
  146. define('PARAM_NOTAGS', 'notags');
  147. /**
  148. * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
  149. * traversals note: the leading slash is not removed, window drive letter is not allowed
  150. */
  151. define('PARAM_PATH', 'path');
  152. /**
  153. * PARAM_PEM - Privacy Enhanced Mail format
  154. */
  155. define('PARAM_PEM', 'pem');
  156. /**
  157. * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
  158. */
  159. define('PARAM_PERMISSION', 'permission');
  160. /**
  161. * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
  162. */
  163. define('PARAM_RAW', 'raw');
  164. /**
  165. * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
  166. */
  167. define('PARAM_RAW_TRIMMED', 'raw_trimmed');
  168. /**
  169. * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
  170. */
  171. define('PARAM_SAFEDIR', 'safedir');
  172. /**
  173. * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
  174. */
  175. define('PARAM_SAFEPATH', 'safepath');
  176. /**
  177. * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
  178. */
  179. define('PARAM_SEQUENCE', 'sequence');
  180. /**
  181. * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
  182. */
  183. define('PARAM_TAG', 'tag');
  184. /**
  185. * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
  186. */
  187. define('PARAM_TAGLIST', 'taglist');
  188. /**
  189. * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
  190. */
  191. define('PARAM_TEXT', 'text');
  192. /**
  193. * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
  194. */
  195. define('PARAM_THEME', 'theme');
  196. /**
  197. * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
  198. * http://localhost.localdomain/ is ok.
  199. */
  200. define('PARAM_URL', 'url');
  201. /**
  202. * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
  203. * accounts, do NOT use when syncing with external systems!!
  204. */
  205. define('PARAM_USERNAME', 'username');
  206. /**
  207. * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
  208. */
  209. define('PARAM_STRINGID', 'stringid');
  210. // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
  211. /**
  212. * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
  213. * It was one of the first types, that is why it is abused so much ;-)
  214. * @deprecated since 2.0
  215. */
  216. define('PARAM_CLEAN', 'clean');
  217. /**
  218. * PARAM_INTEGER - deprecated alias for PARAM_INT
  219. * @deprecated since 2.0
  220. */
  221. define('PARAM_INTEGER', 'int');
  222. /**
  223. * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
  224. * @deprecated since 2.0
  225. */
  226. define('PARAM_NUMBER', 'float');
  227. /**
  228. * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
  229. * NOTE: originally alias for PARAM_APLHA
  230. * @deprecated since 2.0
  231. */
  232. define('PARAM_ACTION', 'alphanumext');
  233. /**
  234. * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
  235. * NOTE: originally alias for PARAM_APLHA
  236. * @deprecated since 2.0
  237. */
  238. define('PARAM_FORMAT', 'alphanumext');
  239. /**
  240. * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
  241. * @deprecated since 2.0
  242. */
  243. define('PARAM_MULTILANG', 'text');
  244. /**
  245. * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
  246. * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
  247. * America/Port-au-Prince)
  248. */
  249. define('PARAM_TIMEZONE', 'timezone');
  250. /**
  251. * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
  252. */
  253. define('PARAM_CLEANFILE', 'file');
  254. /**
  255. * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
  256. * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
  257. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  258. * NOTE: numbers and underscores are strongly discouraged in plugin names!
  259. */
  260. define('PARAM_COMPONENT', 'component');
  261. /**
  262. * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
  263. * It is usually used together with context id and component.
  264. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  265. */
  266. define('PARAM_AREA', 'area');
  267. /**
  268. * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
  269. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  270. * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
  271. */
  272. define('PARAM_PLUGIN', 'plugin');
  273. // Web Services.
  274. /**
  275. * VALUE_REQUIRED - if the parameter is not supplied, there is an error
  276. */
  277. define('VALUE_REQUIRED', 1);
  278. /**
  279. * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
  280. */
  281. define('VALUE_OPTIONAL', 2);
  282. /**
  283. * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
  284. */
  285. define('VALUE_DEFAULT', 0);
  286. /**
  287. * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
  288. */
  289. define('NULL_NOT_ALLOWED', false);
  290. /**
  291. * NULL_ALLOWED - the parameter can be set to null in the database
  292. */
  293. define('NULL_ALLOWED', true);
  294. // Page types.
  295. /**
  296. * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
  297. */
  298. define('PAGE_COURSE_VIEW', 'course-view');
  299. /** Get remote addr constant */
  300. define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
  301. /** Get remote addr constant */
  302. define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
  303. /**
  304. * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
  305. */
  306. define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP);
  307. // Blog access level constant declaration.
  308. define ('BLOG_USER_LEVEL', 1);
  309. define ('BLOG_GROUP_LEVEL', 2);
  310. define ('BLOG_COURSE_LEVEL', 3);
  311. define ('BLOG_SITE_LEVEL', 4);
  312. define ('BLOG_GLOBAL_LEVEL', 5);
  313. // Tag constants.
  314. /**
  315. * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
  316. * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
  317. * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
  318. *
  319. * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
  320. */
  321. define('TAG_MAX_LENGTH', 50);
  322. // Password policy constants.
  323. define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
  324. define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  325. define ('PASSWORD_DIGITS', '0123456789');
  326. define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
  327. // Feature constants.
  328. // Used for plugin_supports() to report features that are, or are not, supported by a module.
  329. /** True if module can provide a grade */
  330. define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
  331. /** True if module supports outcomes */
  332. define('FEATURE_GRADE_OUTCOMES', 'outcomes');
  333. /** True if module supports advanced grading methods */
  334. define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
  335. /** True if module controls the grade visibility over the gradebook */
  336. define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
  337. /** True if module supports plagiarism plugins */
  338. define('FEATURE_PLAGIARISM', 'plagiarism');
  339. /** True if module has code to track whether somebody viewed it */
  340. define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
  341. /** True if module has custom completion rules */
  342. define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
  343. /** True if module has no 'view' page (like label) */
  344. define('FEATURE_NO_VIEW_LINK', 'viewlink');
  345. /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
  346. define('FEATURE_IDNUMBER', 'idnumber');
  347. /** True if module supports groups */
  348. define('FEATURE_GROUPS', 'groups');
  349. /** True if module supports groupings */
  350. define('FEATURE_GROUPINGS', 'groupings');
  351. /**
  352. * True if module supports groupmembersonly (which no longer exists)
  353. * @deprecated Since Moodle 2.8
  354. */
  355. define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
  356. /** Type of module */
  357. define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
  358. /** True if module supports intro editor */
  359. define('FEATURE_MOD_INTRO', 'mod_intro');
  360. /** True if module has default completion */
  361. define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
  362. define('FEATURE_COMMENT', 'comment');
  363. define('FEATURE_RATE', 'rate');
  364. /** True if module supports backup/restore of moodle2 format */
  365. define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
  366. /** True if module can show description on course main page */
  367. define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
  368. /** True if module uses the question bank */
  369. define('FEATURE_USES_QUESTIONS', 'usesquestions');
  370. /**
  371. * Maximum filename char size
  372. */
  373. define('MAX_FILENAME_SIZE', 100);
  374. /** Unspecified module archetype */
  375. define('MOD_ARCHETYPE_OTHER', 0);
  376. /** Resource-like type module */
  377. define('MOD_ARCHETYPE_RESOURCE', 1);
  378. /** Assignment module archetype */
  379. define('MOD_ARCHETYPE_ASSIGNMENT', 2);
  380. /** System (not user-addable) module archetype */
  381. define('MOD_ARCHETYPE_SYSTEM', 3);
  382. /**
  383. * Security token used for allowing access
  384. * from external application such as web services.
  385. * Scripts do not use any session, performance is relatively
  386. * low because we need to load access info in each request.
  387. * Scripts are executed in parallel.
  388. */
  389. define('EXTERNAL_TOKEN_PERMANENT', 0);
  390. /**
  391. * Security token used for allowing access
  392. * of embedded applications, the code is executed in the
  393. * active user session. Token is invalidated after user logs out.
  394. * Scripts are executed serially - normal session locking is used.
  395. */
  396. define('EXTERNAL_TOKEN_EMBEDDED', 1);
  397. /**
  398. * The home page should be the site home
  399. */
  400. define('HOMEPAGE_SITE', 0);
  401. /**
  402. * The home page should be the users my page
  403. */
  404. define('HOMEPAGE_MY', 1);
  405. /**
  406. * The home page can be chosen by the user
  407. */
  408. define('HOMEPAGE_USER', 2);
  409. /**
  410. * URL of the Moodle sites registration portal.
  411. */
  412. defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
  413. /**
  414. * Moodle mobile app service name
  415. */
  416. define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
  417. /**
  418. * Indicates the user has the capabilities required to ignore activity and course file size restrictions
  419. */
  420. define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
  421. /**
  422. * Course display settings: display all sections on one page.
  423. */
  424. define('COURSE_DISPLAY_SINGLEPAGE', 0);
  425. /**
  426. * Course display settings: split pages into a page per section.
  427. */
  428. define('COURSE_DISPLAY_MULTIPAGE', 1);
  429. /**
  430. * Authentication constant: String used in password field when password is not stored.
  431. */
  432. define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
  433. /**
  434. * Email from header to never include via information.
  435. */
  436. define('EMAIL_VIA_NEVER', 0);
  437. /**
  438. * Email from header to always include via information.
  439. */
  440. define('EMAIL_VIA_ALWAYS', 1);
  441. /**
  442. * Email from header to only include via information if the address is no-reply.
  443. */
  444. define('EMAIL_VIA_NO_REPLY_ONLY', 2);
  445. // PARAMETER HANDLING.
  446. /**
  447. * Returns a particular value for the named variable, taken from
  448. * POST or GET. If the parameter doesn't exist then an error is
  449. * thrown because we require this variable.
  450. *
  451. * This function should be used to initialise all required values
  452. * in a script that are based on parameters. Usually it will be
  453. * used like this:
  454. * $id = required_param('id', PARAM_INT);
  455. *
  456. * Please note the $type parameter is now required and the value can not be array.
  457. *
  458. * @param string $parname the name of the page parameter we want
  459. * @param string $type expected type of parameter
  460. * @return mixed
  461. * @throws coding_exception
  462. */
  463. function required_param($parname, $type) {
  464. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  465. throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
  466. }
  467. // POST has precedence.
  468. if (isset($_POST[$parname])) {
  469. $param = $_POST[$parname];
  470. } else if (isset($_GET[$parname])) {
  471. $param = $_GET[$parname];
  472. } else {
  473. print_error('missingparam', '', '', $parname);
  474. }
  475. if (is_array($param)) {
  476. debugging('Invalid array parameter detected in required_param(): '.$parname);
  477. // TODO: switch to fatal error in Moodle 2.3.
  478. return required_param_array($parname, $type);
  479. }
  480. return clean_param($param, $type);
  481. }
  482. /**
  483. * Returns a particular array value for the named variable, taken from
  484. * POST or GET. If the parameter doesn't exist then an error is
  485. * thrown because we require this variable.
  486. *
  487. * This function should be used to initialise all required values
  488. * in a script that are based on parameters. Usually it will be
  489. * used like this:
  490. * $ids = required_param_array('ids', PARAM_INT);
  491. *
  492. * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
  493. *
  494. * @param string $parname the name of the page parameter we want
  495. * @param string $type expected type of parameter
  496. * @return array
  497. * @throws coding_exception
  498. */
  499. function required_param_array($parname, $type) {
  500. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  501. throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
  502. }
  503. // POST has precedence.
  504. if (isset($_POST[$parname])) {
  505. $param = $_POST[$parname];
  506. } else if (isset($_GET[$parname])) {
  507. $param = $_GET[$parname];
  508. } else {
  509. print_error('missingparam', '', '', $parname);
  510. }
  511. if (!is_array($param)) {
  512. print_error('missingparam', '', '', $parname);
  513. }
  514. $result = array();
  515. foreach ($param as $key => $value) {
  516. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  517. debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
  518. continue;
  519. }
  520. $result[$key] = clean_param($value, $type);
  521. }
  522. return $result;
  523. }
  524. /**
  525. * Returns a particular value for the named variable, taken from
  526. * POST or GET, otherwise returning a given default.
  527. *
  528. * This function should be used to initialise all optional values
  529. * in a script that are based on parameters. Usually it will be
  530. * used like this:
  531. * $name = optional_param('name', 'Fred', PARAM_TEXT);
  532. *
  533. * Please note the $type parameter is now required and the value can not be array.
  534. *
  535. * @param string $parname the name of the page parameter we want
  536. * @param mixed $default the default value to return if nothing is found
  537. * @param string $type expected type of parameter
  538. * @return mixed
  539. * @throws coding_exception
  540. */
  541. function optional_param($parname, $default, $type) {
  542. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  543. throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
  544. }
  545. // POST has precedence.
  546. if (isset($_POST[$parname])) {
  547. $param = $_POST[$parname];
  548. } else if (isset($_GET[$parname])) {
  549. $param = $_GET[$parname];
  550. } else {
  551. return $default;
  552. }
  553. if (is_array($param)) {
  554. debugging('Invalid array parameter detected in required_param(): '.$parname);
  555. // TODO: switch to $default in Moodle 2.3.
  556. return optional_param_array($parname, $default, $type);
  557. }
  558. return clean_param($param, $type);
  559. }
  560. /**
  561. * Returns a particular array value for the named variable, taken from
  562. * POST or GET, otherwise returning a given default.
  563. *
  564. * This function should be used to initialise all optional values
  565. * in a script that are based on parameters. Usually it will be
  566. * used like this:
  567. * $ids = optional_param('id', array(), PARAM_INT);
  568. *
  569. * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
  570. *
  571. * @param string $parname the name of the page parameter we want
  572. * @param mixed $default the default value to return if nothing is found
  573. * @param string $type expected type of parameter
  574. * @return array
  575. * @throws coding_exception
  576. */
  577. function optional_param_array($parname, $default, $type) {
  578. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  579. throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
  580. }
  581. // POST has precedence.
  582. if (isset($_POST[$parname])) {
  583. $param = $_POST[$parname];
  584. } else if (isset($_GET[$parname])) {
  585. $param = $_GET[$parname];
  586. } else {
  587. return $default;
  588. }
  589. if (!is_array($param)) {
  590. debugging('optional_param_array() expects array parameters only: '.$parname);
  591. return $default;
  592. }
  593. $result = array();
  594. foreach ($param as $key => $value) {
  595. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  596. debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
  597. continue;
  598. }
  599. $result[$key] = clean_param($value, $type);
  600. }
  601. return $result;
  602. }
  603. /**
  604. * Strict validation of parameter values, the values are only converted
  605. * to requested PHP type. Internally it is using clean_param, the values
  606. * before and after cleaning must be equal - otherwise
  607. * an invalid_parameter_exception is thrown.
  608. * Objects and classes are not accepted.
  609. *
  610. * @param mixed $param
  611. * @param string $type PARAM_ constant
  612. * @param bool $allownull are nulls valid value?
  613. * @param string $debuginfo optional debug information
  614. * @return mixed the $param value converted to PHP type
  615. * @throws invalid_parameter_exception if $param is not of given type
  616. */
  617. function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
  618. if (is_null($param)) {
  619. if ($allownull == NULL_ALLOWED) {
  620. return null;
  621. } else {
  622. throw new invalid_parameter_exception($debuginfo);
  623. }
  624. }
  625. if (is_array($param) or is_object($param)) {
  626. throw new invalid_parameter_exception($debuginfo);
  627. }
  628. $cleaned = clean_param($param, $type);
  629. if ($type == PARAM_FLOAT) {
  630. // Do not detect precision loss here.
  631. if (is_float($param) or is_int($param)) {
  632. // These always fit.
  633. } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
  634. throw new invalid_parameter_exception($debuginfo);
  635. }
  636. } else if ((string)$param !== (string)$cleaned) {
  637. // Conversion to string is usually lossless.
  638. throw new invalid_parameter_exception($debuginfo);
  639. }
  640. return $cleaned;
  641. }
  642. /**
  643. * Makes sure array contains only the allowed types, this function does not validate array key names!
  644. *
  645. * <code>
  646. * $options = clean_param($options, PARAM_INT);
  647. * </code>
  648. *
  649. * @param array $param the variable array we are cleaning
  650. * @param string $type expected format of param after cleaning.
  651. * @param bool $recursive clean recursive arrays
  652. * @return array
  653. * @throws coding_exception
  654. */
  655. function clean_param_array(array $param = null, $type, $recursive = false) {
  656. // Convert null to empty array.
  657. $param = (array)$param;
  658. foreach ($param as $key => $value) {
  659. if (is_array($value)) {
  660. if ($recursive) {
  661. $param[$key] = clean_param_array($value, $type, true);
  662. } else {
  663. throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
  664. }
  665. } else {
  666. $param[$key] = clean_param($value, $type);
  667. }
  668. }
  669. return $param;
  670. }
  671. /**
  672. * Used by {@link optional_param()} and {@link required_param()} to
  673. * clean the variables and/or cast to specific types, based on
  674. * an options field.
  675. * <code>
  676. * $course->format = clean_param($course->format, PARAM_ALPHA);
  677. * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
  678. * </code>
  679. *
  680. * @param mixed $param the variable we are cleaning
  681. * @param string $type expected format of param after cleaning.
  682. * @return mixed
  683. * @throws coding_exception
  684. */
  685. function clean_param($param, $type) {
  686. global $CFG;
  687. if (is_array($param)) {
  688. throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
  689. } else if (is_object($param)) {
  690. if (method_exists($param, '__toString')) {
  691. $param = $param->__toString();
  692. } else {
  693. throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
  694. }
  695. }
  696. switch ($type) {
  697. case PARAM_RAW:
  698. // No cleaning at all.
  699. $param = fix_utf8($param);
  700. return $param;
  701. case PARAM_RAW_TRIMMED:
  702. // No cleaning, but strip leading and trailing whitespace.
  703. $param = fix_utf8($param);
  704. return trim($param);
  705. case PARAM_CLEAN:
  706. // General HTML cleaning, try to use more specific type if possible this is deprecated!
  707. // Please use more specific type instead.
  708. if (is_numeric($param)) {
  709. return $param;
  710. }
  711. $param = fix_utf8($param);
  712. // Sweep for scripts, etc.
  713. return clean_text($param);
  714. case PARAM_CLEANHTML:
  715. // Clean html fragment.
  716. $param = fix_utf8($param);
  717. // Sweep for scripts, etc.
  718. $param = clean_text($param, FORMAT_HTML);
  719. return trim($param);
  720. case PARAM_INT:
  721. // Convert to integer.
  722. return (int)$param;
  723. case PARAM_FLOAT:
  724. // Convert to float.
  725. return (float)$param;
  726. case PARAM_LOCALISEDFLOAT:
  727. // Convert to float.
  728. return unformat_float($param, true);
  729. case PARAM_ALPHA:
  730. // Remove everything not `a-z`.
  731. return preg_replace('/[^a-zA-Z]/i', '', $param);
  732. case PARAM_ALPHAEXT:
  733. // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
  734. return preg_replace('/[^a-zA-Z_-]/i', '', $param);
  735. case PARAM_ALPHANUM:
  736. // Remove everything not `a-zA-Z0-9`.
  737. return preg_replace('/[^A-Za-z0-9]/i', '', $param);
  738. case PARAM_ALPHANUMEXT:
  739. // Remove everything not `a-zA-Z0-9_-`.
  740. return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
  741. case PARAM_SEQUENCE:
  742. // Remove everything not `0-9,`.
  743. return preg_replace('/[^0-9,]/i', '', $param);
  744. case PARAM_BOOL:
  745. // Convert to 1 or 0.
  746. $tempstr = strtolower($param);
  747. if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
  748. $param = 1;
  749. } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
  750. $param = 0;
  751. } else {
  752. $param = empty($param) ? 0 : 1;
  753. }
  754. return $param;
  755. case PARAM_NOTAGS:
  756. // Strip all tags.
  757. $param = fix_utf8($param);
  758. return strip_tags($param);
  759. case PARAM_TEXT:
  760. // Leave only tags needed for multilang.
  761. $param = fix_utf8($param);
  762. // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
  763. // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
  764. do {
  765. if (strpos($param, '</lang>') !== false) {
  766. // Old and future mutilang syntax.
  767. $param = strip_tags($param, '<lang>');
  768. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  769. break;
  770. }
  771. $open = false;
  772. foreach ($matches[0] as $match) {
  773. if ($match === '</lang>') {
  774. if ($open) {
  775. $open = false;
  776. continue;
  777. } else {
  778. break 2;
  779. }
  780. }
  781. if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
  782. break 2;
  783. } else {
  784. $open = true;
  785. }
  786. }
  787. if ($open) {
  788. break;
  789. }
  790. return $param;
  791. } else if (strpos($param, '</span>') !== false) {
  792. // Current problematic multilang syntax.
  793. $param = strip_tags($param, '<span>');
  794. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  795. break;
  796. }
  797. $open = false;
  798. foreach ($matches[0] as $match) {
  799. if ($match === '</span>') {
  800. if ($open) {
  801. $open = false;
  802. continue;
  803. } else {
  804. break 2;
  805. }
  806. }
  807. if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
  808. break 2;
  809. } else {
  810. $open = true;
  811. }
  812. }
  813. if ($open) {
  814. break;
  815. }
  816. return $param;
  817. }
  818. } while (false);
  819. // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
  820. return strip_tags($param);
  821. case PARAM_COMPONENT:
  822. // We do not want any guessing here, either the name is correct or not
  823. // please note only normalised component names are accepted.
  824. if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
  825. return '';
  826. }
  827. if (strpos($param, '__') !== false) {
  828. return '';
  829. }
  830. if (strpos($param, 'mod_') === 0) {
  831. // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
  832. if (substr_count($param, '_') != 1) {
  833. return '';
  834. }
  835. }
  836. return $param;
  837. case PARAM_PLUGIN:
  838. case PARAM_AREA:
  839. // We do not want any guessing here, either the name is correct or not.
  840. if (!is_valid_plugin_name($param)) {
  841. return '';
  842. }
  843. return $param;
  844. case PARAM_SAFEDIR:
  845. // Remove everything not a-zA-Z0-9_- .
  846. return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
  847. case PARAM_SAFEPATH:
  848. // Remove everything not a-zA-Z0-9/_- .
  849. return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
  850. case PARAM_FILE:
  851. // Strip all suspicious characters from filename.
  852. $param = fix_utf8($param);
  853. $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
  854. if ($param === '.' || $param === '..') {
  855. $param = '';
  856. }
  857. return $param;
  858. case PARAM_PATH:
  859. // Strip all suspicious characters from file path.
  860. $param = fix_utf8($param);
  861. $param = str_replace('\\', '/', $param);
  862. // Explode the path and clean each element using the PARAM_FILE rules.
  863. $breadcrumb = explode('/', $param);
  864. foreach ($breadcrumb as $key => $crumb) {
  865. if ($crumb === '.' && $key === 0) {
  866. // Special condition to allow for relative current path such as ./currentdirfile.txt.
  867. } else {
  868. $crumb = clean_param($crumb, PARAM_FILE);
  869. }
  870. $breadcrumb[$key] = $crumb;
  871. }
  872. $param = implode('/', $breadcrumb);
  873. // Remove multiple current path (./././) and multiple slashes (///).
  874. $param = preg_replace('~//+~', '/', $param);
  875. $param = preg_replace('~/(\./)+~', '/', $param);
  876. return $param;
  877. case PARAM_HOST:
  878. // Allow FQDN or IPv4 dotted quad.
  879. $param = preg_replace('/[^\.\d\w-]/', '', $param );
  880. // Match ipv4 dotted quad.
  881. if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
  882. // Confirm values are ok.
  883. if ( $match[0] > 255
  884. || $match[1] > 255
  885. || $match[3] > 255
  886. || $match[4] > 255 ) {
  887. // Hmmm, what kind of dotted quad is this?
  888. $param = '';
  889. }
  890. } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
  891. && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
  892. && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
  893. ) {
  894. // All is ok - $param is respected.
  895. } else {
  896. // All is not ok...
  897. $param='';
  898. }
  899. return $param;
  900. case PARAM_URL:
  901. // Allow safe urls.
  902. $param = fix_utf8($param);
  903. include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
  904. if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
  905. // All is ok, param is respected.
  906. } else {
  907. // Not really ok.
  908. $param ='';
  909. }
  910. return $param;
  911. case PARAM_LOCALURL:
  912. // Allow http absolute, root relative and relative URLs within wwwroot.
  913. $param = clean_param($param, PARAM_URL);
  914. if (!empty($param)) {
  915. if ($param === $CFG->wwwroot) {
  916. // Exact match;
  917. } else if (preg_match(':^/:', $param)) {
  918. // Root-relative, ok!
  919. } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
  920. // Absolute, and matches our wwwroot.
  921. } else {
  922. // Relative - let's make sure there are no tricks.
  923. if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
  924. // Looks ok.
  925. } else {
  926. $param = '';
  927. }
  928. }
  929. }
  930. return $param;
  931. case PARAM_PEM:
  932. $param = trim($param);
  933. // PEM formatted strings may contain letters/numbers and the symbols:
  934. // forward slash: /
  935. // plus sign: +
  936. // equal sign: =
  937. // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
  938. if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
  939. list($wholething, $body) = $matches;
  940. unset($wholething, $matches);
  941. $b64 = clean_param($body, PARAM_BASE64);
  942. if (!empty($b64)) {
  943. return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
  944. } else {
  945. return '';
  946. }
  947. }
  948. return '';
  949. case PARAM_BASE64:
  950. if (!empty($param)) {
  951. // PEM formatted strings may contain letters/numbers and the symbols
  952. // forward slash: /
  953. // plus sign: +
  954. // equal sign: =.
  955. if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
  956. return '';
  957. }
  958. $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
  959. // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
  960. // than (or equal to) 64 characters long.
  961. for ($i=0, $j=count($lines); $i < $j; $i++) {
  962. if ($i + 1 == $j) {
  963. if (64 < strlen($lines[$i])) {
  964. return '';
  965. }
  966. continue;
  967. }
  968. if (64 != strlen($lines[$i])) {
  969. return '';
  970. }
  971. }
  972. return implode("\n", $lines);
  973. } else {
  974. return '';
  975. }
  976. case PARAM_TAG:
  977. $param = fix_utf8($param);
  978. // Please note it is not safe to use the tag name directly anywhere,
  979. // it must be processed with s(), urlencode() before embedding anywhere.
  980. // Remove some nasties.
  981. $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
  982. // Convert many whitespace chars into one.
  983. $param = preg_replace('/\s+/u', ' ', $param);
  984. $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
  985. return $param;
  986. case PARAM_TAGLIST:
  987. $param = fix_utf8($param);
  988. $tags = explode(',', $param);
  989. $result = array();
  990. foreach ($tags as $tag) {
  991. $res = clean_param($tag, PARAM_TAG);
  992. if ($res !== '') {
  993. $result[] = $res;
  994. }
  995. }
  996. if ($result) {
  997. return implode(',', $result);
  998. } else {
  999. return '';
  1000. }
  1001. case PARAM_CAPABILITY:
  1002. if (get_capability_info($param)) {
  1003. return $param;
  1004. } else {
  1005. return '';
  1006. }
  1007. case PARAM_PERMISSION:
  1008. $param = (int)$param;
  1009. if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
  1010. return $param;
  1011. } else {
  1012. return CAP_INHERIT;
  1013. }
  1014. case PARAM_AUTH:
  1015. $param = clean_param($param, PARAM_PLUGIN);
  1016. if (empty($param)) {
  1017. return '';
  1018. } else if (exists_auth_plugin($param)) {
  1019. return $param;
  1020. } else {
  1021. return '';
  1022. }
  1023. case PARAM_LANG:
  1024. $param = clean_param($param, PARAM_SAFEDIR);
  1025. if (get_string_manager()->translation_exists($param)) {
  1026. return $param;
  1027. } else {
  1028. // Specified language is not installed or param malformed.
  1029. return '';
  1030. }
  1031. case PARAM_THEME:
  1032. $param = clean_param($param, PARAM_PLUGIN);
  1033. if (empty($param)) {
  1034. return '';
  1035. } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
  1036. return $param;
  1037. } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
  1038. return $param;
  1039. } else {
  1040. // Specified theme is not installed.
  1041. return '';
  1042. }
  1043. case PARAM_USERNAME:
  1044. $param = fix_utf8($param);
  1045. $param = trim($param);
  1046. // Convert uppercase to lowercase MDL-16919.
  1047. $param = core_text::strtolower($param);
  1048. if (empty($CFG->extendedusernamechars)) {
  1049. $param = str_replace(" " , "", $param);
  1050. // Regular expression, eliminate all chars EXCEPT:
  1051. // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
  1052. $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
  1053. }
  1054. return $param;
  1055. case PARAM_EMAIL:
  1056. $param = fix_utf8($param);
  1057. if (validate_email($param)) {
  1058. return $param;
  1059. } else {
  1060. return '';
  1061. }
  1062. case PARAM_STRINGID:
  1063. if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
  1064. return $param;
  1065. } else {
  1066. return '';
  1067. }
  1068. case PARAM_TIMEZONE:
  1069. // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
  1070. $param = fix_utf8($param);
  1071. $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
  1072. if (preg_match($timezonepattern, $param)) {
  1073. return $param;
  1074. } else {
  1075. return '';
  1076. }
  1077. default:
  1078. // Doh! throw error, switched parameters in optional_param or another serious problem.
  1079. print_error("unknownparamtype", '', '', $type);
  1080. }
  1081. }
  1082. /**
  1083. * Whether the PARAM_* type is compatible in RTL.
  1084. *
  1085. * Being compatible with RTL means that the data they contain can flow
  1086. * from right-to-left or left-to-right without compromising the user experience.
  1087. *
  1088. * Take URLs for example, they are not RTL compatible as they should always
  1089. * flow from the left to the right. This also applies to numbers, email addresses,
  1090. * configuration snippets, base64 strings, etc...
  1091. *
  1092. * This function tries to best guess which parameters can contain localised strings.
  1093. *
  1094. * @param string $paramtype Constant PARAM_*.
  1095. * @return bool
  1096. */
  1097. function is_rtl_compatible($paramtype) {
  1098. return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
  1099. }
  1100. /**
  1101. * Makes sure the data is using valid utf8, invalid characters are discarded.
  1102. *
  1103. * Note: this function is not intended for full objects with methods and private properties.
  1104. *
  1105. * @param mixed $value
  1106. * @return mixed with proper utf-8 encoding
  1107. */
  1108. function fix_utf8($value) {
  1109. if (is_null($value) or $value === '') {
  1110. return $value;
  1111. } else if (is_string($value)) {
  1112. if ((string)(int)$value === $value) {
  1113. // Shortcut.
  1114. return $value;
  1115. }
  1116. // No null bytes expected in our data, so let's remove it.
  1117. $value = str_replace("\0", '', $value);
  1118. // Note: this duplicates min_fix_utf8() intentionally.
  1119. static $buggyiconv = null;
  1120. if ($buggyiconv === null) {
  1121. $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
  1122. }
  1123. if ($buggyiconv) {
  1124. if (function_exists('mb_convert_encoding')) {
  1125. $subst = mb_substitute_character();
  1126. mb_substitute_character('none');
  1127. $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
  1128. mb_substitute_character($subst);
  1129. } else {
  1130. // Warn admins on admin/index.php page.
  1131. $result = $value;
  1132. }
  1133. } else {
  1134. $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
  1135. }
  1136. return $result;
  1137. } else if (is_array($value)) {
  1138. foreach ($value as $k => $v) {
  1139. $value[$k] = fix_utf8($v);
  1140. }
  1141. return $value;
  1142. } else if (is_object($value)) {
  1143. // Do not modify original.
  1144. $value = clone($value);
  1145. foreach ($value as $k => $v) {
  1146. $value->$k = fix_utf8($v);
  1147. }
  1148. return $value;
  1149. } else {
  1150. // This is some other type, no utf-8 here.
  1151. return $value;
  1152. }
  1153. }
  1154. /**
  1155. * Return true if given value is integer or string with integer value
  1156. *
  1157. * @param mixed $value String or Int
  1158. * @return bool true if number, false if not
  1159. */
  1160. function is_number($value) {
  1161. if (is_int($value)) {
  1162. return true;
  1163. } else if (is_string($value)) {
  1164. return ((string)(int)$value) === $value;
  1165. } else {
  1166. return false;
  1167. }
  1168. }
  1169. /**
  1170. * Returns host part from url.
  1171. *
  1172. * @param string $url full url
  1173. * @return string host, null if not found
  1174. */
  1175. function get_host_from_url($url) {
  1176. preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
  1177. if ($matches) {
  1178. return $matches[1];
  1179. }
  1180. return null;
  1181. }
  1182. /**
  1183. * Tests whether anything was returned by text editor
  1184. *
  1185. * This function is useful for testing whether something you got back from
  1186. * the HTML editor actually contains anything. Sometimes the HTML editor
  1187. * appear to be empty, but actually you get back a <br> tag or something.
  1188. *
  1189. * @param string $string a string containing HTML.
  1190. * @return boolean does the string contain any actual content - that is text,
  1191. * images, objects, etc.
  1192. */
  1193. function html_is_blank($string) {
  1194. return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
  1195. }
  1196. /**
  1197. * Set a key in global configuration
  1198. *
  1199. * Set a key/value pair in both this session's {@link $CFG} global variable
  1200. * and in the 'config' database table for future sessions.
  1201. *
  1202. * Can also be used to update keys for plugin-scoped configs in config_plugin table.
  1203. * In that case it doesn't affect $CFG.
  1204. *
  1205. * A NULL value will delete the entry.
  1206. *
  1207. * NOTE: this function is called from lib/db/upgrade.php
  1208. *
  1209. * @param string $name the key to set
  1210. * @param string $value the value to set (without magic quotes)
  1211. * @param string $plugin (optional) the plugin scope, default null
  1212. * @return bool true or exception
  1213. */
  1214. function set_config($name, $value, $plugin=null) {
  1215. global $CFG, $DB;
  1216. if (empty($plugin)) {
  1217. if (!array_key_exists($name, $CFG->config_php_settings)) {
  1218. // So it's defined for this invocation at least.
  1219. if (is_null($value)) {
  1220. unset($CFG->$name);
  1221. } else {
  1222. // Settings from db are always strings.
  1223. $CFG->$name = (string)$value;
  1224. }
  1225. }
  1226. if ($DB->get_field('config', 'name', array('name' => $name))) {
  1227. if ($value === null) {
  1228. $DB->delete_records('config', array('name' => $name));
  1229. } else {
  1230. $DB->set_field('config', 'value', $value, array('name' => $name));
  1231. }
  1232. } else {
  1233. if ($value !== null) {
  1234. $config = new stdClass();
  1235. $config->name = $name;
  1236. $config->value = $value;
  1237. $DB->insert_record('config', $config, false);
  1238. }
  1239. // When setting config during a Behat test (in the CLI script, not in the web browser
  1240. // requests), remember which ones are set so that we can clear them later.
  1241. if (defined('BEHAT_TEST')) {
  1242. if (!property_exists($CFG, 'behat_cli_added_config')) {
  1243. $CFG->behat_cli_added_config = [];
  1244. }
  1245. $CFG->behat_cli_added_config[$name] = true;
  1246. }
  1247. }
  1248. if ($name === 'siteidentifier') {
  1249. cache_helper::update_site_identifier($value);
  1250. }
  1251. cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
  1252. } else {
  1253. // Plugin scope.
  1254. if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
  1255. if ($value===null) {
  1256. $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
  1257. } else {
  1258. $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
  1259. }
  1260. } else {
  1261. if ($value !== null) {
  1262. $config = new stdClass();
  1263. $config->plugin = $plugin;
  1264. $config->name = $name;
  1265. $config->value = $value;
  1266. $DB->insert_record('config_plugins', $config, false);
  1267. }
  1268. }
  1269. cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
  1270. }
  1271. return true;
  1272. }
  1273. /**
  1274. * Get configuration values from the global config table
  1275. * or the config_plugins table.
  1276. *
  1277. * If called with one parameter, it will load all the config
  1278. * variables for one plugin, and return them as an object.
  1279. *
  1280. * If called with 2 parameters it will return a string single
  1281. * value or false if the value is not found.
  1282. *
  1283. * NOTE: this function is called from lib/db/upgrade.php
  1284. *
  1285. * @param string $plugin full component name
  1286. * @param string $name default null
  1287. * @return mixed hash-like object or single value, return false no config found
  1288. * @throws dml_exception
  1289. */
  1290. function get_config($plugin, $name = null) {
  1291. global $CFG, $DB;
  1292. if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
  1293. $forced =& $CFG->config_php_settings;
  1294. $iscore = true;
  1295. $plugin = 'core';
  1296. } else {
  1297. if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
  1298. $forced =& $CFG->forced_plugin_settings[$plugin];
  1299. } else {
  1300. $forced = array();
  1301. }
  1302. $iscore = false;
  1303. }
  1304. if (!isset($CFG->siteidentifier)) {
  1305. try {
  1306. // This may throw an exception during installation, which is how we detect the
  1307. // need to install the database. For more details see {@see initialise_cfg()}.
  1308. $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
  1309. } catch (dml_exception $ex) {
  1310. // Set siteidentifier to false. We don't want to trip this continually.
  1311. $siteidentifier = false;
  1312. throw $ex;
  1313. }
  1314. }
  1315. if (!empty($name)) {
  1316. if (array_key_exists($name, $forced)) {
  1317. return (string)$forced[$name];
  1318. } else if ($name === 'siteidentifier' && $plugin == 'core') {
  1319. return $CFG->siteidentifier;
  1320. }
  1321. }
  1322. $cache = cache::make('core', 'config');
  1323. $result = $cache->get($plugin);
  1324. if ($result === false) {
  1325. // The user is after a recordset.
  1326. if (!$iscore) {
  1327. $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
  1328. } else {
  1329. // This part is not really used any more, but anyway...
  1330. $result = $DB->get_records_menu('config', array(), '', 'name,value');;
  1331. }
  1332. $cache->set($plugin, $result);
  1333. }
  1334. if (!empty($name)) {
  1335. if (array_key_exists($name, $result)) {
  1336. return $result[$name];
  1337. }
  1338. return false;
  1339. }
  1340. if ($plugin === 'core') {
  1341. $result['siteidentifier'] = $CFG->siteidentifier;
  1342. }
  1343. foreach ($forced as $key => $value) {
  1344. if (is_null($value) or is_array($value) or is_object($value)) {
  1345. // We do not want any extra mess here, just real settings that could be saved in db.
  1346. unset($result[$key]);
  1347. } else {
  1348. // Convert to string as if it went through the DB.
  1349. $result[$key] = (string)$value;
  1350. }
  1351. }
  1352. return (object)$result;
  1353. }
  1354. /**
  1355. * Removes a key from global configuration.
  1356. *
  1357. * NOTE: this function is called from lib/db/upgrade.php
  1358. *
  1359. * @param string $name the key to set
  1360. * @param string $plugin (optional) the plugin scope
  1361. * @return boolean whether the operation succeeded.
  1362. */
  1363. function unset_config($name, $plugin=null) {
  1364. global $CFG, $DB;
  1365. if (empty($plugin)) {
  1366. unset($CFG->$name);
  1367. $DB->delete_records('config', array('name' => $name));
  1368. cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
  1369. } else {
  1370. $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
  1371. cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
  1372. }
  1373. return true;
  1374. }
  1375. /**
  1376. * Remove all the config variables for a given plugin.
  1377. *
  1378. * NOTE: this function is called from lib/db/upgrade.php
  1379. *
  1380. * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
  1381. * @return boolean whether the operation succeeded.
  1382. */
  1383. function unset_all_config_for_plugin($plugin) {
  1384. global $DB;
  1385. // Delete from the obvious config_plugins first.
  1386. $DB->delete_records('config_plugins', array('plugin' => $plugin));
  1387. // Next delete any suspect settings from config.
  1388. $like = $DB->sql_like('name', '?', true, true, false, '|');
  1389. $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
  1390. $DB->delete_records_select('config', $like, $params);
  1391. // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
  1392. cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
  1393. return true;
  1394. }
  1395. /**
  1396. * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
  1397. *
  1398. * All users are verified if they still have the necessary capability.
  1399. *
  1400. * @param string $value the value of the config setting.
  1401. * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
  1402. * @param bool $includeadmins include administrators.
  1403. * @return array of user objects.
  1404. */
  1405. function get_users_from_config($value, $capability, $includeadmins = true) {
  1406. if (empty($value) or $value === '$@NONE@$') {
  1407. return array();
  1408. }
  1409. // We have to make sure that users still have the necessary capability,
  1410. // it should be faster to fetch them all first and then test if they are present
  1411. // instead of validating them one-by-one.
  1412. $users = get_users_by_capability(context_system::instance(), $capability);
  1413. if ($includeadmins) {
  1414. $admins = get_admins();
  1415. foreach ($admins as $admin) {
  1416. $users[$admin->id] = $admin;
  1417. }
  1418. }
  1419. if ($value === '$@ALL@$') {
  1420. return $users;
  1421. }
  1422. $result = array(); // Result in correct order.
  1423. $allowed = explode(',', $value);
  1424. foreach ($allowed as $uid) {
  1425. if (isset($users[$uid])) {
  1426. $user = $users[$uid];
  1427. $result[$user->id] = $user;
  1428. }
  1429. }
  1430. return $result;
  1431. }
  1432. /**
  1433. * Invalidates browser caches and cached data in temp.
  1434. *
  1435. * @return void
  1436. */
  1437. function purge_all_caches() {
  1438. purge_caches();
  1439. }
  1440. /**
  1441. * Selectively invalidate different types of cache.
  1442. *
  1443. * Purges the cache areas specified. By default, this will purge all caches but can selectively purge specific
  1444. * areas alone or in combination.
  1445. *
  1446. * @param bool[] $options Specific parts of the cache to purge. Valid options are:
  1447. * 'muc' Purge MUC caches?
  1448. * 'theme' Purge theme cache?
  1449. * 'lang' Purge language string cache?
  1450. * 'js' Purge javascript cache?
  1451. * 'filter' Purge text filter cache?
  1452. * 'other' Purge all other caches?
  1453. */
  1454. function purge_caches($options = []) {
  1455. $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
  1456. if (empty(array_filter($options))) {
  1457. $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
  1458. } else {
  1459. $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
  1460. }
  1461. if ($options['muc']) {
  1462. cache_helper::purge_all();
  1463. }
  1464. if ($options['theme']) {
  1465. theme_reset_all_caches();
  1466. }
  1467. if ($options['lang']) {
  1468. get_string_manager()->reset_caches();
  1469. }
  1470. if ($options['js']) {
  1471. js_reset_all_caches();
  1472. }
  1473. if ($options['template']) {
  1474. template_reset_all_caches();
  1475. }
  1476. if ($options['filter']) {
  1477. reset_text_filters_cache();
  1478. }
  1479. if ($options['other']) {
  1480. purge_other_caches();
  1481. }
  1482. }
  1483. /**
  1484. * Purge all non-MUC caches not otherwise purged in purge_caches.
  1485. *
  1486. * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
  1487. * {@link phpunit_util::reset_dataroot()}
  1488. */
  1489. function purge_other_caches() {
  1490. global $DB, $CFG;
  1491. if (class_exists('core_plugin_manager')) {
  1492. core_plugin_manager::reset_caches();
  1493. }
  1494. // Bump up cacherev field for all courses.
  1495. try {
  1496. increment_revision_number('course', 'cacherev', '');
  1497. } catch (moodle_exception $e) {
  1498. // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
  1499. }
  1500. $DB->reset_caches();
  1501. // Purge all other caches: rss, simplepie, etc.
  1502. clearstatcache();
  1503. remove_dir($CFG->cachedir.'', true);
  1504. // Make sure cache dir is writable, throws exception if not.
  1505. make_cache_directory('');
  1506. // This is the only place where we purge local caches, we are only adding files there.
  1507. // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
  1508. remove_dir($CFG->localcachedir, true);
  1509. set_config('localcachedirpurged', time());
  1510. make_localcache_directory('', true);
  1511. \core\task\manager::clear_static_caches();
  1512. }
  1513. /**
  1514. * Get volatile flags
  1515. *
  1516. * @param string $type
  1517. * @param int $changedsince default null
  1518. * @return array records array
  1519. */
  1520. function get_cache_flags($type, $changedsince = null) {
  1521. global $DB;
  1522. $params = array('type' => $type, 'expiry' => time());
  1523. $sqlwhere = "flagtype = :type AND expiry >= :expiry";
  1524. if ($changedsince !== null) {
  1525. $params['changedsince'] = $changedsince;
  1526. $sqlwhere .= " AND timemodified > :changedsince";
  1527. }
  1528. $cf = array();
  1529. if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
  1530. foreach ($flags as $flag) {
  1531. $cf[$flag->name] = $flag->value;
  1532. }
  1533. }
  1534. return $cf;
  1535. }
  1536. /**
  1537. * Get volatile flags
  1538. *
  1539. * @param string $type
  1540. * @param string $name
  1541. * @param int $changedsince default null
  1542. * @return string|false The cache flag value or false
  1543. */
  1544. function get_cache_flag($type, $name, $changedsince=null) {
  1545. global $DB;
  1546. $params = array('type' => $type, 'name' => $name, 'expiry' => time());
  1547. $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
  1548. if ($changedsince !== null) {
  1549. $params['changedsince'] = $changedsince;
  1550. $sqlwhere .= " AND timemodified > :changedsince";
  1551. }
  1552. return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
  1553. }
  1554. /**
  1555. * Set a volatile flag
  1556. *
  1557. * @param string $type the "type" namespace for the key
  1558. * @param string $name the key to set
  1559. * @param string $value the value to set (without magic quotes) - null will remove the flag
  1560. * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
  1561. * @return bool Always returns true
  1562. */
  1563. function set_cache_flag($type, $name, $value, $expiry = null) {
  1564. global $DB;
  1565. $timemodified = time();
  1566. if ($expiry === null || $expiry < $timemodified) {
  1567. $expiry = $timemodified + 24 * 60 * 60;
  1568. } else {
  1569. $expiry = (int)$expiry;
  1570. }
  1571. if ($value === null) {
  1572. unset_cache_flag($type, $name);
  1573. return true;
  1574. }
  1575. if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
  1576. // This is a potential problem in DEBUG_DEVELOPER.
  1577. if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
  1578. return true; // No need to update.
  1579. }
  1580. $f->value = $value;
  1581. $f->expiry = $expiry;
  1582. $f->timemodified = $timemodified;
  1583. $DB->update_record('cache_flags', $f);
  1584. } else {
  1585. $f = new stdClass();
  1586. $f->flagtype = $type;
  1587. $f->name = $name;
  1588. $f->value = $value;
  1589. $f->expiry = $expiry;
  1590. $f->timemodified = $timemodified;
  1591. $DB->insert_record('cache_flags', $f);
  1592. }
  1593. return true;
  1594. }
  1595. /**
  1596. * Removes a single volatile flag
  1597. *
  1598. * @param string $type the "type" namespace for the key
  1599. * @param string $name the key to set
  1600. * @return bool
  1601. */
  1602. function unset_cache_flag($type, $name) {
  1603. global $DB;
  1604. $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
  1605. return true;
  1606. }
  1607. /**
  1608. * Garbage-collect volatile flags
  1609. *
  1610. * @return bool Always returns true
  1611. */
  1612. function gc_cache_flags() {
  1613. global $DB;
  1614. $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
  1615. return true;
  1616. }
  1617. // USER PREFERENCE API.
  1618. /**
  1619. * Refresh user preference cache. This is used most often for $USER
  1620. * object that is stored in session, but it also helps with performance in cron script.
  1621. *
  1622. * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
  1623. *
  1624. * @package core
  1625. * @category preference
  1626. * @access public
  1627. * @param stdClass $user User object. Preferences are preloaded into 'preference' property
  1628. * @param int $cachelifetime Cache life time on the current page (in seconds)
  1629. * @throws coding_exception
  1630. * @return null
  1631. */
  1632. function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
  1633. global $DB;
  1634. // Static cache, we need to check on each page load, not only every 2 minutes.
  1635. static $loadedusers = array();
  1636. if (!isset($user->id)) {
  1637. throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
  1638. }
  1639. if (empty($user->id) or isguestuser($user->id)) {
  1640. // No permanent storage for not-logged-in users and guest.
  1641. if (!isset($user->preference)) {
  1642. $user->preference = array();
  1643. }
  1644. return;
  1645. }
  1646. $timenow = time();
  1647. if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
  1648. // Already loaded at least once on this page. Are we up to date?
  1649. if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
  1650. // No need to reload - we are on the same page and we loaded prefs just a moment ago.
  1651. return;
  1652. } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
  1653. // No change since the lastcheck on this page.
  1654. $user->preference['_lastloaded'] = $timenow;
  1655. return;
  1656. }
  1657. }
  1658. // OK, so we have to reload all preferences.
  1659. $loadedusers[$user->id] = true;
  1660. $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
  1661. $user->preference['_lastloaded'] = $timenow;
  1662. }
  1663. /**
  1664. * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
  1665. *
  1666. * NOTE: internal function, do not call from other code.
  1667. *
  1668. * @package core
  1669. * @access private
  1670. * @param integer $userid the user whose prefs were changed.
  1671. */
  1672. function mark_user_preferences_changed($userid) {
  1673. global $CFG;
  1674. if (empty($userid) or isguestuser($userid)) {
  1675. // No cache flags for guest and not-logged-in users.
  1676. return;
  1677. }
  1678. set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
  1679. }
  1680. /**
  1681. * Sets a preference for the specified user.
  1682. *
  1683. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1684. *
  1685. * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
  1686. *
  1687. * @package core
  1688. * @category preference
  1689. * @access public
  1690. * @param string $name The key to set as preference for the specified user
  1691. * @param string $value The value to set for the $name key in the specified user's
  1692. * record, null means delete current value.
  1693. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1694. * @throws coding_exception
  1695. * @return bool Always true or exception
  1696. */
  1697. function set_user_preference($name, $value, $user = null) {
  1698. global $USER, $DB;
  1699. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1700. throw new coding_exception('Invalid preference name in set_user_preference() call');
  1701. }
  1702. if (is_null($value)) {
  1703. // Null means delete current.
  1704. return unset_user_preference($name, $user);
  1705. } else if (is_object($value)) {
  1706. throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
  1707. } else if (is_array($value)) {
  1708. throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
  1709. }
  1710. // Value column maximum length is 1333 characters.
  1711. $value = (string)$value;
  1712. if (core_text::strlen($value) > 1333) {
  1713. throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
  1714. }
  1715. if (is_null($user)) {
  1716. $user = $USER;
  1717. } else if (isset($user->id)) {
  1718. // It is a valid object.
  1719. } else if (is_numeric($user)) {
  1720. $user = (object)array('id' => (int)$user);
  1721. } else {
  1722. throw new coding_exception('Invalid $user parameter in set_user_preference() call');
  1723. }
  1724. check_user_preferences_loaded($user);
  1725. if (empty($user->id) or isguestuser($user->id)) {
  1726. // No permanent storage for not-logged-in users and guest.
  1727. $user->preference[$name] = $value;
  1728. return true;
  1729. }
  1730. if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
  1731. if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
  1732. // Preference already set to this value.
  1733. return true;
  1734. }
  1735. $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
  1736. } else {
  1737. $preference = new stdClass();
  1738. $preference->userid = $user->id;
  1739. $preference->name = $name;
  1740. $preference->value = $value;
  1741. $DB->insert_record('user_preferences', $preference);
  1742. }
  1743. // Update value in cache.
  1744. $user->preference[$name] = $value;
  1745. // Update the $USER in case where we've not a direct reference to $USER.
  1746. if ($user !== $USER && $user->id == $USER->id) {
  1747. $USER->preference[$name] = $value;
  1748. }
  1749. // Set reload flag for other sessions.
  1750. mark_user_preferences_changed($user->id);
  1751. return true;
  1752. }
  1753. /**
  1754. * Sets a whole array of preferences for the current user
  1755. *
  1756. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1757. *
  1758. * @package core
  1759. * @category preference
  1760. * @access public
  1761. * @param array $prefarray An array of key/value pairs to be set
  1762. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1763. * @return bool Always true or exception
  1764. */
  1765. function set_user_preferences(array $prefarray, $user = null) {
  1766. foreach ($prefarray as $name => $value) {
  1767. set_user_preference($name, $value, $user);
  1768. }
  1769. return true;
  1770. }
  1771. /**
  1772. * Unsets a preference completely by deleting it from the database
  1773. *
  1774. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1775. *
  1776. * @package core
  1777. * @category preference
  1778. * @access public
  1779. * @param string $name The key to unset as preference for the specified user
  1780. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1781. * @throws coding_exception
  1782. * @return bool Always true or exception
  1783. */
  1784. function unset_user_preference($name, $user = null) {
  1785. global $USER, $DB;
  1786. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1787. throw new coding_exception('Invalid preference name in unset_user_preference() call');
  1788. }
  1789. if (is_null($user)) {
  1790. $user = $USER;
  1791. } else if (isset($user->id)) {
  1792. // It is a valid object.
  1793. } else if (is_numeric($user)) {
  1794. $user = (object)array('id' => (int)$user);
  1795. } else {
  1796. throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
  1797. }
  1798. check_user_preferences_loaded($user);
  1799. if (empty($user->id) or isguestuser($user->id)) {
  1800. // No permanent storage for not-logged-in user and guest.
  1801. unset($user->preference[$name]);
  1802. return true;
  1803. }
  1804. // Delete from DB.
  1805. $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
  1806. // Delete the preference from cache.
  1807. unset($user->preference[$name]);
  1808. // Update the $USER in case where we've not a direct reference to $USER.
  1809. if ($user !== $USER && $user->id == $USER->id) {
  1810. unset($USER->preference[$name]);
  1811. }
  1812. // Set reload flag for other sessions.
  1813. mark_user_preferences_changed($user->id);
  1814. return true;
  1815. }
  1816. /**
  1817. * Used to fetch user preference(s)
  1818. *
  1819. * If no arguments are supplied this function will return
  1820. * all of the current user preferences as an array.
  1821. *
  1822. * If a name is specified then this function
  1823. * attempts to return that particular preference value. If
  1824. * none is found, then the optional value $default is returned,
  1825. * otherwise null.
  1826. *
  1827. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1828. *
  1829. * @package core
  1830. * @category preference
  1831. * @access public
  1832. * @param string $name Name of the key to use in finding a preference value
  1833. * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
  1834. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1835. * @throws coding_exception
  1836. * @return string|mixed|null A string containing the value of a single preference. An
  1837. * array with all of the preferences or null
  1838. */
  1839. function get_user_preferences($name = null, $default = null, $user = null) {
  1840. global $USER;
  1841. if (is_null($name)) {
  1842. // All prefs.
  1843. } else if (is_numeric($name) or $name === '_lastloaded') {
  1844. throw new coding_exception('Invalid preference name in get_user_preferences() call');
  1845. }
  1846. if (is_null($user)) {
  1847. $user = $USER;
  1848. } else if (isset($user->id)) {
  1849. // Is a valid object.
  1850. } else if (is_numeric($user)) {
  1851. if ($USER->id == $user) {
  1852. $user = $USER;
  1853. } else {
  1854. $user = (object)array('id' => (int)$user);
  1855. }
  1856. } else {
  1857. throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
  1858. }
  1859. check_user_preferences_loaded($user);
  1860. if (empty($name)) {
  1861. // All values.
  1862. return $user->preference;
  1863. } else if (isset($user->preference[$name])) {
  1864. // The single string value.
  1865. return $user->preference[$name];
  1866. } else {
  1867. // Default value (null if not specified).
  1868. return $default;
  1869. }
  1870. }
  1871. // FUNCTIONS FOR HANDLING TIME.
  1872. /**
  1873. * Given Gregorian date parts in user time produce a GMT timestamp.
  1874. *
  1875. * @package core
  1876. * @category time
  1877. * @param int $year The year part to create timestamp of
  1878. * @param int $month The month part to create timestamp of
  1879. * @param int $day The day part to create timestamp of
  1880. * @param int $hour The hour part to create timestamp of
  1881. * @param int $minute The minute part to create timestamp of
  1882. * @param int $second The second part to create timestamp of
  1883. * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
  1884. * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1885. * @param bool $applydst Toggle Daylight Saving Time, default true, will be
  1886. * applied only if timezone is 99 or string.
  1887. * @return int GMT timestamp
  1888. */
  1889. function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
  1890. $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
  1891. $date->setDate((int)$year, (int)$month, (int)$day);
  1892. $date->setTime((int)$hour, (int)$minute, (int)$second);
  1893. $time = $date->getTimestamp();
  1894. if ($time === false) {
  1895. throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
  1896. ' This can fail if year is more than 2038 and OS is 32 bit windows');
  1897. }
  1898. // Moodle BC DST stuff.
  1899. if (!$applydst) {
  1900. $time += dst_offset_on($time, $timezone);
  1901. }
  1902. return $time;
  1903. }
  1904. /**
  1905. * Format a date/time (seconds) as weeks, days, hours etc as needed
  1906. *
  1907. * Given an amount of time in seconds, returns string
  1908. * formatted nicely as years, days, hours etc as needed
  1909. *
  1910. * @package core
  1911. * @category time
  1912. * @uses MINSECS
  1913. * @uses HOURSECS
  1914. * @uses DAYSECS
  1915. * @uses YEARSECS
  1916. * @param int $totalsecs Time in seconds
  1917. * @param stdClass $str Should be a time object
  1918. * @return string A nicely formatted date/time string
  1919. */
  1920. function format_time($totalsecs, $str = null) {
  1921. $totalsecs = abs($totalsecs);
  1922. if (!$str) {
  1923. // Create the str structure the slow way.
  1924. $str = new stdClass();
  1925. $str->day = get_string('day');
  1926. $str->days = get_string('days');
  1927. $str->hour = get_string('hour');
  1928. $str->hours = get_string('hours');
  1929. $str->min = get_string('min');
  1930. $str->mins = get_string('mins');
  1931. $str->sec = get_string('sec');
  1932. $str->secs = get_string('secs');
  1933. $str->year = get_string('year');
  1934. $str->years = get_string('years');
  1935. }
  1936. $years = floor($totalsecs/YEARSECS);
  1937. $remainder = $totalsecs - ($years*YEARSECS);
  1938. $days = floor($remainder/DAYSECS);
  1939. $remainder = $totalsecs - ($days*DAYSECS);
  1940. $hours = floor($remainder/HOURSECS);
  1941. $remainder = $remainder - ($hours*HOURSECS);
  1942. $mins = floor($remainder/MINSECS);
  1943. $secs = $remainder - ($mins*MINSECS);
  1944. $ss = ($secs == 1) ? $str->sec : $str->secs;
  1945. $sm = ($mins == 1) ? $str->min : $str->mins;
  1946. $sh = ($hours == 1) ? $str->hour : $str->hours;
  1947. $sd = ($days == 1) ? $str->day : $str->days;
  1948. $sy = ($years == 1) ? $str->year : $str->years;
  1949. $oyears = '';
  1950. $odays = '';
  1951. $ohours = '';
  1952. $omins = '';
  1953. $osecs = '';
  1954. if ($years) {
  1955. $oyears = $years .' '. $sy;
  1956. }
  1957. if ($days) {
  1958. $odays = $days .' '. $sd;
  1959. }
  1960. if ($hours) {
  1961. $ohours = $hours .' '. $sh;
  1962. }
  1963. if ($mins) {
  1964. $omins = $mins .' '. $sm;
  1965. }
  1966. if ($secs) {
  1967. $osecs = $secs .' '. $ss;
  1968. }
  1969. if ($years) {
  1970. return trim($oyears .' '. $odays);
  1971. }
  1972. if ($days) {
  1973. return trim($odays .' '. $ohours);
  1974. }
  1975. if ($hours) {
  1976. return trim($ohours .' '. $omins);
  1977. }
  1978. if ($mins) {
  1979. return trim($omins .' '. $osecs);
  1980. }
  1981. if ($secs) {
  1982. return $osecs;
  1983. }
  1984. return get_string('now');
  1985. }
  1986. /**
  1987. * Returns a formatted string that represents a date in user time.
  1988. *
  1989. * @package core
  1990. * @category time
  1991. * @param int $date the timestamp in UTC, as obtained from the database.
  1992. * @param string $format strftime format. You should probably get this using
  1993. * get_string('strftime...', 'langconfig');
  1994. * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
  1995. * not 99 then daylight saving will not be added.
  1996. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1997. * @param bool $fixday If true (default) then the leading zero from %d is removed.
  1998. * If false then the leading zero is maintained.
  1999. * @param bool $fixhour If true (default) then the leading zero from %I is removed.
  2000. * @return string the formatted date/time.
  2001. */
  2002. function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
  2003. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2004. return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
  2005. }
  2006. /**
  2007. * Returns a html "time" tag with both the exact user date with timezone information
  2008. * as a datetime attribute in the W3C format, and the user readable date and time as text.
  2009. *
  2010. * @package core
  2011. * @category time
  2012. * @param int $date the timestamp in UTC, as obtained from the database.
  2013. * @param string $format strftime format. You should probably get this using
  2014. * get_string('strftime...', 'langconfig');
  2015. * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
  2016. * not 99 then daylight saving will not be added.
  2017. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2018. * @param bool $fixday If true (default) then the leading zero from %d is removed.
  2019. * If false then the leading zero is maintained.
  2020. * @param bool $fixhour If true (default) then the leading zero from %I is removed.
  2021. * @return string the formatted date/time.
  2022. */
  2023. function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
  2024. $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
  2025. if (CLI_SCRIPT && !PHPUNIT_TEST) {
  2026. return $userdatestr;
  2027. }
  2028. $machinedate = new DateTime();
  2029. $machinedate->setTimestamp(intval($date));
  2030. $machinedate->setTimezone(core_date::get_user_timezone_object());
  2031. return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
  2032. }
  2033. /**
  2034. * Returns a formatted date ensuring it is UTF-8.
  2035. *
  2036. * If we are running under Windows convert to Windows encoding and then back to UTF-8
  2037. * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
  2038. *
  2039. * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
  2040. * @param string $format strftime format.
  2041. * @param int|float|string $tz the user timezone
  2042. * @return string the formatted date/time.
  2043. * @since Moodle 2.3.3
  2044. */
  2045. function date_format_string($date, $format, $tz = 99) {
  2046. global $CFG;
  2047. $localewincharset = null;
  2048. // Get the calendar type user is using.
  2049. if ($CFG->ostype == 'WINDOWS') {
  2050. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2051. $localewincharset = $calendartype->locale_win_charset();
  2052. }
  2053. if ($localewincharset) {
  2054. $format = core_text::convert($format, 'utf-8', $localewincharset);
  2055. }
  2056. date_default_timezone_set(core_date::get_user_timezone($tz));
  2057. $datestring = strftime($format, $date);
  2058. core_date::set_default_server_timezone();
  2059. if ($localewincharset) {
  2060. $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
  2061. }
  2062. return $datestring;
  2063. }
  2064. /**
  2065. * Given a $time timestamp in GMT (seconds since epoch),
  2066. * returns an array that represents the Gregorian date in user time
  2067. *
  2068. * @package core
  2069. * @category time
  2070. * @param int $time Timestamp in GMT
  2071. * @param float|int|string $timezone user timezone
  2072. * @return array An array that represents the date in user time
  2073. */
  2074. function usergetdate($time, $timezone=99) {
  2075. if ($time === null) {
  2076. // PHP8 and PHP7 return different results when getdate(null) is called.
  2077. // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
  2078. // In the future versions of Moodle we may consider adding a strict typehint.
  2079. debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
  2080. $time = 0;
  2081. }
  2082. date_default_timezone_set(core_date::get_user_timezone($timezone));
  2083. $result = getdate($time);
  2084. core_date::set_default_server_timezone();
  2085. return $result;
  2086. }
  2087. /**
  2088. * Given a GMT timestamp (seconds since epoch), offsets it by
  2089. * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
  2090. *
  2091. * NOTE: this function does not include DST properly,
  2092. * you should use the PHP date stuff instead!
  2093. *
  2094. * @package core
  2095. * @category time
  2096. * @param int $date Timestamp in GMT
  2097. * @param float|int|string $timezone user timezone
  2098. * @return int
  2099. */
  2100. function usertime($date, $timezone=99) {
  2101. $userdate = new DateTime('@' . $date);
  2102. $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
  2103. $dst = dst_offset_on($date, $timezone);
  2104. return $date - $userdate->getOffset() + $dst;
  2105. }
  2106. /**
  2107. * Get a formatted string representation of an interval between two unix timestamps.
  2108. *
  2109. * E.g.
  2110. * $intervalstring = get_time_interval_string(12345600, 12345660);
  2111. * Will produce the string:
  2112. * '0d 0h 1m'
  2113. *
  2114. * @param int $time1 unix timestamp
  2115. * @param int $time2 unix timestamp
  2116. * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
  2117. * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
  2118. */
  2119. function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
  2120. $dtdate = new DateTime();
  2121. $dtdate->setTimeStamp($time1);
  2122. $dtdate2 = new DateTime();
  2123. $dtdate2->setTimeStamp($time2);
  2124. $interval = $dtdate2->diff($dtdate);
  2125. $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
  2126. return $interval->format($format);
  2127. }
  2128. /**
  2129. * Given a time, return the GMT timestamp of the most recent midnight
  2130. * for the current user.
  2131. *
  2132. * @package core
  2133. * @category time
  2134. * @param int $date Timestamp in GMT
  2135. * @param float|int|string $timezone user timezone
  2136. * @return int Returns a GMT timestamp
  2137. */
  2138. function usergetmidnight($date, $timezone=99) {
  2139. $userdate = usergetdate($date, $timezone);
  2140. // Time of midnight of this user's day, in GMT.
  2141. return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
  2142. }
  2143. /**
  2144. * Returns a string that prints the user's timezone
  2145. *
  2146. * @package core
  2147. * @category time
  2148. * @param float|int|string $timezone user timezone
  2149. * @return string
  2150. */
  2151. function usertimezone($timezone=99) {
  2152. $tz = core_date::get_user_timezone($timezone);
  2153. return core_date::get_localised_timezone($tz);
  2154. }
  2155. /**
  2156. * Returns a float or a string which denotes the user's timezone
  2157. * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
  2158. * means that for this timezone there are also DST rules to be taken into account
  2159. * Checks various settings and picks the most dominant of those which have a value
  2160. *
  2161. * @package core
  2162. * @category time
  2163. * @param float|int|string $tz timezone to calculate GMT time offset before
  2164. * calculating user timezone, 99 is default user timezone
  2165. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2166. * @return float|string
  2167. */
  2168. function get_user_timezone($tz = 99) {
  2169. global $USER, $CFG;
  2170. $timezones = array(
  2171. $tz,
  2172. isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
  2173. isset($USER->timezone) ? $USER->timezone : 99,
  2174. isset($CFG->timezone) ? $CFG->timezone : 99,
  2175. );
  2176. $tz = 99;
  2177. // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
  2178. foreach ($timezones as $nextvalue) {
  2179. if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
  2180. $tz = $nextvalue;
  2181. }
  2182. }
  2183. return is_numeric($tz) ? (float) $tz : $tz;
  2184. }
  2185. /**
  2186. * Calculates the Daylight Saving Offset for a given date/time (timestamp)
  2187. * - Note: Daylight saving only works for string timezones and not for float.
  2188. *
  2189. * @package core
  2190. * @category time
  2191. * @param int $time must NOT be compensated at all, it has to be a pure timestamp
  2192. * @param int|float|string $strtimezone user timezone
  2193. * @return int
  2194. */
  2195. function dst_offset_on($time, $strtimezone = null) {
  2196. $tz = core_date::get_user_timezone($strtimezone);
  2197. $date = new DateTime('@' . $time);
  2198. $date->setTimezone(new DateTimeZone($tz));
  2199. if ($date->format('I') == '1') {
  2200. if ($tz === 'Australia/Lord_Howe') {
  2201. return 1800;
  2202. }
  2203. return 3600;
  2204. }
  2205. return 0;
  2206. }
  2207. /**
  2208. * Calculates when the day appears in specific month
  2209. *
  2210. * @package core
  2211. * @category time
  2212. * @param int $startday starting day of the month
  2213. * @param int $weekday The day when week starts (normally taken from user preferences)
  2214. * @param int $month The month whose day is sought
  2215. * @param int $year The year of the month whose day is sought
  2216. * @return int
  2217. */
  2218. function find_day_in_month($startday, $weekday, $month, $year) {
  2219. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2220. $daysinmonth = days_in_month($month, $year);
  2221. $daysinweek = count($calendartype->get_weekdays());
  2222. if ($weekday == -1) {
  2223. // Don't care about weekday, so return:
  2224. // abs($startday) if $startday != -1
  2225. // $daysinmonth otherwise.
  2226. return ($startday == -1) ? $daysinmonth : abs($startday);
  2227. }
  2228. // From now on we 're looking for a specific weekday.
  2229. // Give "end of month" its actual value, since we know it.
  2230. if ($startday == -1) {
  2231. $startday = -1 * $daysinmonth;
  2232. }
  2233. // Starting from day $startday, the sign is the direction.
  2234. if ($startday < 1) {
  2235. $startday = abs($startday);
  2236. $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
  2237. // This is the last such weekday of the month.
  2238. $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
  2239. if ($lastinmonth > $daysinmonth) {
  2240. $lastinmonth -= $daysinweek;
  2241. }
  2242. // Find the first such weekday <= $startday.
  2243. while ($lastinmonth > $startday) {
  2244. $lastinmonth -= $daysinweek;
  2245. }
  2246. return $lastinmonth;
  2247. } else {
  2248. $indexweekday = dayofweek($startday, $month, $year);
  2249. $diff = $weekday - $indexweekday;
  2250. if ($diff < 0) {
  2251. $diff += $daysinweek;
  2252. }
  2253. // This is the first such weekday of the month equal to or after $startday.
  2254. $firstfromindex = $startday + $diff;
  2255. return $firstfromindex;
  2256. }
  2257. }
  2258. /**
  2259. * Calculate the number of days in a given month
  2260. *
  2261. * @package core
  2262. * @category time
  2263. * @param int $month The month whose day count is sought
  2264. * @param int $year The year of the month whose day count is sought
  2265. * @return int
  2266. */
  2267. function days_in_month($month, $year) {
  2268. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2269. return $calendartype->get_num_days_in_month($year, $month);
  2270. }
  2271. /**
  2272. * Calculate the position in the week of a specific calendar day
  2273. *
  2274. * @package core
  2275. * @category time
  2276. * @param int $day The day of the date whose position in the week is sought
  2277. * @param int $month The month of the date whose position in the week is sought
  2278. * @param int $year The year of the date whose position in the week is sought
  2279. * @return int
  2280. */
  2281. function dayofweek($day, $month, $year) {
  2282. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2283. return $calendartype->get_weekday($year, $month, $day);
  2284. }
  2285. // USER AUTHENTICATION AND LOGIN.
  2286. /**
  2287. * Returns full login url.
  2288. *
  2289. * Any form submissions for authentication to this URL must include username,
  2290. * password as well as a logintoken generated by \core\session\manager::get_login_token().
  2291. *
  2292. * @return string login url
  2293. */
  2294. function get_login_url() {
  2295. global $CFG;
  2296. return "$CFG->wwwroot/login/index.php";
  2297. }
  2298. /**
  2299. * This function checks that the current user is logged in and has the
  2300. * required privileges
  2301. *
  2302. * This function checks that the current user is logged in, and optionally
  2303. * whether they are allowed to be in a particular course and view a particular
  2304. * course module.
  2305. * If they are not logged in, then it redirects them to the site login unless
  2306. * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
  2307. * case they are automatically logged in as guests.
  2308. * If $courseid is given and the user is not enrolled in that course then the
  2309. * user is redirected to the course enrolment page.
  2310. * If $cm is given and the course module is hidden and the user is not a teacher
  2311. * in the course then the user is redirected to the course home page.
  2312. *
  2313. * When $cm parameter specified, this function sets page layout to 'module'.
  2314. * You need to change it manually later if some other layout needed.
  2315. *
  2316. * @package core_access
  2317. * @category access
  2318. *
  2319. * @param mixed $courseorid id of the course or course object
  2320. * @param bool $autologinguest default true
  2321. * @param object $cm course module object
  2322. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  2323. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  2324. * in order to keep redirects working properly. MDL-14495
  2325. * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
  2326. * @return mixed Void, exit, and die depending on path
  2327. * @throws coding_exception
  2328. * @throws require_login_exception
  2329. * @throws moodle_exception
  2330. */
  2331. function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
  2332. global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
  2333. // Must not redirect when byteserving already started.
  2334. if (!empty($_SERVER['HTTP_RANGE'])) {
  2335. $preventredirect = true;
  2336. }
  2337. if (AJAX_SCRIPT) {
  2338. // We cannot redirect for AJAX scripts either.
  2339. $preventredirect = true;
  2340. }
  2341. // Setup global $COURSE, themes, language and locale.
  2342. if (!empty($courseorid)) {
  2343. if (is_object($courseorid)) {
  2344. $course = $courseorid;
  2345. } else if ($courseorid == SITEID) {
  2346. $course = clone($SITE);
  2347. } else {
  2348. $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
  2349. }
  2350. if ($cm) {
  2351. if ($cm->course != $course->id) {
  2352. throw new coding_exception('course and cm parameters in require_login() call do not match!!');
  2353. }
  2354. // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
  2355. if (!($cm instanceof cm_info)) {
  2356. // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
  2357. // db queries so this is not really a performance concern, however it is obviously
  2358. // better if you use get_fast_modinfo to get the cm before calling this.
  2359. $modinfo = get_fast_modinfo($course);
  2360. $cm = $modinfo->get_cm($cm->id);
  2361. }
  2362. }
  2363. } else {
  2364. // Do not touch global $COURSE via $PAGE->set_course(),
  2365. // the reasons is we need to be able to call require_login() at any time!!
  2366. $course = $SITE;
  2367. if ($cm) {
  2368. throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
  2369. }
  2370. }
  2371. // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
  2372. // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
  2373. // risk leading the user back to the AJAX request URL.
  2374. if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
  2375. $setwantsurltome = false;
  2376. }
  2377. // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
  2378. if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
  2379. if ($preventredirect) {
  2380. throw new require_login_session_timeout_exception();
  2381. } else {
  2382. if ($setwantsurltome) {
  2383. $SESSION->wantsurl = qualified_me();
  2384. }
  2385. redirect(get_login_url());
  2386. }
  2387. }
  2388. // If the user is not even logged in yet then make sure they are.
  2389. if (!isloggedin()) {
  2390. if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
  2391. if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
  2392. // Misconfigured site guest, just redirect to login page.
  2393. redirect(get_login_url());
  2394. exit; // Never reached.
  2395. }
  2396. $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
  2397. complete_user_login($guest);
  2398. $USER->autologinguest = true;
  2399. $SESSION->lang = $lang;
  2400. } else {
  2401. // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
  2402. if ($preventredirect) {
  2403. throw new require_login_exception('You are not logged in');
  2404. }
  2405. if ($setwantsurltome) {
  2406. $SESSION->wantsurl = qualified_me();
  2407. }
  2408. $referer = get_local_referer(false);
  2409. if (!empty($referer)) {
  2410. $SESSION->fromurl = $referer;
  2411. }
  2412. // Give auth plugins an opportunity to authenticate or redirect to an external login page
  2413. $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
  2414. foreach($authsequence as $authname) {
  2415. $authplugin = get_auth_plugin($authname);
  2416. $authplugin->pre_loginpage_hook();
  2417. if (isloggedin()) {
  2418. if ($cm) {
  2419. $modinfo = get_fast_modinfo($course);
  2420. $cm = $modinfo->get_cm($cm->id);
  2421. }
  2422. set_access_log_user();
  2423. break;
  2424. }
  2425. }
  2426. // If we're still not logged in then go to the login page
  2427. if (!isloggedin()) {
  2428. redirect(get_login_url());
  2429. exit; // Never reached.
  2430. }
  2431. }
  2432. }
  2433. // Loginas as redirection if needed.
  2434. if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
  2435. if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
  2436. if ($USER->loginascontext->instanceid != $course->id) {
  2437. print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
  2438. }
  2439. }
  2440. }
  2441. // Check whether the user should be changing password (but only if it is REALLY them).
  2442. if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
  2443. $userauth = get_auth_plugin($USER->auth);
  2444. if ($userauth->can_change_password() and !$preventredirect) {
  2445. if ($setwantsurltome) {
  2446. $SESSION->wantsurl = qualified_me();
  2447. }
  2448. if ($changeurl = $userauth->change_password_url()) {
  2449. // Use plugin custom url.
  2450. redirect($changeurl);
  2451. } else {
  2452. // Use moodle internal method.
  2453. redirect($CFG->wwwroot .'/login/change_password.php');
  2454. }
  2455. } else if ($userauth->can_change_password()) {
  2456. throw new moodle_exception('forcepasswordchangenotice');
  2457. } else {
  2458. throw new moodle_exception('nopasswordchangeforced', 'auth');
  2459. }
  2460. }
  2461. // Check that the user account is properly set up. If we can't redirect to
  2462. // edit their profile and this is not a WS request, perform just the lax check.
  2463. // It will allow them to use filepicker on the profile edit page.
  2464. if ($preventredirect && !WS_SERVER) {
  2465. $usernotfullysetup = user_not_fully_set_up($USER, false);
  2466. } else {
  2467. $usernotfullysetup = user_not_fully_set_up($USER, true);
  2468. }
  2469. if ($usernotfullysetup) {
  2470. if ($preventredirect) {
  2471. throw new moodle_exception('usernotfullysetup');
  2472. }
  2473. if ($setwantsurltome) {
  2474. $SESSION->wantsurl = qualified_me();
  2475. }
  2476. redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
  2477. }
  2478. // Make sure the USER has a sesskey set up. Used for CSRF protection.
  2479. sesskey();
  2480. if (\core\session\manager::is_loggedinas()) {
  2481. // During a "logged in as" session we should force all content to be cleaned because the
  2482. // logged in user will be viewing potentially malicious user generated content.
  2483. // See MDL-63786 for more details.
  2484. $CFG->forceclean = true;
  2485. }
  2486. $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
  2487. // Do not bother admins with any formalities, except for activities pending deletion.
  2488. if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
  2489. // Set the global $COURSE.
  2490. if ($cm) {
  2491. $PAGE->set_cm($cm, $course);
  2492. $PAGE->set_pagelayout('incourse');
  2493. } else if (!empty($courseorid)) {
  2494. $PAGE->set_course($course);
  2495. }
  2496. // Set accesstime or the user will appear offline which messes up messaging.
  2497. // Do not update access time for webservice or ajax requests.
  2498. if (!WS_SERVER && !AJAX_SCRIPT) {
  2499. user_accesstime_log($course->id);
  2500. }
  2501. foreach ($afterlogins as $plugintype => $plugins) {
  2502. foreach ($plugins as $pluginfunction) {
  2503. $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2504. }
  2505. }
  2506. return;
  2507. }
  2508. // Scripts have a chance to declare that $USER->policyagreed should not be checked.
  2509. // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
  2510. if (!defined('NO_SITEPOLICY_CHECK')) {
  2511. define('NO_SITEPOLICY_CHECK', false);
  2512. }
  2513. // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
  2514. // Do not test if the script explicitly asked for skipping the site policies check.
  2515. if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
  2516. $manager = new \core_privacy\local\sitepolicy\manager();
  2517. if ($policyurl = $manager->get_redirect_url(isguestuser())) {
  2518. if ($preventredirect) {
  2519. throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
  2520. }
  2521. if ($setwantsurltome) {
  2522. $SESSION->wantsurl = qualified_me();
  2523. }
  2524. redirect($policyurl);
  2525. }
  2526. }
  2527. // Fetch the system context, the course context, and prefetch its child contexts.
  2528. $sysctx = context_system::instance();
  2529. $coursecontext = context_course::instance($course->id, MUST_EXIST);
  2530. if ($cm) {
  2531. $cmcontext = context_module::instance($cm->id, MUST_EXIST);
  2532. } else {
  2533. $cmcontext = null;
  2534. }
  2535. // If the site is currently under maintenance, then print a message.
  2536. if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
  2537. if ($preventredirect) {
  2538. throw new require_login_exception('Maintenance in progress');
  2539. }
  2540. $PAGE->set_context(null);
  2541. print_maintenance_message();
  2542. }
  2543. // Make sure the course itself is not hidden.
  2544. if ($course->id == SITEID) {
  2545. // Frontpage can not be hidden.
  2546. } else {
  2547. if (is_role_switched($course->id)) {
  2548. // When switching roles ignore the hidden flag - user had to be in course to do the switch.
  2549. } else {
  2550. if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
  2551. // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
  2552. // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
  2553. if ($preventredirect) {
  2554. throw new require_login_exception('Course is hidden');
  2555. }
  2556. $PAGE->set_context(null);
  2557. // We need to override the navigation URL as the course won't have been added to the navigation and thus
  2558. // the navigation will mess up when trying to find it.
  2559. navigation_node::override_active_url(new moodle_url('/'));
  2560. notice(get_string('coursehidden'), $CFG->wwwroot .'/');
  2561. }
  2562. }
  2563. }
  2564. // Is the user enrolled?
  2565. if ($course->id == SITEID) {
  2566. // Everybody is enrolled on the frontpage.
  2567. } else {
  2568. if (\core\session\manager::is_loggedinas()) {
  2569. // Make sure the REAL person can access this course first.
  2570. $realuser = \core\session\manager::get_realuser();
  2571. if (!is_enrolled($coursecontext, $realuser->id, '', true) and
  2572. !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
  2573. if ($preventredirect) {
  2574. throw new require_login_exception('Invalid course login-as access');
  2575. }
  2576. $PAGE->set_context(null);
  2577. echo $OUTPUT->header();
  2578. notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
  2579. }
  2580. }
  2581. $access = false;
  2582. if (is_role_switched($course->id)) {
  2583. // Ok, user had to be inside this course before the switch.
  2584. $access = true;
  2585. } else if (is_viewing($coursecontext, $USER)) {
  2586. // Ok, no need to mess with enrol.
  2587. $access = true;
  2588. } else {
  2589. if (isset($USER->enrol['enrolled'][$course->id])) {
  2590. if ($USER->enrol['enrolled'][$course->id] > time()) {
  2591. $access = true;
  2592. if (isset($USER->enrol['tempguest'][$course->id])) {
  2593. unset($USER->enrol['tempguest'][$course->id]);
  2594. remove_temp_course_roles($coursecontext);
  2595. }
  2596. } else {
  2597. // Expired.
  2598. unset($USER->enrol['enrolled'][$course->id]);
  2599. }
  2600. }
  2601. if (isset($USER->enrol['tempguest'][$course->id])) {
  2602. if ($USER->enrol['tempguest'][$course->id] == 0) {
  2603. $access = true;
  2604. } else if ($USER->enrol['tempguest'][$course->id] > time()) {
  2605. $access = true;
  2606. } else {
  2607. // Expired.
  2608. unset($USER->enrol['tempguest'][$course->id]);
  2609. remove_temp_course_roles($coursecontext);
  2610. }
  2611. }
  2612. if (!$access) {
  2613. // Cache not ok.
  2614. $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
  2615. if ($until !== false) {
  2616. // Active participants may always access, a timestamp in the future, 0 (always) or false.
  2617. if ($until == 0) {
  2618. $until = ENROL_MAX_TIMESTAMP;
  2619. }
  2620. $USER->enrol['enrolled'][$course->id] = $until;
  2621. $access = true;
  2622. } else if (core_course_category::can_view_course_info($course)) {
  2623. $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
  2624. $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
  2625. $enrols = enrol_get_plugins(true);
  2626. // First ask all enabled enrol instances in course if they want to auto enrol user.
  2627. foreach ($instances as $instance) {
  2628. if (!isset($enrols[$instance->enrol])) {
  2629. continue;
  2630. }
  2631. // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
  2632. $until = $enrols[$instance->enrol]->try_autoenrol($instance);
  2633. if ($until !== false) {
  2634. if ($until == 0) {
  2635. $until = ENROL_MAX_TIMESTAMP;
  2636. }
  2637. $USER->enrol['enrolled'][$course->id] = $until;
  2638. $access = true;
  2639. break;
  2640. }
  2641. }
  2642. // If not enrolled yet try to gain temporary guest access.
  2643. if (!$access) {
  2644. foreach ($instances as $instance) {
  2645. if (!isset($enrols[$instance->enrol])) {
  2646. continue;
  2647. }
  2648. // Get a duration for the guest access, a timestamp in the future or false.
  2649. $until = $enrols[$instance->enrol]->try_guestaccess($instance);
  2650. if ($until !== false and $until > time()) {
  2651. $USER->enrol['tempguest'][$course->id] = $until;
  2652. $access = true;
  2653. break;
  2654. }
  2655. }
  2656. }
  2657. } else {
  2658. // User is not enrolled and is not allowed to browse courses here.
  2659. if ($preventredirect) {
  2660. throw new require_login_exception('Course is not available');
  2661. }
  2662. $PAGE->set_context(null);
  2663. // We need to override the navigation URL as the course won't have been added to the navigation and thus
  2664. // the navigation will mess up when trying to find it.
  2665. navigation_node::override_active_url(new moodle_url('/'));
  2666. notice(get_string('coursehidden'), $CFG->wwwroot .'/');
  2667. }
  2668. }
  2669. }
  2670. if (!$access) {
  2671. if ($preventredirect) {
  2672. throw new require_login_exception('Not enrolled');
  2673. }
  2674. if ($setwantsurltome) {
  2675. $SESSION->wantsurl = qualified_me();
  2676. }
  2677. redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
  2678. }
  2679. }
  2680. // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
  2681. if ($cm && $cm->deletioninprogress) {
  2682. if ($preventredirect) {
  2683. throw new moodle_exception('activityisscheduledfordeletion');
  2684. }
  2685. require_once($CFG->dirroot . '/course/lib.php');
  2686. redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
  2687. }
  2688. // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
  2689. if ($cm && !$cm->uservisible) {
  2690. if ($preventredirect) {
  2691. throw new require_login_exception('Activity is hidden');
  2692. }
  2693. // Get the error message that activity is not available and why (if explanation can be shown to the user).
  2694. $PAGE->set_course($course);
  2695. $renderer = $PAGE->get_renderer('course');
  2696. $message = $renderer->course_section_cm_unavailable_error_message($cm);
  2697. redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
  2698. }
  2699. // Set the global $COURSE.
  2700. if ($cm) {
  2701. $PAGE->set_cm($cm, $course);
  2702. $PAGE->set_pagelayout('incourse');
  2703. } else if (!empty($courseorid)) {
  2704. $PAGE->set_course($course);
  2705. }
  2706. foreach ($afterlogins as $plugintype => $plugins) {
  2707. foreach ($plugins as $pluginfunction) {
  2708. $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2709. }
  2710. }
  2711. // Finally access granted, update lastaccess times.
  2712. // Do not update access time for webservice or ajax requests.
  2713. if (!WS_SERVER && !AJAX_SCRIPT) {
  2714. user_accesstime_log($course->id);
  2715. }
  2716. }
  2717. /**
  2718. * A convenience function for where we must be logged in as admin
  2719. * @return void
  2720. */
  2721. function require_admin() {
  2722. require_login(null, false);
  2723. require_capability('moodle/site:config', context_system::instance());
  2724. }
  2725. /**
  2726. * This function just makes sure a user is logged out.
  2727. *
  2728. * @package core_access
  2729. * @category access
  2730. */
  2731. function require_logout() {
  2732. global $USER, $DB;
  2733. if (!isloggedin()) {
  2734. // This should not happen often, no need for hooks or events here.
  2735. \core\session\manager::terminate_current();
  2736. return;
  2737. }
  2738. // Execute hooks before action.
  2739. $authplugins = array();
  2740. $authsequence = get_enabled_auth_plugins();
  2741. foreach ($authsequence as $authname) {
  2742. $authplugins[$authname] = get_auth_plugin($authname);
  2743. $authplugins[$authname]->prelogout_hook();
  2744. }
  2745. // Store info that gets removed during logout.
  2746. $sid = session_id();
  2747. $event = \core\event\user_loggedout::create(
  2748. array(
  2749. 'userid' => $USER->id,
  2750. 'objectid' => $USER->id,
  2751. 'other' => array('sessionid' => $sid),
  2752. )
  2753. );
  2754. if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
  2755. $event->add_record_snapshot('sessions', $session);
  2756. }
  2757. // Clone of $USER object to be used by auth plugins.
  2758. $user = fullclone($USER);
  2759. // Delete session record and drop $_SESSION content.
  2760. \core\session\manager::terminate_current();
  2761. // Trigger event AFTER action.
  2762. $event->trigger();
  2763. // Hook to execute auth plugins redirection after event trigger.
  2764. foreach ($authplugins as $authplugin) {
  2765. $authplugin->postlogout_hook($user);
  2766. }
  2767. }
  2768. /**
  2769. * Weaker version of require_login()
  2770. *
  2771. * This is a weaker version of {@link require_login()} which only requires login
  2772. * when called from within a course rather than the site page, unless
  2773. * the forcelogin option is turned on.
  2774. * @see require_login()
  2775. *
  2776. * @package core_access
  2777. * @category access
  2778. *
  2779. * @param mixed $courseorid The course object or id in question
  2780. * @param bool $autologinguest Allow autologin guests if that is wanted
  2781. * @param object $cm Course activity module if known
  2782. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  2783. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  2784. * in order to keep redirects working properly. MDL-14495
  2785. * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
  2786. * @return void
  2787. * @throws coding_exception
  2788. */
  2789. function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
  2790. global $CFG, $PAGE, $SITE;
  2791. $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
  2792. or (!is_object($courseorid) and $courseorid == SITEID));
  2793. if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
  2794. // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
  2795. // db queries so this is not really a performance concern, however it is obviously
  2796. // better if you use get_fast_modinfo to get the cm before calling this.
  2797. if (is_object($courseorid)) {
  2798. $course = $courseorid;
  2799. } else {
  2800. $course = clone($SITE);
  2801. }
  2802. $modinfo = get_fast_modinfo($course);
  2803. $cm = $modinfo->get_cm($cm->id);
  2804. }
  2805. if (!empty($CFG->forcelogin)) {
  2806. // Login required for both SITE and courses.
  2807. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2808. } else if ($issite && !empty($cm) and !$cm->uservisible) {
  2809. // Always login for hidden activities.
  2810. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2811. } else if (isloggedin() && !isguestuser()) {
  2812. // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
  2813. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2814. } else if ($issite) {
  2815. // Login for SITE not required.
  2816. // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
  2817. if (!empty($courseorid)) {
  2818. if (is_object($courseorid)) {
  2819. $course = $courseorid;
  2820. } else {
  2821. $course = clone $SITE;
  2822. }
  2823. if ($cm) {
  2824. if ($cm->course != $course->id) {
  2825. throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
  2826. }
  2827. $PAGE->set_cm($cm, $course);
  2828. $PAGE->set_pagelayout('incourse');
  2829. } else {
  2830. $PAGE->set_course($course);
  2831. }
  2832. } else {
  2833. // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
  2834. $PAGE->set_course($PAGE->course);
  2835. }
  2836. // Do not update access time for webservice or ajax requests.
  2837. if (!WS_SERVER && !AJAX_SCRIPT) {
  2838. user_accesstime_log(SITEID);
  2839. }
  2840. return;
  2841. } else {
  2842. // Course login always required.
  2843. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2844. }
  2845. }
  2846. /**
  2847. * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
  2848. *
  2849. * @param string $keyvalue the key value
  2850. * @param string $script unique script identifier
  2851. * @param int $instance instance id
  2852. * @return stdClass the key entry in the user_private_key table
  2853. * @since Moodle 3.2
  2854. * @throws moodle_exception
  2855. */
  2856. function validate_user_key($keyvalue, $script, $instance) {
  2857. global $DB;
  2858. if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
  2859. print_error('invalidkey');
  2860. }
  2861. if (!empty($key->validuntil) and $key->validuntil < time()) {
  2862. print_error('expiredkey');
  2863. }
  2864. if ($key->iprestriction) {
  2865. $remoteaddr = getremoteaddr(null);
  2866. if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
  2867. print_error('ipmismatch');
  2868. }
  2869. }
  2870. return $key;
  2871. }
  2872. /**
  2873. * Require key login. Function terminates with error if key not found or incorrect.
  2874. *
  2875. * @uses NO_MOODLE_COOKIES
  2876. * @uses PARAM_ALPHANUM
  2877. * @param string $script unique script identifier
  2878. * @param int $instance optional instance id
  2879. * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
  2880. * @return int Instance ID
  2881. */
  2882. function require_user_key_login($script, $instance = null, $keyvalue = null) {
  2883. global $DB;
  2884. if (!NO_MOODLE_COOKIES) {
  2885. print_error('sessioncookiesdisable');
  2886. }
  2887. // Extra safety.
  2888. \core\session\manager::write_close();
  2889. if (null === $keyvalue) {
  2890. $keyvalue = required_param('key', PARAM_ALPHANUM);
  2891. }
  2892. $key = validate_user_key($keyvalue, $script, $instance);
  2893. if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
  2894. print_error('invaliduserid');
  2895. }
  2896. core_user::require_active_user($user, true, true);
  2897. // Emulate normal session.
  2898. enrol_check_plugins($user);
  2899. \core\session\manager::set_user($user);
  2900. // Note we are not using normal login.
  2901. if (!defined('USER_KEY_LOGIN')) {
  2902. define('USER_KEY_LOGIN', true);
  2903. }
  2904. // Return instance id - it might be empty.
  2905. return $key->instance;
  2906. }
  2907. /**
  2908. * Creates a new private user access key.
  2909. *
  2910. * @param string $script unique target identifier
  2911. * @param int $userid
  2912. * @param int $instance optional instance id
  2913. * @param string $iprestriction optional ip restricted access
  2914. * @param int $validuntil key valid only until given data
  2915. * @return string access key value
  2916. */
  2917. function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
  2918. global $DB;
  2919. $key = new stdClass();
  2920. $key->script = $script;
  2921. $key->userid = $userid;
  2922. $key->instance = $instance;
  2923. $key->iprestriction = $iprestriction;
  2924. $key->validuntil = $validuntil;
  2925. $key->timecreated = time();
  2926. // Something long and unique.
  2927. $key->value = md5($userid.'_'.time().random_string(40));
  2928. while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
  2929. // Must be unique.
  2930. $key->value = md5($userid.'_'.time().random_string(40));
  2931. }
  2932. $DB->insert_record('user_private_key', $key);
  2933. return $key->value;
  2934. }
  2935. /**
  2936. * Delete the user's new private user access keys for a particular script.
  2937. *
  2938. * @param string $script unique target identifier
  2939. * @param int $userid
  2940. * @return void
  2941. */
  2942. function delete_user_key($script, $userid) {
  2943. global $DB;
  2944. $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
  2945. }
  2946. /**
  2947. * Gets a private user access key (and creates one if one doesn't exist).
  2948. *
  2949. * @param string $script unique target identifier
  2950. * @param int $userid
  2951. * @param int $instance optional instance id
  2952. * @param string $iprestriction optional ip restricted access
  2953. * @param int $validuntil key valid only until given date
  2954. * @return string access key value
  2955. */
  2956. function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
  2957. global $DB;
  2958. if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
  2959. 'instance' => $instance, 'iprestriction' => $iprestriction,
  2960. 'validuntil' => $validuntil))) {
  2961. return $key->value;
  2962. } else {
  2963. return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
  2964. }
  2965. }
  2966. /**
  2967. * Modify the user table by setting the currently logged in user's last login to now.
  2968. *
  2969. * @return bool Always returns true
  2970. */
  2971. function update_user_login_times() {
  2972. global $USER, $DB;
  2973. if (isguestuser()) {
  2974. // Do not update guest access times/ips for performance.
  2975. return true;
  2976. }
  2977. $now = time();
  2978. $user = new stdClass();
  2979. $user->id = $USER->id;
  2980. // Make sure all users that logged in have some firstaccess.
  2981. if ($USER->firstaccess == 0) {
  2982. $USER->firstaccess = $user->firstaccess = $now;
  2983. }
  2984. // Store the previous current as lastlogin.
  2985. $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
  2986. $USER->currentlogin = $user->currentlogin = $now;
  2987. // Function user_accesstime_log() may not update immediately, better do it here.
  2988. $USER->lastaccess = $user->lastaccess = $now;
  2989. $USER->lastip = $user->lastip = getremoteaddr();
  2990. // Note: do not call user_update_user() here because this is part of the login process,
  2991. // the login event means that these fields were updated.
  2992. $DB->update_record('user', $user);
  2993. return true;
  2994. }
  2995. /**
  2996. * Determines if a user has completed setting up their account.
  2997. *
  2998. * The lax mode (with $strict = false) has been introduced for special cases
  2999. * only where we want to skip certain checks intentionally. This is valid in
  3000. * certain mnet or ajax scenarios when the user cannot / should not be
  3001. * redirected to edit their profile. In most cases, you should perform the
  3002. * strict check.
  3003. *
  3004. * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
  3005. * @param bool $strict Be more strict and assert id and custom profile fields set, too
  3006. * @return bool
  3007. */
  3008. function user_not_fully_set_up($user, $strict = true) {
  3009. global $CFG;
  3010. require_once($CFG->dirroot.'/user/profile/lib.php');
  3011. if (isguestuser($user)) {
  3012. return false;
  3013. }
  3014. if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
  3015. return true;
  3016. }
  3017. if ($strict) {
  3018. if (empty($user->id)) {
  3019. // Strict mode can be used with existing accounts only.
  3020. return true;
  3021. }
  3022. if (!profile_has_required_custom_fields_set($user->id)) {
  3023. return true;
  3024. }
  3025. }
  3026. return false;
  3027. }
  3028. /**
  3029. * Check whether the user has exceeded the bounce threshold
  3030. *
  3031. * @param stdClass $user A {@link $USER} object
  3032. * @return bool true => User has exceeded bounce threshold
  3033. */
  3034. function over_bounce_threshold($user) {
  3035. global $CFG, $DB;
  3036. if (empty($CFG->handlebounces)) {
  3037. return false;
  3038. }
  3039. if (empty($user->id)) {
  3040. // No real (DB) user, nothing to do here.
  3041. return false;
  3042. }
  3043. // Set sensible defaults.
  3044. if (empty($CFG->minbounces)) {
  3045. $CFG->minbounces = 10;
  3046. }
  3047. if (empty($CFG->bounceratio)) {
  3048. $CFG->bounceratio = .20;
  3049. }
  3050. $bouncecount = 0;
  3051. $sendcount = 0;
  3052. if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
  3053. $bouncecount = $bounce->value;
  3054. }
  3055. if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
  3056. $sendcount = $send->value;
  3057. }
  3058. return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
  3059. }
  3060. /**
  3061. * Used to increment or reset email sent count
  3062. *
  3063. * @param stdClass $user object containing an id
  3064. * @param bool $reset will reset the count to 0
  3065. * @return void
  3066. */
  3067. function set_send_count($user, $reset=false) {
  3068. global $DB;
  3069. if (empty($user->id)) {
  3070. // No real (DB) user, nothing to do here.
  3071. return;
  3072. }
  3073. if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
  3074. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  3075. $DB->update_record('user_preferences', $pref);
  3076. } else if (!empty($reset)) {
  3077. // If it's not there and we're resetting, don't bother. Make a new one.
  3078. $pref = new stdClass();
  3079. $pref->name = 'email_send_count';
  3080. $pref->value = 1;
  3081. $pref->userid = $user->id;
  3082. $DB->insert_record('user_preferences', $pref, false);
  3083. }
  3084. }
  3085. /**
  3086. * Increment or reset user's email bounce count
  3087. *
  3088. * @param stdClass $user object containing an id
  3089. * @param bool $reset will reset the count to 0
  3090. */
  3091. function set_bounce_count($user, $reset=false) {
  3092. global $DB;
  3093. if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
  3094. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  3095. $DB->update_record('user_preferences', $pref);
  3096. } else if (!empty($reset)) {
  3097. // If it's not there and we're resetting, don't bother. Make a new one.
  3098. $pref = new stdClass();
  3099. $pref->name = 'email_bounce_count';
  3100. $pref->value = 1;
  3101. $pref->userid = $user->id;
  3102. $DB->insert_record('user_preferences', $pref, false);
  3103. }
  3104. }
  3105. /**
  3106. * Determines if the logged in user is currently moving an activity
  3107. *
  3108. * @param int $courseid The id of the course being tested
  3109. * @return bool
  3110. */
  3111. function ismoving($courseid) {
  3112. global $USER;
  3113. if (!empty($USER->activitycopy)) {
  3114. return ($USER->activitycopycourse == $courseid);
  3115. }
  3116. return false;
  3117. }
  3118. /**
  3119. * Returns a persons full name
  3120. *
  3121. * Given an object containing all of the users name values, this function returns a string with the full name of the person.
  3122. * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
  3123. * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
  3124. * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
  3125. *
  3126. * @param stdClass $user A {@link $USER} object to get full name of.
  3127. * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
  3128. * @return string
  3129. */
  3130. function fullname($user, $override=false) {
  3131. global $CFG, $SESSION;
  3132. if (!isset($user->firstname) and !isset($user->lastname)) {
  3133. return '';
  3134. }
  3135. // Get all of the name fields.
  3136. $allnames = \core_user\fields::get_name_fields();
  3137. if ($CFG->debugdeveloper) {
  3138. foreach ($allnames as $allname) {
  3139. if (!property_exists($user, $allname)) {
  3140. // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
  3141. debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
  3142. // Message has been sent, no point in sending the message multiple times.
  3143. break;
  3144. }
  3145. }
  3146. }
  3147. if (!$override) {
  3148. if (!empty($CFG->forcefirstname)) {
  3149. $user->firstname = $CFG->forcefirstname;
  3150. }
  3151. if (!empty($CFG->forcelastname)) {
  3152. $user->lastname = $CFG->forcelastname;
  3153. }
  3154. }
  3155. if (!empty($SESSION->fullnamedisplay)) {
  3156. $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
  3157. }
  3158. $template = null;
  3159. // If the fullnamedisplay setting is available, set the template to that.
  3160. if (isset($CFG->fullnamedisplay)) {
  3161. $template = $CFG->fullnamedisplay;
  3162. }
  3163. // If the template is empty, or set to language, return the language string.
  3164. if ((empty($template) || $template == 'language') && !$override) {
  3165. return get_string('fullnamedisplay', null, $user);
  3166. }
  3167. // Check to see if we are displaying according to the alternative full name format.
  3168. if ($override) {
  3169. if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
  3170. // Default to show just the user names according to the fullnamedisplay string.
  3171. return get_string('fullnamedisplay', null, $user);
  3172. } else {
  3173. // If the override is true, then change the template to use the complete name.
  3174. $template = $CFG->alternativefullnameformat;
  3175. }
  3176. }
  3177. $requirednames = array();
  3178. // With each name, see if it is in the display name template, and add it to the required names array if it is.
  3179. foreach ($allnames as $allname) {
  3180. if (strpos($template, $allname) !== false) {
  3181. $requirednames[] = $allname;
  3182. }
  3183. }
  3184. $displayname = $template;
  3185. // Switch in the actual data into the template.
  3186. foreach ($requirednames as $altname) {
  3187. if (isset($user->$altname)) {
  3188. // Using empty() on the below if statement causes breakages.
  3189. if ((string)$user->$altname == '') {
  3190. $displayname = str_replace($altname, 'EMPTY', $displayname);
  3191. } else {
  3192. $displayname = str_replace($altname, $user->$altname, $displayname);
  3193. }
  3194. } else {
  3195. $displayname = str_replace($altname, 'EMPTY', $displayname);
  3196. }
  3197. }
  3198. // Tidy up any misc. characters (Not perfect, but gets most characters).
  3199. // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
  3200. // katakana and parenthesis.
  3201. $patterns = array();
  3202. // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
  3203. // filled in by a user.
  3204. // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
  3205. $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
  3206. // This regular expression is to remove any double spaces in the display name.
  3207. $patterns[] = '/\s{2,}/u';
  3208. foreach ($patterns as $pattern) {
  3209. $displayname = preg_replace($pattern, ' ', $displayname);
  3210. }
  3211. // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
  3212. $displayname = trim($displayname);
  3213. if (empty($displayname)) {
  3214. // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
  3215. // people in general feel is a good setting to fall back on.
  3216. $displayname = $user->firstname;
  3217. }
  3218. return $displayname;
  3219. }
  3220. /**
  3221. * Reduces lines of duplicated code for getting user name fields.
  3222. *
  3223. * See also {@link user_picture::unalias()}
  3224. *
  3225. * @param object $addtoobject Object to add user name fields to.
  3226. * @param object $secondobject Object that contains user name field information.
  3227. * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
  3228. * @param array $additionalfields Additional fields to be matched with data in the second object.
  3229. * The key can be set to the user table field name.
  3230. * @return object User name fields.
  3231. */
  3232. function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
  3233. $fields = [];
  3234. foreach (\core_user\fields::get_name_fields() as $field) {
  3235. $fields[$field] = $prefix . $field;
  3236. }
  3237. if ($additionalfields) {
  3238. // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
  3239. // the key is a number and then sets the key to the array value.
  3240. foreach ($additionalfields as $key => $value) {
  3241. if (is_numeric($key)) {
  3242. $additionalfields[$value] = $prefix . $value;
  3243. unset($additionalfields[$key]);
  3244. } else {
  3245. $additionalfields[$key] = $prefix . $value;
  3246. }
  3247. }
  3248. $fields = array_merge($fields, $additionalfields);
  3249. }
  3250. foreach ($fields as $key => $field) {
  3251. // Important that we have all of the user name fields present in the object that we are sending back.
  3252. $addtoobject->$key = '';
  3253. if (isset($secondobject->$field)) {
  3254. $addtoobject->$key = $secondobject->$field;
  3255. }
  3256. }
  3257. return $addtoobject;
  3258. }
  3259. /**
  3260. * Returns an array of values in order of occurance in a provided string.
  3261. * The key in the result is the character postion in the string.
  3262. *
  3263. * @param array $values Values to be found in the string format
  3264. * @param string $stringformat The string which may contain values being searched for.
  3265. * @return array An array of values in order according to placement in the string format.
  3266. */
  3267. function order_in_string($values, $stringformat) {
  3268. $valuearray = array();
  3269. foreach ($values as $value) {
  3270. $pattern = "/$value\b/";
  3271. // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
  3272. if (preg_match($pattern, $stringformat)) {
  3273. $replacement = "thing";
  3274. // Replace the value with something more unique to ensure we get the right position when using strpos().
  3275. $newformat = preg_replace($pattern, $replacement, $stringformat);
  3276. $position = strpos($newformat, $replacement);
  3277. $valuearray[$position] = $value;
  3278. }
  3279. }
  3280. ksort($valuearray);
  3281. return $valuearray;
  3282. }
  3283. /**
  3284. * Returns whether a given authentication plugin exists.
  3285. *
  3286. * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
  3287. * @return boolean Whether the plugin is available.
  3288. */
  3289. function exists_auth_plugin($auth) {
  3290. global $CFG;
  3291. if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
  3292. return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
  3293. }
  3294. return false;
  3295. }
  3296. /**
  3297. * Checks if a given plugin is in the list of enabled authentication plugins.
  3298. *
  3299. * @param string $auth Authentication plugin.
  3300. * @return boolean Whether the plugin is enabled.
  3301. */
  3302. function is_enabled_auth($auth) {
  3303. if (empty($auth)) {
  3304. return false;
  3305. }
  3306. $enabled = get_enabled_auth_plugins();
  3307. return in_array($auth, $enabled);
  3308. }
  3309. /**
  3310. * Returns an authentication plugin instance.
  3311. *
  3312. * @param string $auth name of authentication plugin
  3313. * @return auth_plugin_base An instance of the required authentication plugin.
  3314. */
  3315. function get_auth_plugin($auth) {
  3316. global $CFG;
  3317. // Check the plugin exists first.
  3318. if (! exists_auth_plugin($auth)) {
  3319. print_error('authpluginnotfound', 'debug', '', $auth);
  3320. }
  3321. // Return auth plugin instance.
  3322. require_once("{$CFG->dirroot}/auth/$auth/auth.php");
  3323. $class = "auth_plugin_$auth";
  3324. return new $class;
  3325. }
  3326. /**
  3327. * Returns array of active auth plugins.
  3328. *
  3329. * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
  3330. * @return array
  3331. */
  3332. function get_enabled_auth_plugins($fix=false) {
  3333. global $CFG;
  3334. $default = array('manual', 'nologin');
  3335. if (empty($CFG->auth)) {
  3336. $auths = array();
  3337. } else {
  3338. $auths = explode(',', $CFG->auth);
  3339. }
  3340. $auths = array_unique($auths);
  3341. $oldauthconfig = implode(',', $auths);
  3342. foreach ($auths as $k => $authname) {
  3343. if (in_array($authname, $default)) {
  3344. // The manual and nologin plugin never need to be stored.
  3345. unset($auths[$k]);
  3346. } else if (!exists_auth_plugin($authname)) {
  3347. debugging(get_string('authpluginnotfound', 'debug', $authname));
  3348. unset($auths[$k]);
  3349. }
  3350. }
  3351. // Ideally only explicit interaction from a human admin should trigger a
  3352. // change in auth config, see MDL-70424 for details.
  3353. if ($fix) {
  3354. $newconfig = implode(',', $auths);
  3355. if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
  3356. add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
  3357. set_config('auth', $newconfig);
  3358. }
  3359. }
  3360. return (array_merge($default, $auths));
  3361. }
  3362. /**
  3363. * Returns true if an internal authentication method is being used.
  3364. * if method not specified then, global default is assumed
  3365. *
  3366. * @param string $auth Form of authentication required
  3367. * @return bool
  3368. */
  3369. function is_internal_auth($auth) {
  3370. // Throws error if bad $auth.
  3371. $authplugin = get_auth_plugin($auth);
  3372. return $authplugin->is_internal();
  3373. }
  3374. /**
  3375. * Returns true if the user is a 'restored' one.
  3376. *
  3377. * Used in the login process to inform the user and allow him/her to reset the password
  3378. *
  3379. * @param string $username username to be checked
  3380. * @return bool
  3381. */
  3382. function is_restored_user($username) {
  3383. global $CFG, $DB;
  3384. return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
  3385. }
  3386. /**
  3387. * Returns an array of user fields
  3388. *
  3389. * @return array User field/column names
  3390. */
  3391. function get_user_fieldnames() {
  3392. global $DB;
  3393. $fieldarray = $DB->get_columns('user');
  3394. unset($fieldarray['id']);
  3395. $fieldarray = array_keys($fieldarray);
  3396. return $fieldarray;
  3397. }
  3398. /**
  3399. * Returns the string of the language for the new user.
  3400. *
  3401. * @return string language for the new user
  3402. */
  3403. function get_newuser_language() {
  3404. global $CFG, $SESSION;
  3405. return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
  3406. }
  3407. /**
  3408. * Creates a bare-bones user record
  3409. *
  3410. * @todo Outline auth types and provide code example
  3411. *
  3412. * @param string $username New user's username to add to record
  3413. * @param string $password New user's password to add to record
  3414. * @param string $auth Form of authentication required
  3415. * @return stdClass A complete user object
  3416. */
  3417. function create_user_record($username, $password, $auth = 'manual') {
  3418. global $CFG, $DB, $SESSION;
  3419. require_once($CFG->dirroot.'/user/profile/lib.php');
  3420. require_once($CFG->dirroot.'/user/lib.php');
  3421. // Just in case check text case.
  3422. $username = trim(core_text::strtolower($username));
  3423. $authplugin = get_auth_plugin($auth);
  3424. $customfields = $authplugin->get_custom_user_profile_fields();
  3425. $newuser = new stdClass();
  3426. if ($newinfo = $authplugin->get_userinfo($username)) {
  3427. $newinfo = truncate_userinfo($newinfo);
  3428. foreach ($newinfo as $key => $value) {
  3429. if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
  3430. $newuser->$key = $value;
  3431. }
  3432. }
  3433. }
  3434. if (!empty($newuser->email)) {
  3435. if (email_is_not_allowed($newuser->email)) {
  3436. unset($newuser->email);
  3437. }
  3438. }
  3439. if (!isset($newuser->city)) {
  3440. $newuser->city = '';
  3441. }
  3442. $newuser->auth = $auth;
  3443. $newuser->username = $username;
  3444. // Fix for MDL-8480
  3445. // user CFG lang for user if $newuser->lang is empty
  3446. // or $user->lang is not an installed language.
  3447. if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
  3448. $newuser->lang = get_newuser_language();
  3449. }
  3450. $newuser->confirmed = 1;
  3451. $newuser->lastip = getremoteaddr();
  3452. $newuser->timecreated = time();
  3453. $newuser->timemodified = $newuser->timecreated;
  3454. $newuser->mnethostid = $CFG->mnet_localhost_id;
  3455. $newuser->id = user_create_user($newuser, false, false);
  3456. // Save user profile data.
  3457. profile_save_data($newuser);
  3458. $user = get_complete_user_data('id', $newuser->id);
  3459. if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
  3460. set_user_preference('auth_forcepasswordchange', 1, $user);
  3461. }
  3462. // Set the password.
  3463. update_internal_user_password($user, $password);
  3464. // Trigger event.
  3465. \core\event\user_created::create_from_userid($newuser->id)->trigger();
  3466. return $user;
  3467. }
  3468. /**
  3469. * Will update a local user record from an external source (MNET users can not be updated using this method!).
  3470. *
  3471. * @param string $username user's username to update the record
  3472. * @return stdClass A complete user object
  3473. */
  3474. function update_user_record($username) {
  3475. global $DB, $CFG;
  3476. // Just in case check text case.
  3477. $username = trim(core_text::strtolower($username));
  3478. $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
  3479. return update_user_record_by_id($oldinfo->id);
  3480. }
  3481. /**
  3482. * Will update a local user record from an external source (MNET users can not be updated using this method!).
  3483. *
  3484. * @param int $id user id
  3485. * @return stdClass A complete user object
  3486. */
  3487. function update_user_record_by_id($id) {
  3488. global $DB, $CFG;
  3489. require_once($CFG->dirroot."/user/profile/lib.php");
  3490. require_once($CFG->dirroot.'/user/lib.php');
  3491. $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
  3492. $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
  3493. $newuser = array();
  3494. $userauth = get_auth_plugin($oldinfo->auth);
  3495. if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
  3496. $newinfo = truncate_userinfo($newinfo);
  3497. $customfields = $userauth->get_custom_user_profile_fields();
  3498. foreach ($newinfo as $key => $value) {
  3499. $iscustom = in_array($key, $customfields);
  3500. if (!$iscustom) {
  3501. $key = strtolower($key);
  3502. }
  3503. if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
  3504. or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
  3505. // Unknown or must not be changed.
  3506. continue;
  3507. }
  3508. if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
  3509. continue;
  3510. }
  3511. $confval = $userauth->config->{'field_updatelocal_' . $key};
  3512. $lockval = $userauth->config->{'field_lock_' . $key};
  3513. if ($confval === 'onlogin') {
  3514. // MDL-4207 Don't overwrite modified user profile values with
  3515. // empty LDAP values when 'unlocked if empty' is set. The purpose
  3516. // of the setting 'unlocked if empty' is to allow the user to fill
  3517. // in a value for the selected field _if LDAP is giving
  3518. // nothing_ for this field. Thus it makes sense to let this value
  3519. // stand in until LDAP is giving a value for this field.
  3520. if (!(empty($value) && $lockval === 'unlockedifempty')) {
  3521. if ($iscustom || (in_array($key, $userauth->userfields) &&
  3522. ((string)$oldinfo->$key !== (string)$value))) {
  3523. $newuser[$key] = (string)$value;
  3524. }
  3525. }
  3526. }
  3527. }
  3528. if ($newuser) {
  3529. $newuser['id'] = $oldinfo->id;
  3530. $newuser['timemodified'] = time();
  3531. user_update_user((object) $newuser, false, false);
  3532. // Save user profile data.
  3533. profile_save_data((object) $newuser);
  3534. // Trigger event.
  3535. \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
  3536. }
  3537. }
  3538. return get_complete_user_data('id', $oldinfo->id);
  3539. }
  3540. /**
  3541. * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
  3542. *
  3543. * @param array $info Array of user properties to truncate if needed
  3544. * @return array The now truncated information that was passed in
  3545. */
  3546. function truncate_userinfo(array $info) {
  3547. // Define the limits.
  3548. $limit = array(
  3549. 'username' => 100,
  3550. 'idnumber' => 255,
  3551. 'firstname' => 100,
  3552. 'lastname' => 100,
  3553. 'email' => 100,
  3554. 'phone1' => 20,
  3555. 'phone2' => 20,
  3556. 'institution' => 255,
  3557. 'department' => 255,
  3558. 'address' => 255,
  3559. 'city' => 120,
  3560. 'country' => 2,
  3561. );
  3562. // Apply where needed.
  3563. foreach (array_keys($info) as $key) {
  3564. if (!empty($limit[$key])) {
  3565. $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
  3566. }
  3567. }
  3568. return $info;
  3569. }
  3570. /**
  3571. * Marks user deleted in internal user database and notifies the auth plugin.
  3572. * Also unenrols user from all roles and does other cleanup.
  3573. *
  3574. * Any plugin that needs to purge user data should register the 'user_deleted' event.
  3575. *
  3576. * @param stdClass $user full user object before delete
  3577. * @return boolean success
  3578. * @throws coding_exception if invalid $user parameter detected
  3579. */
  3580. function delete_user(stdClass $user) {
  3581. global $CFG, $DB, $SESSION;
  3582. require_once($CFG->libdir.'/grouplib.php');
  3583. require_once($CFG->libdir.'/gradelib.php');
  3584. require_once($CFG->dirroot.'/message/lib.php');
  3585. require_once($CFG->dirroot.'/user/lib.php');
  3586. // Make sure nobody sends bogus record type as parameter.
  3587. if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
  3588. throw new coding_exception('Invalid $user parameter in delete_user() detected');
  3589. }
  3590. // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
  3591. if (!$user = $DB->get_record('user', array('id' => $user->id))) {
  3592. debugging('Attempt to delete unknown user account.');
  3593. return false;
  3594. }
  3595. // There must be always exactly one guest record, originally the guest account was identified by username only,
  3596. // now we use $CFG->siteguest for performance reasons.
  3597. if ($user->username === 'guest' or isguestuser($user)) {
  3598. debugging('Guest user account can not be deleted.');
  3599. return false;
  3600. }
  3601. // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
  3602. // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
  3603. if ($user->auth === 'manual' and is_siteadmin($user)) {
  3604. debugging('Local administrator accounts can not be deleted.');
  3605. return false;
  3606. }
  3607. // Allow plugins to use this user object before we completely delete it.
  3608. if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
  3609. foreach ($pluginsfunction as $plugintype => $plugins) {
  3610. foreach ($plugins as $pluginfunction) {
  3611. $pluginfunction($user);
  3612. }
  3613. }
  3614. }
  3615. // Keep user record before updating it, as we have to pass this to user_deleted event.
  3616. $olduser = clone $user;
  3617. // Keep a copy of user context, we need it for event.
  3618. $usercontext = context_user::instance($user->id);
  3619. // Delete all grades - backup is kept in grade_grades_history table.
  3620. grade_user_delete($user->id);
  3621. // TODO: remove from cohorts using standard API here.
  3622. // Remove user tags.
  3623. core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
  3624. // Unconditionally unenrol from all courses.
  3625. enrol_user_delete($user);
  3626. // Unenrol from all roles in all contexts.
  3627. // This might be slow but it is really needed - modules might do some extra cleanup!
  3628. role_unassign_all(array('userid' => $user->id));
  3629. // Notify the competency subsystem.
  3630. \core_competency\api::hook_user_deleted($user->id);
  3631. // Now do a brute force cleanup.
  3632. // Delete all user events and subscription events.
  3633. $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
  3634. // Now, delete all calendar subscription from the user.
  3635. $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
  3636. // Remove from all cohorts.
  3637. $DB->delete_records('cohort_members', array('userid' => $user->id));
  3638. // Remove from all groups.
  3639. $DB->delete_records('groups_members', array('userid' => $user->id));
  3640. // Brute force unenrol from all courses.
  3641. $DB->delete_records('user_enrolments', array('userid' => $user->id));
  3642. // Purge user preferences.
  3643. $DB->delete_records('user_preferences', array('userid' => $user->id));
  3644. // Purge user extra profile info.
  3645. $DB->delete_records('user_info_data', array('userid' => $user->id));
  3646. // Purge log of previous password hashes.
  3647. $DB->delete_records('user_password_history', array('userid' => $user->id));
  3648. // Last course access not necessary either.
  3649. $DB->delete_records('user_lastaccess', array('userid' => $user->id));
  3650. // Remove all user tokens.
  3651. $DB->delete_records('external_tokens', array('userid' => $user->id));
  3652. // Unauthorise the user for all services.
  3653. $DB->delete_records('external_services_users', array('userid' => $user->id));
  3654. // Remove users private keys.
  3655. $DB->delete_records('user_private_key', array('userid' => $user->id));
  3656. // Remove users customised pages.
  3657. $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
  3658. // Remove user's oauth2 refresh tokens, if present.
  3659. $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
  3660. // Delete user from $SESSION->bulk_users.
  3661. if (isset($SESSION->bulk_users[$user->id])) {
  3662. unset($SESSION->bulk_users[$user->id]);
  3663. }
  3664. // Force logout - may fail if file based sessions used, sorry.
  3665. \core\session\manager::kill_user_sessions($user->id);
  3666. // Generate username from email address, or a fake email.
  3667. $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
  3668. $deltime = time();
  3669. $deltimelength = core_text::strlen((string) $deltime);
  3670. // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
  3671. $delname = clean_param($delemail, PARAM_USERNAME);
  3672. $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
  3673. // Workaround for bulk deletes of users with the same email address.
  3674. while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
  3675. $delname++;
  3676. }
  3677. // Mark internal user record as "deleted".
  3678. $updateuser = new stdClass();
  3679. $updateuser->id = $user->id;
  3680. $updateuser->deleted = 1;
  3681. $updateuser->username = $delname; // Remember it just in case.
  3682. $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
  3683. $updateuser->idnumber = ''; // Clear this field to free it up.
  3684. $updateuser->picture = 0;
  3685. $updateuser->timemodified = $deltime;
  3686. // Don't trigger update event, as user is being deleted.
  3687. user_update_user($updateuser, false, false);
  3688. // Delete all content associated with the user context, but not the context itself.
  3689. $usercontext->delete_content();
  3690. // Delete any search data.
  3691. \core_search\manager::context_deleted($usercontext);
  3692. // Any plugin that needs to cleanup should register this event.
  3693. // Trigger event.
  3694. $event = \core\event\user_deleted::create(
  3695. array(
  3696. 'objectid' => $user->id,
  3697. 'relateduserid' => $user->id,
  3698. 'context' => $usercontext,
  3699. 'other' => array(
  3700. 'username' => $user->username,
  3701. 'email' => $user->email,
  3702. 'idnumber' => $user->idnumber,
  3703. 'picture' => $user->picture,
  3704. 'mnethostid' => $user->mnethostid
  3705. )
  3706. )
  3707. );
  3708. $event->add_record_snapshot('user', $olduser);
  3709. $event->trigger();
  3710. // We will update the user's timemodified, as it will be passed to the user_deleted event, which
  3711. // should know about this updated property persisted to the user's table.
  3712. $user->timemodified = $updateuser->timemodified;
  3713. // Notify auth plugin - do not block the delete even when plugin fails.
  3714. $authplugin = get_auth_plugin($user->auth);
  3715. $authplugin->user_delete($user);
  3716. return true;
  3717. }
  3718. /**
  3719. * Retrieve the guest user object.
  3720. *
  3721. * @return stdClass A {@link $USER} object
  3722. */
  3723. function guest_user() {
  3724. global $CFG, $DB;
  3725. if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
  3726. $newuser->confirmed = 1;
  3727. $newuser->lang = get_newuser_language();
  3728. $newuser->lastip = getremoteaddr();
  3729. }
  3730. return $newuser;
  3731. }
  3732. /**
  3733. * Authenticates a user against the chosen authentication mechanism
  3734. *
  3735. * Given a username and password, this function looks them
  3736. * up using the currently selected authentication mechanism,
  3737. * and if the authentication is successful, it returns a
  3738. * valid $user object from the 'user' table.
  3739. *
  3740. * Uses auth_ functions from the currently active auth module
  3741. *
  3742. * After authenticate_user_login() returns success, you will need to
  3743. * log that the user has logged in, and call complete_user_login() to set
  3744. * the session up.
  3745. *
  3746. * Note: this function works only with non-mnet accounts!
  3747. *
  3748. * @param string $username User's username (or also email if $CFG->authloginviaemail enabled)
  3749. * @param string $password User's password
  3750. * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
  3751. * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
  3752. * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
  3753. * @return stdClass|false A {@link $USER} object or false if error
  3754. */
  3755. function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
  3756. global $CFG, $DB, $PAGE;
  3757. require_once("$CFG->libdir/authlib.php");
  3758. if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
  3759. // we have found the user
  3760. } else if (!empty($CFG->authloginviaemail)) {
  3761. if ($email = clean_param($username, PARAM_EMAIL)) {
  3762. $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
  3763. $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
  3764. $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
  3765. if (count($users) === 1) {
  3766. // Use email for login only if unique.
  3767. $user = reset($users);
  3768. $user = get_complete_user_data('id', $user->id);
  3769. $username = $user->username;
  3770. }
  3771. unset($users);
  3772. }
  3773. }
  3774. // Make sure this request came from the login form.
  3775. if (!\core\session\manager::validate_login_token($logintoken)) {
  3776. $failurereason = AUTH_LOGIN_FAILED;
  3777. // Trigger login failed event (specifying the ID of the found user, if available).
  3778. \core\event\user_login_failed::create([
  3779. 'userid' => ($user->id ?? 0),
  3780. 'other' => [
  3781. 'username' => $username,
  3782. 'reason' => $failurereason,
  3783. ],
  3784. ])->trigger();
  3785. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Invalid Login Token: $username ".$_SERVER['HTTP_USER_AGENT']);
  3786. return false;
  3787. }
  3788. $authsenabled = get_enabled_auth_plugins();
  3789. if ($user) {
  3790. // Use manual if auth not set.
  3791. $auth = empty($user->auth) ? 'manual' : $user->auth;
  3792. if (in_array($user->auth, $authsenabled)) {
  3793. $authplugin = get_auth_plugin($user->auth);
  3794. $authplugin->pre_user_login_hook($user);
  3795. }
  3796. if (!empty($user->suspended)) {
  3797. $failurereason = AUTH_LOGIN_SUSPENDED;
  3798. // Trigger login failed event.
  3799. $event = \core\event\user_login_failed::create(array('userid' => $user->id,
  3800. 'other' => array('username' => $username, 'reason' => $failurereason)));
  3801. $event->trigger();
  3802. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3803. return false;
  3804. }
  3805. if ($auth=='nologin' or !is_enabled_auth($auth)) {
  3806. // Legacy way to suspend user.
  3807. $failurereason = AUTH_LOGIN_SUSPENDED;
  3808. // Trigger login failed event.
  3809. $event = \core\event\user_login_failed::create(array('userid' => $user->id,
  3810. 'other' => array('username' => $username, 'reason' => $failurereason)));
  3811. $event->trigger();
  3812. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3813. return false;
  3814. }
  3815. $auths = array($auth);
  3816. } else {
  3817. // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
  3818. if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
  3819. $failurereason = AUTH_LOGIN_NOUSER;
  3820. // Trigger login failed event.
  3821. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
  3822. 'reason' => $failurereason)));
  3823. $event->trigger();
  3824. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3825. return false;
  3826. }
  3827. // User does not exist.
  3828. $auths = $authsenabled;
  3829. $user = new stdClass();
  3830. $user->id = 0;
  3831. }
  3832. if ($ignorelockout) {
  3833. // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
  3834. // or this function is called from a SSO script.
  3835. } else if ($user->id) {
  3836. // Verify login lockout after other ways that may prevent user login.
  3837. if (login_is_lockedout($user)) {
  3838. $failurereason = AUTH_LOGIN_LOCKOUT;
  3839. // Trigger login failed event.
  3840. $event = \core\event\user_login_failed::create(array('userid' => $user->id,
  3841. 'other' => array('username' => $username, 'reason' => $failurereason)));
  3842. $event->trigger();
  3843. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
  3844. return false;
  3845. }
  3846. } else {
  3847. // We can not lockout non-existing accounts.
  3848. }
  3849. foreach ($auths as $auth) {
  3850. $authplugin = get_auth_plugin($auth);
  3851. // On auth fail fall through to the next plugin.
  3852. if (!$authplugin->user_login($username, $password)) {
  3853. continue;
  3854. }
  3855. // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
  3856. if (!empty($CFG->passwordpolicycheckonlogin)) {
  3857. $errmsg = '';
  3858. $passed = check_password_policy($password, $errmsg, $user);
  3859. if (!$passed) {
  3860. // First trigger event for failure.
  3861. $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
  3862. $failedevent->trigger();
  3863. // If able to change password, set flag and move on.
  3864. if ($authplugin->can_change_password()) {
  3865. // Check if we are on internal change password page, or service is external, don't show notification.
  3866. $internalchangeurl = new moodle_url('/login/change_password.php');
  3867. if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
  3868. \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
  3869. }
  3870. set_user_preference('auth_forcepasswordchange', 1, $user);
  3871. } else if ($authplugin->can_reset_password()) {
  3872. // Else force a reset if possible.
  3873. \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
  3874. redirect(new moodle_url('/login/forgot_password.php'));
  3875. } else {
  3876. $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
  3877. // If support page is set, add link for help.
  3878. if (!empty($CFG->supportpage)) {
  3879. $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
  3880. $link = \html_writer::tag('p', $link);
  3881. $notifymsg .= $link;
  3882. }
  3883. // If no change or reset is possible, add a notification for user.
  3884. \core\notification::error($notifymsg);
  3885. }
  3886. }
  3887. }
  3888. // Successful authentication.
  3889. if ($user->id) {
  3890. // User already exists in database.
  3891. if (empty($user->auth)) {
  3892. // For some reason auth isn't set yet.
  3893. $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
  3894. $user->auth = $auth;
  3895. }
  3896. // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
  3897. // the current hash algorithm while we have access to the user's password.
  3898. update_internal_user_password($user, $password);
  3899. if ($authplugin->is_synchronised_with_external()) {
  3900. // Update user record from external DB.
  3901. $user = update_user_record_by_id($user->id);
  3902. }
  3903. } else {
  3904. // The user is authenticated but user creation may be disabled.
  3905. if (!empty($CFG->authpreventaccountcreation)) {
  3906. $failurereason = AUTH_LOGIN_UNAUTHORISED;
  3907. // Trigger login failed event.
  3908. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
  3909. 'reason' => $failurereason)));
  3910. $event->trigger();
  3911. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".
  3912. $_SERVER['HTTP_USER_AGENT']);
  3913. return false;
  3914. } else {
  3915. $user = create_user_record($username, $password, $auth);
  3916. }
  3917. }
  3918. $authplugin->sync_roles($user);
  3919. foreach ($authsenabled as $hau) {
  3920. $hauth = get_auth_plugin($hau);
  3921. $hauth->user_authenticated_hook($user, $username, $password);
  3922. }
  3923. if (empty($user->id)) {
  3924. $failurereason = AUTH_LOGIN_NOUSER;
  3925. // Trigger login failed event.
  3926. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
  3927. 'reason' => $failurereason)));
  3928. $event->trigger();
  3929. return false;
  3930. }
  3931. if (!empty($user->suspended)) {
  3932. // Just in case some auth plugin suspended account.
  3933. $failurereason = AUTH_LOGIN_SUSPENDED;
  3934. // Trigger login failed event.
  3935. $event = \core\event\user_login_failed::create(array('userid' => $user->id,
  3936. 'other' => array('username' => $username, 'reason' => $failurereason)));
  3937. $event->trigger();
  3938. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3939. return false;
  3940. }
  3941. login_attempt_valid($user);
  3942. $failurereason = AUTH_LOGIN_OK;
  3943. return $user;
  3944. }
  3945. // Failed if all the plugins have failed.
  3946. if (debugging('', DEBUG_ALL)) {
  3947. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3948. }
  3949. if ($user->id) {
  3950. login_attempt_failed($user);
  3951. $failurereason = AUTH_LOGIN_FAILED;
  3952. // Trigger login failed event.
  3953. $event = \core\event\user_login_failed::create(array('userid' => $user->id,
  3954. 'other' => array('username' => $username, 'reason' => $failurereason)));
  3955. $event->trigger();
  3956. } else {
  3957. $failurereason = AUTH_LOGIN_NOUSER;
  3958. // Trigger login failed event.
  3959. $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
  3960. 'reason' => $failurereason)));
  3961. $event->trigger();
  3962. }
  3963. return false;
  3964. }
  3965. /**
  3966. * Call to complete the user login process after authenticate_user_login()
  3967. * has succeeded. It will setup the $USER variable and other required bits
  3968. * and pieces.
  3969. *
  3970. * NOTE:
  3971. * - It will NOT log anything -- up to the caller to decide what to log.
  3972. * - this function does not set any cookies any more!
  3973. *
  3974. * @param stdClass $user
  3975. * @return stdClass A {@link $USER} object - BC only, do not use
  3976. */
  3977. function complete_user_login($user) {
  3978. global $CFG, $DB, $USER, $SESSION;
  3979. \core\session\manager::login_user($user);
  3980. // Reload preferences from DB.
  3981. unset($USER->preference);
  3982. check_user_preferences_loaded($USER);
  3983. // Update login times.
  3984. update_user_login_times();
  3985. // Extra session prefs init.
  3986. set_login_session_preferences();
  3987. // Trigger login event.
  3988. $event = \core\event\user_loggedin::create(
  3989. array(
  3990. 'userid' => $USER->id,
  3991. 'objectid' => $USER->id,
  3992. 'other' => array('username' => $USER->username),
  3993. )
  3994. );
  3995. $event->trigger();
  3996. // Queue migrating the messaging data, if we need to.
  3997. if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
  3998. // Check if there are any legacy messages to migrate.
  3999. if (\core_message\helper::legacy_messages_exist($USER->id)) {
  4000. \core_message\task\migrate_message_data::queue_task($USER->id);
  4001. } else {
  4002. set_user_preference('core_message_migrate_data', true, $USER->id);
  4003. }
  4004. }
  4005. if (isguestuser()) {
  4006. // No need to continue when user is THE guest.
  4007. return $USER;
  4008. }
  4009. if (CLI_SCRIPT) {
  4010. // We can redirect to password change URL only in browser.
  4011. return $USER;
  4012. }
  4013. // Select password change url.
  4014. $userauth = get_auth_plugin($USER->auth);
  4015. // Check whether the user should be changing password.
  4016. if (get_user_preferences('auth_forcepasswordchange', false)) {
  4017. if ($userauth->can_change_password()) {
  4018. if ($changeurl = $userauth->change_password_url()) {
  4019. redirect($changeurl);
  4020. } else {
  4021. require_once($CFG->dirroot . '/login/lib.php');
  4022. $SESSION->wantsurl = core_login_get_return_url();
  4023. redirect($CFG->wwwroot.'/login/change_password.php');
  4024. }
  4025. } else {
  4026. print_error('nopasswordchangeforced', 'auth');
  4027. }
  4028. }
  4029. return $USER;
  4030. }
  4031. /**
  4032. * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
  4033. *
  4034. * @param string $password String to check.
  4035. * @return boolean True if the $password matches the format of an md5 sum.
  4036. */
  4037. function password_is_legacy_hash($password) {
  4038. return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
  4039. }
  4040. /**
  4041. * Compare password against hash stored in user object to determine if it is valid.
  4042. *
  4043. * If necessary it also updates the stored hash to the current format.
  4044. *
  4045. * @param stdClass $user (Password property may be updated).
  4046. * @param string $password Plain text password.
  4047. * @return bool True if password is valid.
  4048. */
  4049. function validate_internal_user_password($user, $password) {
  4050. global $CFG;
  4051. if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
  4052. // Internal password is not used at all, it can not validate.
  4053. return false;
  4054. }
  4055. // If hash isn't a legacy (md5) hash, validate using the library function.
  4056. if (!password_is_legacy_hash($user->password)) {
  4057. return password_verify($password, $user->password);
  4058. }
  4059. // Otherwise we need to check for a legacy (md5) hash instead. If the hash
  4060. // is valid we can then update it to the new algorithm.
  4061. $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
  4062. $validated = false;
  4063. if ($user->password === md5($password.$sitesalt)
  4064. or $user->password === md5($password)
  4065. or $user->password === md5(addslashes($password).$sitesalt)
  4066. or $user->password === md5(addslashes($password))) {
  4067. // Note: we are intentionally using the addslashes() here because we
  4068. // need to accept old password hashes of passwords with magic quotes.
  4069. $validated = true;
  4070. } else {
  4071. for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
  4072. $alt = 'passwordsaltalt'.$i;
  4073. if (!empty($CFG->$alt)) {
  4074. if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
  4075. $validated = true;
  4076. break;
  4077. }
  4078. }
  4079. }
  4080. }
  4081. if ($validated) {
  4082. // If the password matches the existing md5 hash, update to the
  4083. // current hash algorithm while we have access to the user's password.
  4084. update_internal_user_password($user, $password);
  4085. }
  4086. return $validated;
  4087. }
  4088. /**
  4089. * Calculate hash for a plain text password.
  4090. *
  4091. * @param string $password Plain text password to be hashed.
  4092. * @param bool $fasthash If true, use a low cost factor when generating the hash
  4093. * This is much faster to generate but makes the hash
  4094. * less secure. It is used when lots of hashes need to
  4095. * be generated quickly.
  4096. * @return string The hashed password.
  4097. *
  4098. * @throws moodle_exception If a problem occurs while generating the hash.
  4099. */
  4100. function hash_internal_user_password($password, $fasthash = false) {
  4101. global $CFG;
  4102. // Set the cost factor to 4 for fast hashing, otherwise use default cost.
  4103. $options = ($fasthash) ? array('cost' => 4) : array();
  4104. $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
  4105. if ($generatedhash === false || $generatedhash === null) {
  4106. throw new moodle_exception('Failed to generate password hash.');
  4107. }
  4108. return $generatedhash;
  4109. }
  4110. /**
  4111. * Update password hash in user object (if necessary).
  4112. *
  4113. * The password is updated if:
  4114. * 1. The password has changed (the hash of $user->password is different
  4115. * to the hash of $password).
  4116. * 2. The existing hash is using an out-of-date algorithm (or the legacy
  4117. * md5 algorithm).
  4118. *
  4119. * Updating the password will modify the $user object and the database
  4120. * record to use the current hashing algorithm.
  4121. * It will remove Web Services user tokens too.
  4122. *
  4123. * @param stdClass $user User object (password property may be updated).
  4124. * @param string $password Plain text password.
  4125. * @param bool $fasthash If true, use a low cost factor when generating the hash
  4126. * This is much faster to generate but makes the hash
  4127. * less secure. It is used when lots of hashes need to
  4128. * be generated quickly.
  4129. * @return bool Always returns true.
  4130. */
  4131. function update_internal_user_password($user, $password, $fasthash = false) {
  4132. global $CFG, $DB;
  4133. // Figure out what the hashed password should be.
  4134. if (!isset($user->auth)) {
  4135. debugging('User record in update_internal_user_password() must include field auth',
  4136. DEBUG_DEVELOPER);
  4137. $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
  4138. }
  4139. $authplugin = get_auth_plugin($user->auth);
  4140. if ($authplugin->prevent_local_passwords()) {
  4141. $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
  4142. } else {
  4143. $hashedpassword = hash_internal_user_password($password, $fasthash);
  4144. }
  4145. $algorithmchanged = false;
  4146. if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
  4147. // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
  4148. $passwordchanged = ($user->password !== $hashedpassword);
  4149. } else if (isset($user->password)) {
  4150. // If verification fails then it means the password has changed.
  4151. $passwordchanged = !password_verify($password, $user->password);
  4152. $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
  4153. } else {
  4154. // While creating new user, password in unset in $user object, to avoid
  4155. // saving it with user_create()
  4156. $passwordchanged = true;
  4157. }
  4158. if ($passwordchanged || $algorithmchanged) {
  4159. $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
  4160. $user->password = $hashedpassword;
  4161. // Trigger event.
  4162. $user = $DB->get_record('user', array('id' => $user->id));
  4163. \core\event\user_password_updated::create_from_user($user)->trigger();
  4164. // Remove WS user tokens.
  4165. if (!empty($CFG->passwordchangetokendeletion)) {
  4166. require_once($CFG->dirroot.'/webservice/lib.php');
  4167. webservice::delete_user_ws_tokens($user->id);
  4168. }
  4169. }
  4170. return true;
  4171. }
  4172. /**
  4173. * Get a complete user record, which includes all the info in the user record.
  4174. *
  4175. * Intended for setting as $USER session variable
  4176. *
  4177. * @param string $field The user field to be checked for a given value.
  4178. * @param string $value The value to match for $field.
  4179. * @param int $mnethostid
  4180. * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
  4181. * found. Otherwise, it will just return false.
  4182. * @return mixed False, or A {@link $USER} object.
  4183. */
  4184. function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
  4185. global $CFG, $DB;
  4186. if (!$field || !$value) {
  4187. return false;
  4188. }
  4189. // Change the field to lowercase.
  4190. $field = core_text::strtolower($field);
  4191. // List of case insensitive fields.
  4192. $caseinsensitivefields = ['email'];
  4193. // Username input is forced to lowercase and should be case sensitive.
  4194. if ($field == 'username') {
  4195. $value = core_text::strtolower($value);
  4196. }
  4197. // Build the WHERE clause for an SQL query.
  4198. $params = array('fieldval' => $value);
  4199. // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
  4200. // such as MySQL by pre-filtering users with accent-insensitive subselect.
  4201. if (in_array($field, $caseinsensitivefields)) {
  4202. $fieldselect = $DB->sql_equal($field, ':fieldval', false);
  4203. $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
  4204. $params['fieldval2'] = $value;
  4205. } else {
  4206. $fieldselect = "$field = :fieldval";
  4207. $idsubselect = '';
  4208. }
  4209. $constraints = "$fieldselect AND deleted <> 1";
  4210. // If we are loading user data based on anything other than id,
  4211. // we must also restrict our search based on mnet host.
  4212. if ($field != 'id') {
  4213. if (empty($mnethostid)) {
  4214. // If empty, we restrict to local users.
  4215. $mnethostid = $CFG->mnet_localhost_id;
  4216. }
  4217. }
  4218. if (!empty($mnethostid)) {
  4219. $params['mnethostid'] = $mnethostid;
  4220. $constraints .= " AND mnethostid = :mnethostid";
  4221. }
  4222. if ($idsubselect) {
  4223. $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
  4224. }
  4225. // Get all the basic user data.
  4226. try {
  4227. // Make sure that there's only a single record that matches our query.
  4228. // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
  4229. // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
  4230. $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
  4231. } catch (dml_exception $exception) {
  4232. if ($throwexception) {
  4233. throw $exception;
  4234. } else {
  4235. // Return false when no records or multiple records were found.
  4236. return false;
  4237. }
  4238. }
  4239. // Get various settings and preferences.
  4240. // Preload preference cache.
  4241. check_user_preferences_loaded($user);
  4242. // Load course enrolment related stuff.
  4243. $user->lastcourseaccess = array(); // During last session.
  4244. $user->currentcourseaccess = array(); // During current session.
  4245. if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
  4246. foreach ($lastaccesses as $lastaccess) {
  4247. $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
  4248. }
  4249. }
  4250. $sql = "SELECT g.id, g.courseid
  4251. FROM {groups} g, {groups_members} gm
  4252. WHERE gm.groupid=g.id AND gm.userid=?";
  4253. // This is a special hack to speedup calendar display.
  4254. $user->groupmember = array();
  4255. if (!isguestuser($user)) {
  4256. if ($groups = $DB->get_records_sql($sql, array($user->id))) {
  4257. foreach ($groups as $group) {
  4258. if (!array_key_exists($group->courseid, $user->groupmember)) {
  4259. $user->groupmember[$group->courseid] = array();
  4260. }
  4261. $user->groupmember[$group->courseid][$group->id] = $group->id;
  4262. }
  4263. }
  4264. }
  4265. // Add cohort theme.
  4266. if (!empty($CFG->allowcohortthemes)) {
  4267. require_once($CFG->dirroot . '/cohort/lib.php');
  4268. if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
  4269. $user->cohorttheme = $cohorttheme;
  4270. }
  4271. }
  4272. // Add the custom profile fields to the user record.
  4273. $user->profile = array();
  4274. if (!isguestuser($user)) {
  4275. require_once($CFG->dirroot.'/user/profile/lib.php');
  4276. profile_load_custom_fields($user);
  4277. }
  4278. // Rewrite some variables if necessary.
  4279. if (!empty($user->description)) {
  4280. // No need to cart all of it around.
  4281. $user->description = true;
  4282. }
  4283. if (isguestuser($user)) {
  4284. // Guest language always same as site.
  4285. $user->lang = get_newuser_language();
  4286. // Name always in current language.
  4287. $user->firstname = get_string('guestuser');
  4288. $user->lastname = ' ';
  4289. }
  4290. return $user;
  4291. }
  4292. /**
  4293. * Validate a password against the configured password policy
  4294. *
  4295. * @param string $password the password to be checked against the password policy
  4296. * @param string $errmsg the error message to display when the password doesn't comply with the policy.
  4297. * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
  4298. *
  4299. * @return bool true if the password is valid according to the policy. false otherwise.
  4300. */
  4301. function check_password_policy($password, &$errmsg, $user = null) {
  4302. global $CFG;
  4303. if (!empty($CFG->passwordpolicy)) {
  4304. $errmsg = '';
  4305. if (core_text::strlen($password) < $CFG->minpasswordlength) {
  4306. $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
  4307. }
  4308. if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
  4309. $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
  4310. }
  4311. if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
  4312. $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
  4313. }
  4314. if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
  4315. $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
  4316. }
  4317. if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
  4318. $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
  4319. }
  4320. if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
  4321. $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
  4322. }
  4323. // Fire any additional password policy functions from plugins.
  4324. // Plugin functions should output an error message string or empty string for success.
  4325. $pluginsfunction = get_plugins_with_function('check_password_policy');
  4326. foreach ($pluginsfunction as $plugintype => $plugins) {
  4327. foreach ($plugins as $pluginfunction) {
  4328. $pluginerr = $pluginfunction($password, $user);
  4329. if ($pluginerr) {
  4330. $errmsg .= '<div>'. $pluginerr .'</div>';
  4331. }
  4332. }
  4333. }
  4334. }
  4335. if ($errmsg == '') {
  4336. return true;
  4337. } else {
  4338. return false;
  4339. }
  4340. }
  4341. /**
  4342. * When logging in, this function is run to set certain preferences for the current SESSION.
  4343. */
  4344. function set_login_session_preferences() {
  4345. global $SESSION;
  4346. $SESSION->justloggedin = true;
  4347. unset($SESSION->lang);
  4348. unset($SESSION->forcelang);
  4349. unset($SESSION->load_navigation_admin);
  4350. }
  4351. /**
  4352. * Delete a course, including all related data from the database, and any associated files.
  4353. *
  4354. * @param mixed $courseorid The id of the course or course object to delete.
  4355. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  4356. * @return bool true if all the removals succeeded. false if there were any failures. If this
  4357. * method returns false, some of the removals will probably have succeeded, and others
  4358. * failed, but you have no way of knowing which.
  4359. */
  4360. function delete_course($courseorid, $showfeedback = true) {
  4361. global $DB;
  4362. if (is_object($courseorid)) {
  4363. $courseid = $courseorid->id;
  4364. $course = $courseorid;
  4365. } else {
  4366. $courseid = $courseorid;
  4367. if (!$course = $DB->get_record('course', array('id' => $courseid))) {
  4368. return false;
  4369. }
  4370. }
  4371. $context = context_course::instance($courseid);
  4372. // Frontpage course can not be deleted!!
  4373. if ($courseid == SITEID) {
  4374. return false;
  4375. }
  4376. // Allow plugins to use this course before we completely delete it.
  4377. if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
  4378. foreach ($pluginsfunction as $plugintype => $plugins) {
  4379. foreach ($plugins as $pluginfunction) {
  4380. $pluginfunction($course);
  4381. }
  4382. }
  4383. }
  4384. // Tell the search manager we are about to delete a course. This prevents us sending updates
  4385. // for each individual context being deleted.
  4386. \core_search\manager::course_deleting_start($courseid);
  4387. $handler = core_course\customfield\course_handler::create();
  4388. $handler->delete_instance($courseid);
  4389. // Make the course completely empty.
  4390. remove_course_contents($courseid, $showfeedback);
  4391. // Delete the course and related context instance.
  4392. context_helper::delete_instance(CONTEXT_COURSE, $courseid);
  4393. $DB->delete_records("course", array("id" => $courseid));
  4394. $DB->delete_records("course_format_options", array("courseid" => $courseid));
  4395. // Reset all course related caches here.
  4396. core_courseformat\base::reset_course_cache($courseid);
  4397. // Tell search that we have deleted the course so it can delete course data from the index.
  4398. \core_search\manager::course_deleting_finish($courseid);
  4399. // Trigger a course deleted event.
  4400. $event = \core\event\course_deleted::create(array(
  4401. 'objectid' => $course->id,
  4402. 'context' => $context,
  4403. 'other' => array(
  4404. 'shortname' => $course->shortname,
  4405. 'fullname' => $course->fullname,
  4406. 'idnumber' => $course->idnumber
  4407. )
  4408. ));
  4409. $event->add_record_snapshot('course', $course);
  4410. $event->trigger();
  4411. return true;
  4412. }
  4413. /**
  4414. * Clear a course out completely, deleting all content but don't delete the course itself.
  4415. *
  4416. * This function does not verify any permissions.
  4417. *
  4418. * Please note this function also deletes all user enrolments,
  4419. * enrolment instances and role assignments by default.
  4420. *
  4421. * $options:
  4422. * - 'keep_roles_and_enrolments' - false by default
  4423. * - 'keep_groups_and_groupings' - false by default
  4424. *
  4425. * @param int $courseid The id of the course that is being deleted
  4426. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  4427. * @param array $options extra options
  4428. * @return bool true if all the removals succeeded. false if there were any failures. If this
  4429. * method returns false, some of the removals will probably have succeeded, and others
  4430. * failed, but you have no way of knowing which.
  4431. */
  4432. function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
  4433. global $CFG, $DB, $OUTPUT;
  4434. require_once($CFG->libdir.'/badgeslib.php');
  4435. require_once($CFG->libdir.'/completionlib.php');
  4436. require_once($CFG->libdir.'/questionlib.php');
  4437. require_once($CFG->libdir.'/gradelib.php');
  4438. require_once($CFG->dirroot.'/group/lib.php');
  4439. require_once($CFG->dirroot.'/comment/lib.php');
  4440. require_once($CFG->dirroot.'/rating/lib.php');
  4441. require_once($CFG->dirroot.'/notes/lib.php');
  4442. // Handle course badges.
  4443. badges_handle_course_deletion($courseid);
  4444. // NOTE: these concatenated strings are suboptimal, but it is just extra info...
  4445. $strdeleted = get_string('deleted').' - ';
  4446. // Some crazy wishlist of stuff we should skip during purging of course content.
  4447. $options = (array)$options;
  4448. $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
  4449. $coursecontext = context_course::instance($courseid);
  4450. $fs = get_file_storage();
  4451. // Delete course completion information, this has to be done before grades and enrols.
  4452. $cc = new completion_info($course);
  4453. $cc->clear_criteria();
  4454. if ($showfeedback) {
  4455. echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
  4456. }
  4457. // Remove all data from gradebook - this needs to be done before course modules
  4458. // because while deleting this information, the system may need to reference
  4459. // the course modules that own the grades.
  4460. remove_course_grades($courseid, $showfeedback);
  4461. remove_grade_letters($coursecontext, $showfeedback);
  4462. // Delete course blocks in any all child contexts,
  4463. // they may depend on modules so delete them first.
  4464. $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
  4465. foreach ($childcontexts as $childcontext) {
  4466. blocks_delete_all_for_context($childcontext->id);
  4467. }
  4468. unset($childcontexts);
  4469. blocks_delete_all_for_context($coursecontext->id);
  4470. if ($showfeedback) {
  4471. echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
  4472. }
  4473. $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
  4474. rebuild_course_cache($courseid, true);
  4475. // Get the list of all modules that are properly installed.
  4476. $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
  4477. // Delete every instance of every module,
  4478. // this has to be done before deleting of course level stuff.
  4479. $locations = core_component::get_plugin_list('mod');
  4480. foreach ($locations as $modname => $moddir) {
  4481. if ($modname === 'NEWMODULE') {
  4482. continue;
  4483. }
  4484. if (array_key_exists($modname, $allmodules)) {
  4485. $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
  4486. FROM {".$modname."} m
  4487. LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
  4488. WHERE m.course = :courseid";
  4489. $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
  4490. 'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
  4491. include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
  4492. $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
  4493. if ($instances) {
  4494. foreach ($instances as $cm) {
  4495. if ($cm->id) {
  4496. // Delete activity context questions and question categories.
  4497. question_delete_activity($cm);
  4498. // Notify the competency subsystem.
  4499. \core_competency\api::hook_course_module_deleted($cm);
  4500. }
  4501. if (function_exists($moddelete)) {
  4502. // This purges all module data in related tables, extra user prefs, settings, etc.
  4503. $moddelete($cm->modinstance);
  4504. } else {
  4505. // NOTE: we should not allow installation of modules with missing delete support!
  4506. debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
  4507. $DB->delete_records($modname, array('id' => $cm->modinstance));
  4508. }
  4509. if ($cm->id) {
  4510. // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
  4511. context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
  4512. $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
  4513. $DB->delete_records('course_modules', array('id' => $cm->id));
  4514. rebuild_course_cache($cm->course, true);
  4515. }
  4516. }
  4517. }
  4518. if ($instances and $showfeedback) {
  4519. echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
  4520. }
  4521. } else {
  4522. // Ooops, this module is not properly installed, force-delete it in the next block.
  4523. }
  4524. }
  4525. // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
  4526. // Delete completion defaults.
  4527. $DB->delete_records("course_completion_defaults", array("course" => $courseid));
  4528. // Remove all data from availability and completion tables that is associated
  4529. // with course-modules belonging to this course. Note this is done even if the
  4530. // features are not enabled now, in case they were enabled previously.
  4531. $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
  4532. 'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
  4533. // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
  4534. $cms = $DB->get_records('course_modules', array('course' => $course->id));
  4535. $allmodulesbyid = array_flip($allmodules);
  4536. foreach ($cms as $cm) {
  4537. if (array_key_exists($cm->module, $allmodulesbyid)) {
  4538. try {
  4539. $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
  4540. } catch (Exception $e) {
  4541. // Ignore weird or missing table problems.
  4542. }
  4543. }
  4544. context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
  4545. $DB->delete_records('course_modules', array('id' => $cm->id));
  4546. rebuild_course_cache($cm->course, true);
  4547. }
  4548. if ($showfeedback) {
  4549. echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
  4550. }
  4551. // Delete questions and question categories.
  4552. question_delete_course($course);
  4553. if ($showfeedback) {
  4554. echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
  4555. }
  4556. // Delete content bank contents.
  4557. $cb = new \core_contentbank\contentbank();
  4558. $cbdeleted = $cb->delete_contents($coursecontext);
  4559. if ($showfeedback && $cbdeleted) {
  4560. echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
  4561. }
  4562. // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
  4563. $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
  4564. foreach ($childcontexts as $childcontext) {
  4565. $childcontext->delete();
  4566. }
  4567. unset($childcontexts);
  4568. // Remove roles and enrolments by default.
  4569. if (empty($options['keep_roles_and_enrolments'])) {
  4570. // This hack is used in restore when deleting contents of existing course.
  4571. // During restore, we should remove only enrolment related data that the user performing the restore has a
  4572. // permission to remove.
  4573. $userid = $options['userid'] ?? null;
  4574. enrol_course_delete($course, $userid);
  4575. role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
  4576. if ($showfeedback) {
  4577. echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
  4578. }
  4579. }
  4580. // Delete any groups, removing members and grouping/course links first.
  4581. if (empty($options['keep_groups_and_groupings'])) {
  4582. groups_delete_groupings($course->id, $showfeedback);
  4583. groups_delete_groups($course->id, $showfeedback);
  4584. }
  4585. // Filters be gone!
  4586. filter_delete_all_for_context($coursecontext->id);
  4587. // Notes, you shall not pass!
  4588. note_delete_all($course->id);
  4589. // Die comments!
  4590. comment::delete_comments($coursecontext->id);
  4591. // Ratings are history too.
  4592. $delopt = new stdclass();
  4593. $delopt->contextid = $coursecontext->id;
  4594. $rm = new rating_manager();
  4595. $rm->delete_ratings($delopt);
  4596. // Delete course tags.
  4597. core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
  4598. // Give the course format the opportunity to remove its obscure data.
  4599. $format = course_get_format($course);
  4600. $format->delete_format_data();
  4601. // Notify the competency subsystem.
  4602. \core_competency\api::hook_course_deleted($course);
  4603. // Delete calendar events.
  4604. $DB->delete_records('event', array('courseid' => $course->id));
  4605. $fs->delete_area_files($coursecontext->id, 'calendar');
  4606. // Delete all related records in other core tables that may have a courseid
  4607. // This array stores the tables that need to be cleared, as
  4608. // table_name => column_name that contains the course id.
  4609. $tablestoclear = array(
  4610. 'backup_courses' => 'courseid', // Scheduled backup stuff.
  4611. 'user_lastaccess' => 'courseid', // User access info.
  4612. );
  4613. foreach ($tablestoclear as $table => $col) {
  4614. $DB->delete_records($table, array($col => $course->id));
  4615. }
  4616. // Delete all course backup files.
  4617. $fs->delete_area_files($coursecontext->id, 'backup');
  4618. // Cleanup course record - remove links to deleted stuff.
  4619. $oldcourse = new stdClass();
  4620. $oldcourse->id = $course->id;
  4621. $oldcourse->summary = '';
  4622. $oldcourse->cacherev = 0;
  4623. $oldcourse->legacyfiles = 0;
  4624. if (!empty($options['keep_groups_and_groupings'])) {
  4625. $oldcourse->defaultgroupingid = 0;
  4626. }
  4627. $DB->update_record('course', $oldcourse);
  4628. // Delete course sections.
  4629. $DB->delete_records('course_sections', array('course' => $course->id));
  4630. // Delete legacy, section and any other course files.
  4631. $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
  4632. // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
  4633. if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
  4634. // Easy, do not delete the context itself...
  4635. $coursecontext->delete_content();
  4636. } else {
  4637. // Hack alert!!!!
  4638. // We can not drop all context stuff because it would bork enrolments and roles,
  4639. // there might be also files used by enrol plugins...
  4640. }
  4641. // Delete legacy files - just in case some files are still left there after conversion to new file api,
  4642. // also some non-standard unsupported plugins may try to store something there.
  4643. fulldelete($CFG->dataroot.'/'.$course->id);
  4644. // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
  4645. $cachemodinfo = cache::make('core', 'coursemodinfo');
  4646. $cachemodinfo->delete($courseid);
  4647. // Trigger a course content deleted event.
  4648. $event = \core\event\course_content_deleted::create(array(
  4649. 'objectid' => $course->id,
  4650. 'context' => $coursecontext,
  4651. 'other' => array('shortname' => $course->shortname,
  4652. 'fullname' => $course->fullname,
  4653. 'options' => $options) // Passing this for legacy reasons.
  4654. ));
  4655. $event->add_record_snapshot('course', $course);
  4656. $event->trigger();
  4657. return true;
  4658. }
  4659. /**
  4660. * Change dates in module - used from course reset.
  4661. *
  4662. * @param string $modname forum, assignment, etc
  4663. * @param array $fields array of date fields from mod table
  4664. * @param int $timeshift time difference
  4665. * @param int $courseid
  4666. * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
  4667. * @return bool success
  4668. */
  4669. function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
  4670. global $CFG, $DB;
  4671. include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
  4672. $return = true;
  4673. $params = array($timeshift, $courseid);
  4674. foreach ($fields as $field) {
  4675. $updatesql = "UPDATE {".$modname."}
  4676. SET $field = $field + ?
  4677. WHERE course=? AND $field<>0";
  4678. if ($modid) {
  4679. $updatesql .= ' AND id=?';
  4680. $params[] = $modid;
  4681. }
  4682. $return = $DB->execute($updatesql, $params) && $return;
  4683. }
  4684. return $return;
  4685. }
  4686. /**
  4687. * This function will empty a course of user data.
  4688. * It will retain the activities and the structure of the course.
  4689. *
  4690. * @param object $data an object containing all the settings including courseid (without magic quotes)
  4691. * @return array status array of array component, item, error
  4692. */
  4693. function reset_course_userdata($data) {
  4694. global $CFG, $DB;
  4695. require_once($CFG->libdir.'/gradelib.php');
  4696. require_once($CFG->libdir.'/completionlib.php');
  4697. require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
  4698. require_once($CFG->dirroot.'/group/lib.php');
  4699. $data->courseid = $data->id;
  4700. $context = context_course::instance($data->courseid);
  4701. $eventparams = array(
  4702. 'context' => $context,
  4703. 'courseid' => $data->id,
  4704. 'other' => array(
  4705. 'reset_options' => (array) $data
  4706. )
  4707. );
  4708. $event = \core\event\course_reset_started::create($eventparams);
  4709. $event->trigger();
  4710. // Calculate the time shift of dates.
  4711. if (!empty($data->reset_start_date)) {
  4712. // Time part of course startdate should be zero.
  4713. $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
  4714. } else {
  4715. $data->timeshift = 0;
  4716. }
  4717. // Result array: component, item, error.
  4718. $status = array();
  4719. // Start the resetting.
  4720. $componentstr = get_string('general');
  4721. // Move the course start time.
  4722. if (!empty($data->reset_start_date) and $data->timeshift) {
  4723. // Change course start data.
  4724. $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
  4725. // Update all course and group events - do not move activity events.
  4726. $updatesql = "UPDATE {event}
  4727. SET timestart = timestart + ?
  4728. WHERE courseid=? AND instance=0";
  4729. $DB->execute($updatesql, array($data->timeshift, $data->courseid));
  4730. // Update any date activity restrictions.
  4731. if ($CFG->enableavailability) {
  4732. \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
  4733. }
  4734. // Update completion expected dates.
  4735. if ($CFG->enablecompletion) {
  4736. $modinfo = get_fast_modinfo($data->courseid);
  4737. $changed = false;
  4738. foreach ($modinfo->get_cms() as $cm) {
  4739. if ($cm->completion && !empty($cm->completionexpected)) {
  4740. $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
  4741. array('id' => $cm->id));
  4742. $changed = true;
  4743. }
  4744. }
  4745. // Clear course cache if changes made.
  4746. if ($changed) {
  4747. rebuild_course_cache($data->courseid, true);
  4748. }
  4749. // Update course date completion criteria.
  4750. \completion_criteria_date::update_date($data->courseid, $data->timeshift);
  4751. }
  4752. $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
  4753. }
  4754. if (!empty($data->reset_end_date)) {
  4755. // If the user set a end date value respect it.
  4756. $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
  4757. } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
  4758. // If there is a time shift apply it to the end date as well.
  4759. $enddate = $data->reset_end_date_old + $data->timeshift;
  4760. $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
  4761. }
  4762. if (!empty($data->reset_events)) {
  4763. $DB->delete_records('event', array('courseid' => $data->courseid));
  4764. $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
  4765. }
  4766. if (!empty($data->reset_notes)) {
  4767. require_once($CFG->dirroot.'/notes/lib.php');
  4768. note_delete_all($data->courseid);
  4769. $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
  4770. }
  4771. if (!empty($data->delete_blog_associations)) {
  4772. require_once($CFG->dirroot.'/blog/lib.php');
  4773. blog_remove_associations_for_course($data->courseid);
  4774. $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
  4775. }
  4776. if (!empty($data->reset_completion)) {
  4777. // Delete course and activity completion information.
  4778. $course = $DB->get_record('course', array('id' => $data->courseid));
  4779. $cc = new completion_info($course);
  4780. $cc->delete_all_completion_data();
  4781. $status[] = array('component' => $componentstr,
  4782. 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
  4783. }
  4784. if (!empty($data->reset_competency_ratings)) {
  4785. \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
  4786. $status[] = array('component' => $componentstr,
  4787. 'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
  4788. }
  4789. $componentstr = get_string('roles');
  4790. if (!empty($data->reset_roles_overrides)) {
  4791. $children = $context->get_child_contexts();
  4792. foreach ($children as $child) {
  4793. $child->delete_capabilities();
  4794. }
  4795. $context->delete_capabilities();
  4796. $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
  4797. }
  4798. if (!empty($data->reset_roles_local)) {
  4799. $children = $context->get_child_contexts();
  4800. foreach ($children as $child) {
  4801. role_unassign_all(array('contextid' => $child->id));
  4802. }
  4803. $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
  4804. }
  4805. // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
  4806. $data->unenrolled = array();
  4807. if (!empty($data->unenrol_users)) {
  4808. $plugins = enrol_get_plugins(true);
  4809. $instances = enrol_get_instances($data->courseid, true);
  4810. foreach ($instances as $key => $instance) {
  4811. if (!isset($plugins[$instance->enrol])) {
  4812. unset($instances[$key]);
  4813. continue;
  4814. }
  4815. }
  4816. $usersroles = enrol_get_course_users_roles($data->courseid);
  4817. foreach ($data->unenrol_users as $withroleid) {
  4818. if ($withroleid) {
  4819. $sql = "SELECT ue.*
  4820. FROM {user_enrolments} ue
  4821. JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
  4822. JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
  4823. JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
  4824. $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
  4825. } else {
  4826. // Without any role assigned at course context.
  4827. $sql = "SELECT ue.*
  4828. FROM {user_enrolments} ue
  4829. JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
  4830. JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
  4831. LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
  4832. WHERE ra.id IS null";
  4833. $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
  4834. }
  4835. $rs = $DB->get_recordset_sql($sql, $params);
  4836. foreach ($rs as $ue) {
  4837. if (!isset($instances[$ue->enrolid])) {
  4838. continue;
  4839. }
  4840. $instance = $instances[$ue->enrolid];
  4841. $plugin = $plugins[$instance->enrol];
  4842. if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
  4843. continue;
  4844. }
  4845. if ($withroleid && count($usersroles[$ue->userid]) > 1) {
  4846. // If we don't remove all roles and user has more than one role, just remove this role.
  4847. role_unassign($withroleid, $ue->userid, $context->id);
  4848. unset($usersroles[$ue->userid][$withroleid]);
  4849. } else {
  4850. // If we remove all roles or user has only one role, unenrol user from course.
  4851. $plugin->unenrol_user($instance, $ue->userid);
  4852. }
  4853. $data->unenrolled[$ue->userid] = $ue->userid;
  4854. }
  4855. $rs->close();
  4856. }
  4857. }
  4858. if (!empty($data->unenrolled)) {
  4859. $status[] = array(
  4860. 'component' => $componentstr,
  4861. 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
  4862. 'error' => false
  4863. );
  4864. }
  4865. $componentstr = get_string('groups');
  4866. // Remove all group members.
  4867. if (!empty($data->reset_groups_members)) {
  4868. groups_delete_group_members($data->courseid);
  4869. $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
  4870. }
  4871. // Remove all groups.
  4872. if (!empty($data->reset_groups_remove)) {
  4873. groups_delete_groups($data->courseid, false);
  4874. $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
  4875. }
  4876. // Remove all grouping members.
  4877. if (!empty($data->reset_groupings_members)) {
  4878. groups_delete_groupings_groups($data->courseid, false);
  4879. $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
  4880. }
  4881. // Remove all groupings.
  4882. if (!empty($data->reset_groupings_remove)) {
  4883. groups_delete_groupings($data->courseid, false);
  4884. $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
  4885. }
  4886. // Look in every instance of every module for data to delete.
  4887. $unsupportedmods = array();
  4888. if ($allmods = $DB->get_records('modules') ) {
  4889. foreach ($allmods as $mod) {
  4890. $modname = $mod->name;
  4891. $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
  4892. $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
  4893. if (file_exists($modfile)) {
  4894. if (!$DB->count_records($modname, array('course' => $data->courseid))) {
  4895. continue; // Skip mods with no instances.
  4896. }
  4897. include_once($modfile);
  4898. if (function_exists($moddeleteuserdata)) {
  4899. $modstatus = $moddeleteuserdata($data);
  4900. if (is_array($modstatus)) {
  4901. $status = array_merge($status, $modstatus);
  4902. } else {
  4903. debugging('Module '.$modname.' returned incorrect staus - must be an array!');
  4904. }
  4905. } else {
  4906. $unsupportedmods[] = $mod;
  4907. }
  4908. } else {
  4909. debugging('Missing lib.php in '.$modname.' module!');
  4910. }
  4911. // Update calendar events for all modules.
  4912. course_module_bulk_update_calendar_events($modname, $data->courseid);
  4913. }
  4914. }
  4915. // Mention unsupported mods.
  4916. if (!empty($unsupportedmods)) {
  4917. foreach ($unsupportedmods as $mod) {
  4918. $status[] = array(
  4919. 'component' => get_string('modulenameplural', $mod->name),
  4920. 'item' => '',
  4921. 'error' => get_string('resetnotimplemented')
  4922. );
  4923. }
  4924. }
  4925. $componentstr = get_string('gradebook', 'grades');
  4926. // Reset gradebook,.
  4927. if (!empty($data->reset_gradebook_items)) {
  4928. remove_course_grades($data->courseid, false);
  4929. grade_grab_course_grades($data->courseid);
  4930. grade_regrade_final_grades($data->courseid);
  4931. $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
  4932. } else if (!empty($data->reset_gradebook_grades)) {
  4933. grade_course_reset($data->courseid);
  4934. $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
  4935. }
  4936. // Reset comments.
  4937. if (!empty($data->reset_comments)) {
  4938. require_once($CFG->dirroot.'/comment/lib.php');
  4939. comment::reset_course_page_comments($context);
  4940. }
  4941. $event = \core\event\course_reset_ended::create($eventparams);
  4942. $event->trigger();
  4943. return $status;
  4944. }
  4945. /**
  4946. * Generate an email processing address.
  4947. *
  4948. * @param int $modid
  4949. * @param string $modargs
  4950. * @return string Returns email processing address
  4951. */
  4952. function generate_email_processing_address($modid, $modargs) {
  4953. global $CFG;
  4954. $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
  4955. return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
  4956. }
  4957. /**
  4958. * ?
  4959. *
  4960. * @todo Finish documenting this function
  4961. *
  4962. * @param string $modargs
  4963. * @param string $body Currently unused
  4964. */
  4965. function moodle_process_email($modargs, $body) {
  4966. global $DB;
  4967. // The first char should be an unencoded letter. We'll take this as an action.
  4968. switch ($modargs[0]) {
  4969. case 'B': { // Bounce.
  4970. list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
  4971. if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
  4972. // Check the half md5 of their email.
  4973. $md5check = substr(md5($user->email), 0, 16);
  4974. if ($md5check == substr($modargs, -16)) {
  4975. set_bounce_count($user);
  4976. }
  4977. // Else maybe they've already changed it?
  4978. }
  4979. }
  4980. break;
  4981. // Maybe more later?
  4982. }
  4983. }
  4984. // CORRESPONDENCE.
  4985. /**
  4986. * Get mailer instance, enable buffering, flush buffer or disable buffering.
  4987. *
  4988. * @param string $action 'get', 'buffer', 'close' or 'flush'
  4989. * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
  4990. */
  4991. function get_mailer($action='get') {
  4992. global $CFG;
  4993. /** @var moodle_phpmailer $mailer */
  4994. static $mailer = null;
  4995. static $counter = 0;
  4996. if (!isset($CFG->smtpmaxbulk)) {
  4997. $CFG->smtpmaxbulk = 1;
  4998. }
  4999. if ($action == 'get') {
  5000. $prevkeepalive = false;
  5001. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  5002. if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
  5003. $counter++;
  5004. // Reset the mailer.
  5005. $mailer->Priority = 3;
  5006. $mailer->CharSet = 'UTF-8'; // Our default.
  5007. $mailer->ContentType = "text/plain";
  5008. $mailer->Encoding = "8bit";
  5009. $mailer->From = "root@localhost";
  5010. $mailer->FromName = "Root User";
  5011. $mailer->Sender = "";
  5012. $mailer->Subject = "";
  5013. $mailer->Body = "";
  5014. $mailer->AltBody = "";
  5015. $mailer->ConfirmReadingTo = "";
  5016. $mailer->clearAllRecipients();
  5017. $mailer->clearReplyTos();
  5018. $mailer->clearAttachments();
  5019. $mailer->clearCustomHeaders();
  5020. return $mailer;
  5021. }
  5022. $prevkeepalive = $mailer->SMTPKeepAlive;
  5023. get_mailer('flush');
  5024. }
  5025. require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
  5026. $mailer = new moodle_phpmailer();
  5027. $counter = 1;
  5028. if ($CFG->smtphosts == 'qmail') {
  5029. // Use Qmail system.
  5030. $mailer->isQmail();
  5031. } else if (empty($CFG->smtphosts)) {
  5032. // Use PHP mail() = sendmail.
  5033. $mailer->isMail();
  5034. } else {
  5035. // Use SMTP directly.
  5036. $mailer->isSMTP();
  5037. if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
  5038. $mailer->SMTPDebug = 3;
  5039. }
  5040. // Specify main and backup servers.
  5041. $mailer->Host = $CFG->smtphosts;
  5042. // Specify secure connection protocol.
  5043. $mailer->SMTPSecure = $CFG->smtpsecure;
  5044. // Use previous keepalive.
  5045. $mailer->SMTPKeepAlive = $prevkeepalive;
  5046. if ($CFG->smtpuser) {
  5047. // Use SMTP authentication.
  5048. $mailer->SMTPAuth = true;
  5049. $mailer->Username = $CFG->smtpuser;
  5050. $mailer->Password = $CFG->smtppass;
  5051. }
  5052. }
  5053. return $mailer;
  5054. }
  5055. $nothing = null;
  5056. // Keep smtp session open after sending.
  5057. if ($action == 'buffer') {
  5058. if (!empty($CFG->smtpmaxbulk)) {
  5059. get_mailer('flush');
  5060. $m = get_mailer();
  5061. if ($m->Mailer == 'smtp') {
  5062. $m->SMTPKeepAlive = true;
  5063. }
  5064. }
  5065. return $nothing;
  5066. }
  5067. // Close smtp session, but continue buffering.
  5068. if ($action == 'flush') {
  5069. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  5070. if (!empty($mailer->SMTPDebug)) {
  5071. echo '<pre>'."\n";
  5072. }
  5073. $mailer->SmtpClose();
  5074. if (!empty($mailer->SMTPDebug)) {
  5075. echo '</pre>';
  5076. }
  5077. }
  5078. return $nothing;
  5079. }
  5080. // Close smtp session, do not buffer anymore.
  5081. if ($action == 'close') {
  5082. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  5083. get_mailer('flush');
  5084. $mailer->SMTPKeepAlive = false;
  5085. }
  5086. $mailer = null; // Better force new instance.
  5087. return $nothing;
  5088. }
  5089. }
  5090. /**
  5091. * A helper function to test for email diversion
  5092. *
  5093. * @param string $email
  5094. * @return bool Returns true if the email should be diverted
  5095. */
  5096. function email_should_be_diverted($email) {
  5097. global $CFG;
  5098. if (empty($CFG->divertallemailsto)) {
  5099. return false;
  5100. }
  5101. if (empty($CFG->divertallemailsexcept)) {
  5102. return true;
  5103. }
  5104. $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept));
  5105. foreach ($patterns as $pattern) {
  5106. if (preg_match("/$pattern/", $email)) {
  5107. return false;
  5108. }
  5109. }
  5110. return true;
  5111. }
  5112. /**
  5113. * Generate a unique email Message-ID using the moodle domain and install path
  5114. *
  5115. * @param string $localpart An optional unique message id prefix.
  5116. * @return string The formatted ID ready for appending to the email headers.
  5117. */
  5118. function generate_email_messageid($localpart = null) {
  5119. global $CFG;
  5120. $urlinfo = parse_url($CFG->wwwroot);
  5121. $base = '@' . $urlinfo['host'];
  5122. // If multiple moodles are on the same domain we want to tell them
  5123. // apart so we add the install path to the local part. This means
  5124. // that the id local part should never contain a / character so
  5125. // we can correctly parse the id to reassemble the wwwroot.
  5126. if (isset($urlinfo['path'])) {
  5127. $base = $urlinfo['path'] . $base;
  5128. }
  5129. if (empty($localpart)) {
  5130. $localpart = uniqid('', true);
  5131. }
  5132. // Because we may have an option /installpath suffix to the local part
  5133. // of the id we need to escape any / chars which are in the $localpart.
  5134. $localpart = str_replace('/', '%2F', $localpart);
  5135. return '<' . $localpart . $base . '>';
  5136. }
  5137. /**
  5138. * Send an email to a specified user
  5139. *
  5140. * @param stdClass $user A {@link $USER} object
  5141. * @param stdClass $from A {@link $USER} object
  5142. * @param string $subject plain text subject line of the email
  5143. * @param string $messagetext plain text version of the message
  5144. * @param string $messagehtml complete html version of the message (optional)
  5145. * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
  5146. * the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
  5147. * @param string $attachname the name of the file (extension indicates MIME)
  5148. * @param bool $usetrueaddress determines whether $from email address should
  5149. * be sent out. Will be overruled by user profile setting for maildisplay
  5150. * @param string $replyto Email address to reply to
  5151. * @param string $replytoname Name of reply to recipient
  5152. * @param int $wordwrapwidth custom word wrap width, default 79
  5153. * @return bool Returns true if mail was sent OK and false if there was an error.
  5154. */
  5155. function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
  5156. $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
  5157. global $CFG, $PAGE, $SITE;
  5158. if (empty($user) or empty($user->id)) {
  5159. debugging('Can not send email to null user', DEBUG_DEVELOPER);
  5160. return false;
  5161. }
  5162. if (empty($user->email)) {
  5163. debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
  5164. return false;
  5165. }
  5166. if (!empty($user->deleted)) {
  5167. debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
  5168. return false;
  5169. }
  5170. if (defined('BEHAT_SITE_RUNNING')) {
  5171. // Fake email sending in behat.
  5172. return true;
  5173. }
  5174. if (!empty($CFG->noemailever)) {
  5175. // Hidden setting for development sites, set in config.php if needed.
  5176. debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
  5177. return true;
  5178. }
  5179. if (email_should_be_diverted($user->email)) {
  5180. $subject = "[DIVERTED {$user->email}] $subject";
  5181. $user = clone($user);
  5182. $user->email = $CFG->divertallemailsto;
  5183. }
  5184. // Skip mail to suspended users.
  5185. if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
  5186. return true;
  5187. }
  5188. if (!validate_email($user->email)) {
  5189. // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
  5190. debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
  5191. return false;
  5192. }
  5193. if (over_bounce_threshold($user)) {
  5194. debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
  5195. return false;
  5196. }
  5197. // TLD .invalid is specifically reserved for invalid domain names.
  5198. // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
  5199. if (substr($user->email, -8) == '.invalid') {
  5200. debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
  5201. return true; // This is not an error.
  5202. }
  5203. // If the user is a remote mnet user, parse the email text for URL to the
  5204. // wwwroot and modify the url to direct the user's browser to login at their
  5205. // home site (identity provider - idp) before hitting the link itself.
  5206. if (is_mnet_remote_user($user)) {
  5207. require_once($CFG->dirroot.'/mnet/lib.php');
  5208. $jumpurl = mnet_get_idp_jump_url($user);
  5209. $callback = partial('mnet_sso_apply_indirection', $jumpurl);
  5210. $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
  5211. $callback,
  5212. $messagetext);
  5213. $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
  5214. $callback,
  5215. $messagehtml);
  5216. }
  5217. $mail = get_mailer();
  5218. if (!empty($mail->SMTPDebug)) {
  5219. echo '<pre>' . "\n";
  5220. }
  5221. $temprecipients = array();
  5222. $tempreplyto = array();
  5223. // Make sure that we fall back onto some reasonable no-reply address.
  5224. $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
  5225. $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
  5226. if (!validate_email($noreplyaddress)) {
  5227. debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
  5228. $noreplyaddress = $noreplyaddressdefault;
  5229. }
  5230. // Make up an email address for handling bounces.
  5231. if (!empty($CFG->handlebounces)) {
  5232. $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
  5233. $mail->Sender = generate_email_processing_address(0, $modargs);
  5234. } else {
  5235. $mail->Sender = $noreplyaddress;
  5236. }
  5237. // Make sure that the explicit replyto is valid, fall back to the implicit one.
  5238. if (!empty($replyto) && !validate_email($replyto)) {
  5239. debugging('email_to_user: Invalid replyto-email '.s($replyto));
  5240. $replyto = $noreplyaddress;
  5241. }
  5242. if (is_string($from)) { // So we can pass whatever we want if there is need.
  5243. $mail->From = $noreplyaddress;
  5244. $mail->FromName = $from;
  5245. // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
  5246. // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
  5247. // in a course with the sender.
  5248. } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
  5249. if (!validate_email($from->email)) {
  5250. debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
  5251. // Better not to use $noreplyaddress in this case.
  5252. return false;
  5253. }
  5254. $mail->From = $from->email;
  5255. $fromdetails = new stdClass();
  5256. $fromdetails->name = fullname($from);
  5257. $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
  5258. $fromdetails->siteshortname = format_string($SITE->shortname);
  5259. $fromstring = $fromdetails->name;
  5260. if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
  5261. $fromstring = get_string('emailvia', 'core', $fromdetails);
  5262. }
  5263. $mail->FromName = $fromstring;
  5264. if (empty($replyto)) {
  5265. $tempreplyto[] = array($from->email, fullname($from));
  5266. }
  5267. } else {
  5268. $mail->From = $noreplyaddress;
  5269. $fromdetails = new stdClass();
  5270. $fromdetails->name = fullname($from);
  5271. $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
  5272. $fromdetails->siteshortname = format_string($SITE->shortname);
  5273. $fromstring = $fromdetails->name;
  5274. if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
  5275. $fromstring = get_string('emailvia', 'core', $fromdetails);
  5276. }
  5277. $mail->FromName = $fromstring;
  5278. if (empty($replyto)) {
  5279. $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
  5280. }
  5281. }
  5282. if (!empty($replyto)) {
  5283. $tempreplyto[] = array($replyto, $replytoname);
  5284. }
  5285. $temprecipients[] = array($user->email, fullname($user));
  5286. // Set word wrap.
  5287. $mail->WordWrap = $wordwrapwidth;
  5288. if (!empty($from->customheaders)) {
  5289. // Add custom headers.
  5290. if (is_array($from->customheaders)) {
  5291. foreach ($from->customheaders as $customheader) {
  5292. $mail->addCustomHeader($customheader);
  5293. }
  5294. } else {
  5295. $mail->addCustomHeader($from->customheaders);
  5296. }
  5297. }
  5298. // If the X-PHP-Originating-Script email header is on then also add an additional
  5299. // header with details of where exactly in moodle the email was triggered from,
  5300. // either a call to message_send() or to email_to_user().
  5301. if (ini_get('mail.add_x_header')) {
  5302. $stack = debug_backtrace(false);
  5303. $origin = $stack[0];
  5304. foreach ($stack as $depth => $call) {
  5305. if ($call['function'] == 'message_send') {
  5306. $origin = $call;
  5307. }
  5308. }
  5309. $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
  5310. . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
  5311. $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
  5312. }
  5313. if (!empty($CFG->emailheaders)) {
  5314. $headers = array_map('trim', explode("\n", $CFG->emailheaders));
  5315. foreach ($headers as $header) {
  5316. if (!empty($header)) {
  5317. $mail->addCustomHeader($header);
  5318. }
  5319. }
  5320. }
  5321. if (!empty($from->priority)) {
  5322. $mail->Priority = $from->priority;
  5323. }
  5324. $renderer = $PAGE->get_renderer('core');
  5325. $context = array(
  5326. 'sitefullname' => $SITE->fullname,
  5327. 'siteshortname' => $SITE->shortname,
  5328. 'sitewwwroot' => $CFG->wwwroot,
  5329. 'subject' => $subject,
  5330. 'prefix' => $CFG->emailsubjectprefix,
  5331. 'to' => $user->email,
  5332. 'toname' => fullname($user),
  5333. 'from' => $mail->From,
  5334. 'fromname' => $mail->FromName,
  5335. );
  5336. if (!empty($tempreplyto[0])) {
  5337. $context['replyto'] = $tempreplyto[0][0];
  5338. $context['replytoname'] = $tempreplyto[0][1];
  5339. }
  5340. if ($user->id > 0) {
  5341. $context['touserid'] = $user->id;
  5342. $context['tousername'] = $user->username;
  5343. }
  5344. if (!empty($user->mailformat) && $user->mailformat == 1) {
  5345. // Only process html templates if the user preferences allow html email.
  5346. if (!$messagehtml) {
  5347. // If no html has been given, BUT there is an html wrapping template then
  5348. // auto convert the text to html and then wrap it.
  5349. $messagehtml = trim(text_to_html($messagetext));
  5350. }
  5351. $context['body'] = $messagehtml;
  5352. $messagehtml = $renderer->render_from_template('core/email_html', $context);
  5353. }
  5354. $context['body'] = html_to_text(nl2br($messagetext));
  5355. $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
  5356. $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
  5357. $messagetext = $renderer->render_from_template('core/email_text', $context);
  5358. // Autogenerate a MessageID if it's missing.
  5359. if (empty($mail->MessageID)) {
  5360. $mail->MessageID = generate_email_messageid();
  5361. }
  5362. if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
  5363. // Don't ever send HTML to users who don't want it.
  5364. $mail->isHTML(true);
  5365. $mail->Encoding = 'quoted-printable';
  5366. $mail->Body = $messagehtml;
  5367. $mail->AltBody = "\n$messagetext\n";
  5368. } else {
  5369. $mail->IsHTML(false);
  5370. $mail->Body = "\n$messagetext\n";
  5371. }
  5372. if ($attachment && $attachname) {
  5373. if (preg_match( "~\\.\\.~" , $attachment )) {
  5374. // Security check for ".." in dir path.
  5375. $supportuser = core_user::get_support_user();
  5376. $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
  5377. $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
  5378. } else {
  5379. require_once($CFG->libdir.'/filelib.php');
  5380. $mimetype = mimeinfo('type', $attachname);
  5381. // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
  5382. // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
  5383. $attachpath = str_replace('\\', '/', realpath($attachment));
  5384. // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
  5385. $allowedpaths = array_map(function(string $path): string {
  5386. return str_replace('\\', '/', realpath($path));
  5387. }, [
  5388. $CFG->cachedir,
  5389. $CFG->dataroot,
  5390. $CFG->dirroot,
  5391. $CFG->localcachedir,
  5392. $CFG->tempdir,
  5393. $CFG->localrequestdir,
  5394. ]);
  5395. // Set addpath to true.
  5396. $addpath = true;
  5397. // Check if attachment includes one of the allowed paths.
  5398. foreach (array_filter($allowedpaths) as $allowedpath) {
  5399. // Set addpath to false if the attachment includes one of the allowed paths.
  5400. if (strpos($attachpath, $allowedpath) === 0) {
  5401. $addpath = false;
  5402. break;
  5403. }
  5404. }
  5405. // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
  5406. // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
  5407. if ($addpath == true) {
  5408. $attachment = $CFG->dataroot . '/' . $attachment;
  5409. }
  5410. $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
  5411. }
  5412. }
  5413. // Check if the email should be sent in an other charset then the default UTF-8.
  5414. if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
  5415. // Use the defined site mail charset or eventually the one preferred by the recipient.
  5416. $charset = $CFG->sitemailcharset;
  5417. if (!empty($CFG->allowusermailcharset)) {
  5418. if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
  5419. $charset = $useremailcharset;
  5420. }
  5421. }
  5422. // Convert all the necessary strings if the charset is supported.
  5423. $charsets = get_list_of_charsets();
  5424. unset($charsets['UTF-8']);
  5425. if (in_array($charset, $charsets)) {
  5426. $mail->CharSet = $charset;
  5427. $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
  5428. $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
  5429. $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
  5430. $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
  5431. foreach ($temprecipients as $key => $values) {
  5432. $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
  5433. }
  5434. foreach ($tempreplyto as $key => $values) {
  5435. $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
  5436. }
  5437. }
  5438. }
  5439. foreach ($temprecipients as $values) {
  5440. $mail->addAddress($values[0], $values[1]);
  5441. }
  5442. foreach ($tempreplyto as $values) {
  5443. $mail->addReplyTo($values[0], $values[1]);
  5444. }
  5445. if (!empty($CFG->emaildkimselector)) {
  5446. $domain = substr(strrchr($mail->From, "@"), 1);
  5447. $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
  5448. if (file_exists($pempath)) {
  5449. $mail->DKIM_domain = $domain;
  5450. $mail->DKIM_private = $pempath;
  5451. $mail->DKIM_selector = $CFG->emaildkimselector;
  5452. $mail->DKIM_identity = $mail->From;
  5453. } else {
  5454. debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
  5455. }
  5456. }
  5457. if ($mail->send()) {
  5458. set_send_count($user);
  5459. if (!empty($mail->SMTPDebug)) {
  5460. echo '</pre>';
  5461. }
  5462. return true;
  5463. } else {
  5464. // Trigger event for failing to send email.
  5465. $event = \core\event\email_failed::create(array(
  5466. 'context' => context_system::instance(),
  5467. 'userid' => $from->id,
  5468. 'relateduserid' => $user->id,
  5469. 'other' => array(
  5470. 'subject' => $subject,
  5471. 'message' => $messagetext,
  5472. 'errorinfo' => $mail->ErrorInfo
  5473. )
  5474. ));
  5475. $event->trigger();
  5476. if (CLI_SCRIPT) {
  5477. mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
  5478. }
  5479. if (!empty($mail->SMTPDebug)) {
  5480. echo '</pre>';
  5481. }
  5482. return false;
  5483. }
  5484. }
  5485. /**
  5486. * Check to see if a user's real email address should be used for the "From" field.
  5487. *
  5488. * @param object $from The user object for the user we are sending the email from.
  5489. * @param object $user The user object that we are sending the email to.
  5490. * @param array $unused No longer used.
  5491. * @return bool Returns true if we can use the from user's email adress in the "From" field.
  5492. */
  5493. function can_send_from_real_email_address($from, $user, $unused = null) {
  5494. global $CFG;
  5495. if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
  5496. return false;
  5497. }
  5498. $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
  5499. // Email is in the list of allowed domains for sending email,
  5500. // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
  5501. // in a course with the sender.
  5502. if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
  5503. && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
  5504. || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
  5505. && enrol_get_shared_courses($user, $from, false, true)))) {
  5506. return true;
  5507. }
  5508. return false;
  5509. }
  5510. /**
  5511. * Generate a signoff for emails based on support settings
  5512. *
  5513. * @return string
  5514. */
  5515. function generate_email_signoff() {
  5516. global $CFG;
  5517. $signoff = "\n";
  5518. if (!empty($CFG->supportname)) {
  5519. $signoff .= $CFG->supportname."\n";
  5520. }
  5521. if (!empty($CFG->supportemail)) {
  5522. $signoff .= $CFG->supportemail."\n";
  5523. }
  5524. if (!empty($CFG->supportpage)) {
  5525. $signoff .= $CFG->supportpage."\n";
  5526. }
  5527. return $signoff;
  5528. }
  5529. /**
  5530. * Sets specified user's password and send the new password to the user via email.
  5531. *
  5532. * @param stdClass $user A {@link $USER} object
  5533. * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
  5534. * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
  5535. */
  5536. function setnew_password_and_mail($user, $fasthash = false) {
  5537. global $CFG, $DB;
  5538. // We try to send the mail in language the user understands,
  5539. // unfortunately the filter_string() does not support alternative langs yet
  5540. // so multilang will not work properly for site->fullname.
  5541. $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
  5542. $site = get_site();
  5543. $supportuser = core_user::get_support_user();
  5544. $newpassword = generate_password();
  5545. update_internal_user_password($user, $newpassword, $fasthash);
  5546. $a = new stdClass();
  5547. $a->firstname = fullname($user, true);
  5548. $a->sitename = format_string($site->fullname);
  5549. $a->username = $user->username;
  5550. $a->newpassword = $newpassword;
  5551. $a->link = $CFG->wwwroot .'/login/?lang='.$lang;
  5552. $a->signoff = generate_email_signoff();
  5553. $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
  5554. $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
  5555. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5556. return email_to_user($user, $supportuser, $subject, $message);
  5557. }
  5558. /**
  5559. * Resets specified user's password and send the new password to the user via email.
  5560. *
  5561. * @param stdClass $user A {@link $USER} object
  5562. * @return bool Returns true if mail was sent OK and false if there was an error.
  5563. */
  5564. function reset_password_and_mail($user) {
  5565. global $CFG;
  5566. $site = get_site();
  5567. $supportuser = core_user::get_support_user();
  5568. $userauth = get_auth_plugin($user->auth);
  5569. if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
  5570. trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
  5571. return false;
  5572. }
  5573. $newpassword = generate_password();
  5574. if (!$userauth->user_update_password($user, $newpassword)) {
  5575. print_error("cannotsetpassword");
  5576. }
  5577. $a = new stdClass();
  5578. $a->firstname = $user->firstname;
  5579. $a->lastname = $user->lastname;
  5580. $a->sitename = format_string($site->fullname);
  5581. $a->username = $user->username;
  5582. $a->newpassword = $newpassword;
  5583. $a->link = $CFG->wwwroot .'/login/change_password.php';
  5584. $a->signoff = generate_email_signoff();
  5585. $message = get_string('newpasswordtext', '', $a);
  5586. $subject = format_string($site->fullname) .': '. get_string('changedpassword');
  5587. unset_user_preference('create_password', $user); // Prevent cron from generating the password.
  5588. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5589. return email_to_user($user, $supportuser, $subject, $message);
  5590. }
  5591. /**
  5592. * Send email to specified user with confirmation text and activation link.
  5593. *
  5594. * @param stdClass $user A {@link $USER} object
  5595. * @param string $confirmationurl user confirmation URL
  5596. * @return bool Returns true if mail was sent OK and false if there was an error.
  5597. */
  5598. function send_confirmation_email($user, $confirmationurl = null) {
  5599. global $CFG;
  5600. $site = get_site();
  5601. $supportuser = core_user::get_support_user();
  5602. $data = new stdClass();
  5603. $data->sitename = format_string($site->fullname);
  5604. $data->admin = generate_email_signoff();
  5605. $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
  5606. if (empty($confirmationurl)) {
  5607. $confirmationurl = '/login/confirm.php';
  5608. }
  5609. $confirmationurl = new moodle_url($confirmationurl);
  5610. // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
  5611. $confirmationurl->remove_params('data');
  5612. $confirmationpath = $confirmationurl->out(false);
  5613. // We need to custom encode the username to include trailing dots in the link.
  5614. // Because of this custom encoding we can't use moodle_url directly.
  5615. // Determine if a query string is present in the confirmation url.
  5616. $hasquerystring = strpos($confirmationpath, '?') !== false;
  5617. // Perform normal url encoding of the username first.
  5618. $username = urlencode($user->username);
  5619. // Prevent problems with trailing dots not being included as part of link in some mail clients.
  5620. $username = str_replace('.', '%2E', $username);
  5621. $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
  5622. $message = get_string('emailconfirmation', '', $data);
  5623. $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
  5624. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5625. return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
  5626. }
  5627. /**
  5628. * Sends a password change confirmation email.
  5629. *
  5630. * @param stdClass $user A {@link $USER} object
  5631. * @param stdClass $resetrecord An object tracking metadata regarding password reset request
  5632. * @return bool Returns true if mail was sent OK and false if there was an error.
  5633. */
  5634. function send_password_change_confirmation_email($user, $resetrecord) {
  5635. global $CFG;
  5636. $site = get_site();
  5637. $supportuser = core_user::get_support_user();
  5638. $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
  5639. $data = new stdClass();
  5640. $data->firstname = $user->firstname;
  5641. $data->lastname = $user->lastname;
  5642. $data->username = $user->username;
  5643. $data->sitename = format_string($site->fullname);
  5644. $data->link = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
  5645. $data->admin = generate_email_signoff();
  5646. $data->resetminutes = $pwresetmins;
  5647. $message = get_string('emailresetconfirmation', '', $data);
  5648. $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
  5649. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5650. return email_to_user($user, $supportuser, $subject, $message);
  5651. }
  5652. /**
  5653. * Sends an email containing information on how to change your password.
  5654. *
  5655. * @param stdClass $user A {@link $USER} object
  5656. * @return bool Returns true if mail was sent OK and false if there was an error.
  5657. */
  5658. function send_password_change_info($user) {
  5659. $site = get_site();
  5660. $supportuser = core_user::get_support_user();
  5661. $data = new stdClass();
  5662. $data->firstname = $user->firstname;
  5663. $data->lastname = $user->lastname;
  5664. $data->username = $user->username;
  5665. $data->sitename = format_string($site->fullname);
  5666. $data->admin = generate_email_signoff();
  5667. if (!is_enabled_auth($user->auth)) {
  5668. $message = get_string('emailpasswordchangeinfodisabled', '', $data);
  5669. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  5670. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5671. return email_to_user($user, $supportuser, $subject, $message);
  5672. }
  5673. $userauth = get_auth_plugin($user->auth);
  5674. ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
  5675. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5676. return email_to_user($user, $supportuser, $subject, $message);
  5677. }
  5678. /**
  5679. * Check that an email is allowed. It returns an error message if there was a problem.
  5680. *
  5681. * @param string $email Content of email
  5682. * @return string|false
  5683. */
  5684. function email_is_not_allowed($email) {
  5685. global $CFG;
  5686. // Comparing lowercase domains.
  5687. $email = strtolower($email);
  5688. if (!empty($CFG->allowemailaddresses)) {
  5689. $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
  5690. foreach ($allowed as $allowedpattern) {
  5691. $allowedpattern = trim($allowedpattern);
  5692. if (!$allowedpattern) {
  5693. continue;
  5694. }
  5695. if (strpos($allowedpattern, '.') === 0) {
  5696. if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
  5697. // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
  5698. return false;
  5699. }
  5700. } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
  5701. return false;
  5702. }
  5703. }
  5704. return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
  5705. } else if (!empty($CFG->denyemailaddresses)) {
  5706. $denied = explode(' ', strtolower($CFG->denyemailaddresses));
  5707. foreach ($denied as $deniedpattern) {
  5708. $deniedpattern = trim($deniedpattern);
  5709. if (!$deniedpattern) {
  5710. continue;
  5711. }
  5712. if (strpos($deniedpattern, '.') === 0) {
  5713. if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
  5714. // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
  5715. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  5716. }
  5717. } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
  5718. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  5719. }
  5720. }
  5721. }
  5722. return false;
  5723. }
  5724. // FILE HANDLING.
  5725. /**
  5726. * Returns local file storage instance
  5727. *
  5728. * @return file_storage
  5729. */
  5730. function get_file_storage($reset = false) {
  5731. global $CFG;
  5732. static $fs = null;
  5733. if ($reset) {
  5734. $fs = null;
  5735. return;
  5736. }
  5737. if ($fs) {
  5738. return $fs;
  5739. }
  5740. require_once("$CFG->libdir/filelib.php");
  5741. $fs = new file_storage();
  5742. return $fs;
  5743. }
  5744. /**
  5745. * Returns local file storage instance
  5746. *
  5747. * @return file_browser
  5748. */
  5749. function get_file_browser() {
  5750. global $CFG;
  5751. static $fb = null;
  5752. if ($fb) {
  5753. return $fb;
  5754. }
  5755. require_once("$CFG->libdir/filelib.php");
  5756. $fb = new file_browser();
  5757. return $fb;
  5758. }
  5759. /**
  5760. * Returns file packer
  5761. *
  5762. * @param string $mimetype default application/zip
  5763. * @return file_packer
  5764. */
  5765. function get_file_packer($mimetype='application/zip') {
  5766. global $CFG;
  5767. static $fp = array();
  5768. if (isset($fp[$mimetype])) {
  5769. return $fp[$mimetype];
  5770. }
  5771. switch ($mimetype) {
  5772. case 'application/zip':
  5773. case 'application/vnd.moodle.profiling':
  5774. $classname = 'zip_packer';
  5775. break;
  5776. case 'application/x-gzip' :
  5777. $classname = 'tgz_packer';
  5778. break;
  5779. case 'application/vnd.moodle.backup':
  5780. $classname = 'mbz_packer';
  5781. break;
  5782. default:
  5783. return false;
  5784. }
  5785. require_once("$CFG->libdir/filestorage/$classname.php");
  5786. $fp[$mimetype] = new $classname();
  5787. return $fp[$mimetype];
  5788. }
  5789. /**
  5790. * Returns current name of file on disk if it exists.
  5791. *
  5792. * @param string $newfile File to be verified
  5793. * @return string Current name of file on disk if true
  5794. */
  5795. function valid_uploaded_file($newfile) {
  5796. if (empty($newfile)) {
  5797. return '';
  5798. }
  5799. if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
  5800. return $newfile['tmp_name'];
  5801. } else {
  5802. return '';
  5803. }
  5804. }
  5805. /**
  5806. * Returns the maximum size for uploading files.
  5807. *
  5808. * There are seven possible upload limits:
  5809. * 1. in Apache using LimitRequestBody (no way of checking or changing this)
  5810. * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
  5811. * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
  5812. * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
  5813. * 5. by the Moodle admin in $CFG->maxbytes
  5814. * 6. by the teacher in the current course $course->maxbytes
  5815. * 7. by the teacher for the current module, eg $assignment->maxbytes
  5816. *
  5817. * These last two are passed to this function as arguments (in bytes).
  5818. * Anything defined as 0 is ignored.
  5819. * The smallest of all the non-zero numbers is returned.
  5820. *
  5821. * @todo Finish documenting this function
  5822. *
  5823. * @param int $sitebytes Set maximum size
  5824. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5825. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5826. * @param bool $unused This parameter has been deprecated and is not used any more.
  5827. * @return int The maximum size for uploading files.
  5828. */
  5829. function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
  5830. if (! $filesize = ini_get('upload_max_filesize')) {
  5831. $filesize = '5M';
  5832. }
  5833. $minimumsize = get_real_size($filesize);
  5834. if ($postsize = ini_get('post_max_size')) {
  5835. $postsize = get_real_size($postsize);
  5836. if ($postsize < $minimumsize) {
  5837. $minimumsize = $postsize;
  5838. }
  5839. }
  5840. if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
  5841. $minimumsize = $sitebytes;
  5842. }
  5843. if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
  5844. $minimumsize = $coursebytes;
  5845. }
  5846. if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
  5847. $minimumsize = $modulebytes;
  5848. }
  5849. return $minimumsize;
  5850. }
  5851. /**
  5852. * Returns the maximum size for uploading files for the current user
  5853. *
  5854. * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
  5855. *
  5856. * @param context $context The context in which to check user capabilities
  5857. * @param int $sitebytes Set maximum size
  5858. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5859. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5860. * @param stdClass $user The user
  5861. * @param bool $unused This parameter has been deprecated and is not used any more.
  5862. * @return int The maximum size for uploading files.
  5863. */
  5864. function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
  5865. $unused = false) {
  5866. global $USER;
  5867. if (empty($user)) {
  5868. $user = $USER;
  5869. }
  5870. if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
  5871. return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
  5872. }
  5873. return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
  5874. }
  5875. /**
  5876. * Returns an array of possible sizes in local language
  5877. *
  5878. * Related to {@link get_max_upload_file_size()} - this function returns an
  5879. * array of possible sizes in an array, translated to the
  5880. * local language.
  5881. *
  5882. * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
  5883. *
  5884. * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
  5885. * with the value set to 0. This option will be the first in the list.
  5886. *
  5887. * @uses SORT_NUMERIC
  5888. * @param int $sitebytes Set maximum size
  5889. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5890. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5891. * @param int|array $custombytes custom upload size/s which will be added to list,
  5892. * Only value/s smaller then maxsize will be added to list.
  5893. * @return array
  5894. */
  5895. function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
  5896. global $CFG;
  5897. if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
  5898. return array();
  5899. }
  5900. if ($sitebytes == 0) {
  5901. // Will get the minimum of upload_max_filesize or post_max_size.
  5902. $sitebytes = get_max_upload_file_size();
  5903. }
  5904. $filesize = array();
  5905. $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
  5906. 5242880, 10485760, 20971520, 52428800, 104857600,
  5907. 262144000, 524288000, 786432000, 1073741824,
  5908. 2147483648, 4294967296, 8589934592);
  5909. // If custombytes is given and is valid then add it to the list.
  5910. if (is_number($custombytes) and $custombytes > 0) {
  5911. $custombytes = (int)$custombytes;
  5912. if (!in_array($custombytes, $sizelist)) {
  5913. $sizelist[] = $custombytes;
  5914. }
  5915. } else if (is_array($custombytes)) {
  5916. $sizelist = array_unique(array_merge($sizelist, $custombytes));
  5917. }
  5918. // Allow maxbytes to be selected if it falls outside the above boundaries.
  5919. if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
  5920. // Note: get_real_size() is used in order to prevent problems with invalid values.
  5921. $sizelist[] = get_real_size($CFG->maxbytes);
  5922. }
  5923. foreach ($sizelist as $sizebytes) {
  5924. if ($sizebytes < $maxsize && $sizebytes > 0) {
  5925. $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
  5926. }
  5927. }
  5928. $limitlevel = '';
  5929. $displaysize = '';
  5930. if ($modulebytes &&
  5931. (($modulebytes < $coursebytes || $coursebytes == 0) &&
  5932. ($modulebytes < $sitebytes || $sitebytes == 0))) {
  5933. $limitlevel = get_string('activity', 'core');
  5934. $displaysize = display_size($modulebytes, 0);
  5935. $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
  5936. } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
  5937. $limitlevel = get_string('course', 'core');
  5938. $displaysize = display_size($coursebytes, 0);
  5939. $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
  5940. } else if ($sitebytes) {
  5941. $limitlevel = get_string('site', 'core');
  5942. $displaysize = display_size($sitebytes, 0);
  5943. $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
  5944. }
  5945. krsort($filesize, SORT_NUMERIC);
  5946. if ($limitlevel) {
  5947. $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
  5948. $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
  5949. }
  5950. return $filesize;
  5951. }
  5952. /**
  5953. * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
  5954. *
  5955. * If excludefiles is defined, then that file/directory is ignored
  5956. * If getdirs is true, then (sub)directories are included in the output
  5957. * If getfiles is true, then files are included in the output
  5958. * (at least one of these must be true!)
  5959. *
  5960. * @todo Finish documenting this function. Add examples of $excludefile usage.
  5961. *
  5962. * @param string $rootdir A given root directory to start from
  5963. * @param string|array $excludefiles If defined then the specified file/directory is ignored
  5964. * @param bool $descend If true then subdirectories are recursed as well
  5965. * @param bool $getdirs If true then (sub)directories are included in the output
  5966. * @param bool $getfiles If true then files are included in the output
  5967. * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
  5968. */
  5969. function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
  5970. $dirs = array();
  5971. if (!$getdirs and !$getfiles) { // Nothing to show.
  5972. return $dirs;
  5973. }
  5974. if (!is_dir($rootdir)) { // Must be a directory.
  5975. return $dirs;
  5976. }
  5977. if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
  5978. return $dirs;
  5979. }
  5980. if (!is_array($excludefiles)) {
  5981. $excludefiles = array($excludefiles);
  5982. }
  5983. while (false !== ($file = readdir($dir))) {
  5984. $firstchar = substr($file, 0, 1);
  5985. if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
  5986. continue;
  5987. }
  5988. $fullfile = $rootdir .'/'. $file;
  5989. if (filetype($fullfile) == 'dir') {
  5990. if ($getdirs) {
  5991. $dirs[] = $file;
  5992. }
  5993. if ($descend) {
  5994. $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
  5995. foreach ($subdirs as $subdir) {
  5996. $dirs[] = $file .'/'. $subdir;
  5997. }
  5998. }
  5999. } else if ($getfiles) {
  6000. $dirs[] = $file;
  6001. }
  6002. }
  6003. closedir($dir);
  6004. asort($dirs);
  6005. return $dirs;
  6006. }
  6007. /**
  6008. * Adds up all the files in a directory and works out the size.
  6009. *
  6010. * @param string $rootdir The directory to start from
  6011. * @param string $excludefile A file to exclude when summing directory size
  6012. * @return int The summed size of all files and subfiles within the root directory
  6013. */
  6014. function get_directory_size($rootdir, $excludefile='') {
  6015. global $CFG;
  6016. // Do it this way if we can, it's much faster.
  6017. if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
  6018. $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
  6019. $output = null;
  6020. $return = null;
  6021. exec($command, $output, $return);
  6022. if (is_array($output)) {
  6023. // We told it to return k.
  6024. return get_real_size(intval($output[0]).'k');
  6025. }
  6026. }
  6027. if (!is_dir($rootdir)) {
  6028. // Must be a directory.
  6029. return 0;
  6030. }
  6031. if (!$dir = @opendir($rootdir)) {
  6032. // Can't open it for some reason.
  6033. return 0;
  6034. }
  6035. $size = 0;
  6036. while (false !== ($file = readdir($dir))) {
  6037. $firstchar = substr($file, 0, 1);
  6038. if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
  6039. continue;
  6040. }
  6041. $fullfile = $rootdir .'/'. $file;
  6042. if (filetype($fullfile) == 'dir') {
  6043. $size += get_directory_size($fullfile, $excludefile);
  6044. } else {
  6045. $size += filesize($fullfile);
  6046. }
  6047. }
  6048. closedir($dir);
  6049. return $size;
  6050. }
  6051. /**
  6052. * Converts bytes into display form
  6053. *
  6054. * @param int $size The size to convert to human readable form
  6055. * @param int $decimalplaces If specified, uses fixed number of decimal places
  6056. * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
  6057. * @return string Display version of size
  6058. */
  6059. function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
  6060. static $units;
  6061. if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
  6062. return get_string('unlimited');
  6063. }
  6064. if (empty($units)) {
  6065. $units[] = get_string('sizeb');
  6066. $units[] = get_string('sizekb');
  6067. $units[] = get_string('sizemb');
  6068. $units[] = get_string('sizegb');
  6069. $units[] = get_string('sizetb');
  6070. $units[] = get_string('sizepb');
  6071. }
  6072. switch ($fixedunits) {
  6073. case 'PB' :
  6074. $magnitude = 5;
  6075. break;
  6076. case 'TB' :
  6077. $magnitude = 4;
  6078. break;
  6079. case 'GB' :
  6080. $magnitude = 3;
  6081. break;
  6082. case 'MB' :
  6083. $magnitude = 2;
  6084. break;
  6085. case 'KB' :
  6086. $magnitude = 1;
  6087. break;
  6088. case 'B' :
  6089. $magnitude = 0;
  6090. break;
  6091. case '':
  6092. $magnitude = floor(log($size, 1024));
  6093. $magnitude = max(0, min(5, $magnitude));
  6094. break;
  6095. default:
  6096. throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
  6097. }
  6098. // Special case for magnitude 0 (bytes) - never use decimal places.
  6099. $nbsp = "\xc2\xa0";
  6100. if ($magnitude === 0) {
  6101. return round($size) . $nbsp . $units[$magnitude];
  6102. }
  6103. // Convert to specified units.
  6104. $sizeinunit = $size / 1024 ** $magnitude;
  6105. // Fixed decimal places.
  6106. return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
  6107. }
  6108. /**
  6109. * Cleans a given filename by removing suspicious or troublesome characters
  6110. *
  6111. * @see clean_param()
  6112. * @param string $string file name
  6113. * @return string cleaned file name
  6114. */
  6115. function clean_filename($string) {
  6116. return clean_param($string, PARAM_FILE);
  6117. }
  6118. // STRING TRANSLATION.
  6119. /**
  6120. * Returns the code for the current language
  6121. *
  6122. * @category string
  6123. * @return string
  6124. */
  6125. function current_language() {
  6126. global $CFG, $USER, $SESSION, $COURSE;
  6127. if (!empty($SESSION->forcelang)) {
  6128. // Allows overriding course-forced language (useful for admins to check
  6129. // issues in courses whose language they don't understand).
  6130. // Also used by some code to temporarily get language-related information in a
  6131. // specific language (see force_current_language()).
  6132. $return = $SESSION->forcelang;
  6133. } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
  6134. // Course language can override all other settings for this page.
  6135. $return = $COURSE->lang;
  6136. } else if (!empty($SESSION->lang)) {
  6137. // Session language can override other settings.
  6138. $return = $SESSION->lang;
  6139. } else if (!empty($USER->lang)) {
  6140. $return = $USER->lang;
  6141. } else if (isset($CFG->lang)) {
  6142. $return = $CFG->lang;
  6143. } else {
  6144. $return = 'en';
  6145. }
  6146. // Just in case this slipped in from somewhere by accident.
  6147. $return = str_replace('_utf8', '', $return);
  6148. return $return;
  6149. }
  6150. /**
  6151. * Returns parent language of current active language if defined
  6152. *
  6153. * @category string
  6154. * @param string $lang null means current language
  6155. * @return string
  6156. */
  6157. function get_parent_language($lang=null) {
  6158. $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
  6159. if ($parentlang === 'en') {
  6160. $parentlang = '';
  6161. }
  6162. return $parentlang;
  6163. }
  6164. /**
  6165. * Force the current language to get strings and dates localised in the given language.
  6166. *
  6167. * After calling this function, all strings will be provided in the given language
  6168. * until this function is called again, or equivalent code is run.
  6169. *
  6170. * @param string $language
  6171. * @return string previous $SESSION->forcelang value
  6172. */
  6173. function force_current_language($language) {
  6174. global $SESSION;
  6175. $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
  6176. if ($language !== $sessionforcelang) {
  6177. // Seting forcelang to null or an empty string disables it's effect.
  6178. if (empty($language) || get_string_manager()->translation_exists($language, false)) {
  6179. $SESSION->forcelang = $language;
  6180. moodle_setlocale();
  6181. }
  6182. }
  6183. return $sessionforcelang;
  6184. }
  6185. /**
  6186. * Returns current string_manager instance.
  6187. *
  6188. * The param $forcereload is needed for CLI installer only where the string_manager instance
  6189. * must be replaced during the install.php script life time.
  6190. *
  6191. * @category string
  6192. * @param bool $forcereload shall the singleton be released and new instance created instead?
  6193. * @return core_string_manager
  6194. */
  6195. function get_string_manager($forcereload=false) {
  6196. global $CFG;
  6197. static $singleton = null;
  6198. if ($forcereload) {
  6199. $singleton = null;
  6200. }
  6201. if ($singleton === null) {
  6202. if (empty($CFG->early_install_lang)) {
  6203. $transaliases = array();
  6204. if (empty($CFG->langlist)) {
  6205. $translist = array();
  6206. } else {
  6207. $translist = explode(',', $CFG->langlist);
  6208. $translist = array_map('trim', $translist);
  6209. // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
  6210. foreach ($translist as $i => $value) {
  6211. $parts = preg_split('/\s*\|\s*/', $value, 2);
  6212. if (count($parts) == 2) {
  6213. $transaliases[$parts[0]] = $parts[1];
  6214. $translist[$i] = $parts[0];
  6215. }
  6216. }
  6217. }
  6218. if (!empty($CFG->config_php_settings['customstringmanager'])) {
  6219. $classname = $CFG->config_php_settings['customstringmanager'];
  6220. if (class_exists($classname)) {
  6221. $implements = class_implements($classname);
  6222. if (isset($implements['core_string_manager'])) {
  6223. $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
  6224. return $singleton;
  6225. } else {
  6226. debugging('Unable to instantiate custom string manager: class '.$classname.
  6227. ' does not implement the core_string_manager interface.');
  6228. }
  6229. } else {
  6230. debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
  6231. }
  6232. }
  6233. $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
  6234. } else {
  6235. $singleton = new core_string_manager_install();
  6236. }
  6237. }
  6238. return $singleton;
  6239. }
  6240. /**
  6241. * Returns a localized string.
  6242. *
  6243. * Returns the translated string specified by $identifier as
  6244. * for $module. Uses the same format files as STphp.
  6245. * $a is an object, string or number that can be used
  6246. * within translation strings
  6247. *
  6248. * eg 'hello {$a->firstname} {$a->lastname}'
  6249. * or 'hello {$a}'
  6250. *
  6251. * If you would like to directly echo the localized string use
  6252. * the function {@link print_string()}
  6253. *
  6254. * Example usage of this function involves finding the string you would
  6255. * like a local equivalent of and using its identifier and module information
  6256. * to retrieve it.<br/>
  6257. * If you open moodle/lang/en/moodle.php and look near line 278
  6258. * you will find a string to prompt a user for their word for 'course'
  6259. * <code>
  6260. * $string['course'] = 'Course';
  6261. * </code>
  6262. * So if you want to display the string 'Course'
  6263. * in any language that supports it on your site
  6264. * you just need to use the identifier 'course'
  6265. * <code>
  6266. * $mystring = '<strong>'. get_string('course') .'</strong>';
  6267. * or
  6268. * </code>
  6269. * If the string you want is in another file you'd take a slightly
  6270. * different approach. Looking in moodle/lang/en/calendar.php you find
  6271. * around line 75:
  6272. * <code>
  6273. * $string['typecourse'] = 'Course event';
  6274. * </code>
  6275. * If you want to display the string "Course event" in any language
  6276. * supported you would use the identifier 'typecourse' and the module 'calendar'
  6277. * (because it is in the file calendar.php):
  6278. * <code>
  6279. * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
  6280. * </code>
  6281. *
  6282. * As a last resort, should the identifier fail to map to a string
  6283. * the returned string will be [[ $identifier ]]
  6284. *
  6285. * In Moodle 2.3 there is a new argument to this function $lazyload.
  6286. * Setting $lazyload to true causes get_string to return a lang_string object
  6287. * rather than the string itself. The fetching of the string is then put off until
  6288. * the string object is first used. The object can be used by calling it's out
  6289. * method or by casting the object to a string, either directly e.g.
  6290. * (string)$stringobject
  6291. * or indirectly by using the string within another string or echoing it out e.g.
  6292. * echo $stringobject
  6293. * return "<p>{$stringobject}</p>";
  6294. * It is worth noting that using $lazyload and attempting to use the string as an
  6295. * array key will cause a fatal error as objects cannot be used as array keys.
  6296. * But you should never do that anyway!
  6297. * For more information {@link lang_string}
  6298. *
  6299. * @category string
  6300. * @param string $identifier The key identifier for the localized string
  6301. * @param string $component The module where the key identifier is stored,
  6302. * usually expressed as the filename in the language pack without the
  6303. * .php on the end but can also be written as mod/forum or grade/export/xls.
  6304. * If none is specified then moodle.php is used.
  6305. * @param string|object|array $a An object, string or number that can be used
  6306. * within translation strings
  6307. * @param bool $lazyload If set to true a string object is returned instead of
  6308. * the string itself. The string then isn't calculated until it is first used.
  6309. * @return string The localized string.
  6310. * @throws coding_exception
  6311. */
  6312. function get_string($identifier, $component = '', $a = null, $lazyload = false) {
  6313. global $CFG;
  6314. // If the lazy load argument has been supplied return a lang_string object
  6315. // instead.
  6316. // We need to make sure it is true (and a bool) as you will see below there
  6317. // used to be a forth argument at one point.
  6318. if ($lazyload === true) {
  6319. return new lang_string($identifier, $component, $a);
  6320. }
  6321. if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
  6322. throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
  6323. }
  6324. // There is now a forth argument again, this time it is a boolean however so
  6325. // we can still check for the old extralocations parameter.
  6326. if (!is_bool($lazyload) && !empty($lazyload)) {
  6327. debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
  6328. }
  6329. if (strpos($component, '/') !== false) {
  6330. debugging('The module name you passed to get_string is the deprecated format ' .
  6331. 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
  6332. $componentpath = explode('/', $component);
  6333. switch ($componentpath[0]) {
  6334. case 'mod':
  6335. $component = $componentpath[1];
  6336. break;
  6337. case 'blocks':
  6338. case 'block':
  6339. $component = 'block_'.$componentpath[1];
  6340. break;
  6341. case 'enrol':
  6342. $component = 'enrol_'.$componentpath[1];
  6343. break;
  6344. case 'format':
  6345. $component = 'format_'.$componentpath[1];
  6346. break;
  6347. case 'grade':
  6348. $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
  6349. break;
  6350. }
  6351. }
  6352. $result = get_string_manager()->get_string($identifier, $component, $a);
  6353. // Debugging feature lets you display string identifier and component.
  6354. if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
  6355. $result .= ' {' . $identifier . '/' . $component . '}';
  6356. }
  6357. return $result;
  6358. }
  6359. /**
  6360. * Converts an array of strings to their localized value.
  6361. *
  6362. * @param array $array An array of strings
  6363. * @param string $component The language module that these strings can be found in.
  6364. * @return stdClass translated strings.
  6365. */
  6366. function get_strings($array, $component = '') {
  6367. $string = new stdClass;
  6368. foreach ($array as $item) {
  6369. $string->$item = get_string($item, $component);
  6370. }
  6371. return $string;
  6372. }
  6373. /**
  6374. * Prints out a translated string.
  6375. *
  6376. * Prints out a translated string using the return value from the {@link get_string()} function.
  6377. *
  6378. * Example usage of this function when the string is in the moodle.php file:<br/>
  6379. * <code>
  6380. * echo '<strong>';
  6381. * print_string('course');
  6382. * echo '</strong>';
  6383. * </code>
  6384. *
  6385. * Example usage of this function when the string is not in the moodle.php file:<br/>
  6386. * <code>
  6387. * echo '<h1>';
  6388. * print_string('typecourse', 'calendar');
  6389. * echo '</h1>';
  6390. * </code>
  6391. *
  6392. * @category string
  6393. * @param string $identifier The key identifier for the localized string
  6394. * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
  6395. * @param string|object|array $a An object, string or number that can be used within translation strings
  6396. */
  6397. function print_string($identifier, $component = '', $a = null) {
  6398. echo get_string($identifier, $component, $a);
  6399. }
  6400. /**
  6401. * Returns a list of charset codes
  6402. *
  6403. * Returns a list of charset codes. It's hardcoded, so they should be added manually
  6404. * (checking that such charset is supported by the texlib library!)
  6405. *
  6406. * @return array And associative array with contents in the form of charset => charset
  6407. */
  6408. function get_list_of_charsets() {
  6409. $charsets = array(
  6410. 'EUC-JP' => 'EUC-JP',
  6411. 'ISO-2022-JP'=> 'ISO-2022-JP',
  6412. 'ISO-8859-1' => 'ISO-8859-1',
  6413. 'SHIFT-JIS' => 'SHIFT-JIS',
  6414. 'GB2312' => 'GB2312',
  6415. 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
  6416. 'UTF-8' => 'UTF-8');
  6417. asort($charsets);
  6418. return $charsets;
  6419. }
  6420. /**
  6421. * Returns a list of valid and compatible themes
  6422. *
  6423. * @return array
  6424. */
  6425. function get_list_of_themes() {
  6426. global $CFG;
  6427. $themes = array();
  6428. if (!empty($CFG->themelist)) { // Use admin's list of themes.
  6429. $themelist = explode(',', $CFG->themelist);
  6430. } else {
  6431. $themelist = array_keys(core_component::get_plugin_list("theme"));
  6432. }
  6433. foreach ($themelist as $key => $themename) {
  6434. $theme = theme_config::load($themename);
  6435. $themes[$themename] = $theme;
  6436. }
  6437. core_collator::asort_objects_by_method($themes, 'get_theme_name');
  6438. return $themes;
  6439. }
  6440. /**
  6441. * Factory function for emoticon_manager
  6442. *
  6443. * @return emoticon_manager singleton
  6444. */
  6445. function get_emoticon_manager() {
  6446. static $singleton = null;
  6447. if (is_null($singleton)) {
  6448. $singleton = new emoticon_manager();
  6449. }
  6450. return $singleton;
  6451. }
  6452. /**
  6453. * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
  6454. *
  6455. * Whenever this manager mentiones 'emoticon object', the following data
  6456. * structure is expected: stdClass with properties text, imagename, imagecomponent,
  6457. * altidentifier and altcomponent
  6458. *
  6459. * @see admin_setting_emoticons
  6460. *
  6461. * @copyright 2010 David Mudrak
  6462. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  6463. */
  6464. class emoticon_manager {
  6465. /**
  6466. * Returns the currently enabled emoticons
  6467. *
  6468. * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
  6469. * @return array of emoticon objects
  6470. */
  6471. public function get_emoticons($selectable = false) {
  6472. global $CFG;
  6473. $notselectable = ['martin', 'egg'];
  6474. if (empty($CFG->emoticons)) {
  6475. return array();
  6476. }
  6477. $emoticons = $this->decode_stored_config($CFG->emoticons);
  6478. if (!is_array($emoticons)) {
  6479. // Something is wrong with the format of stored setting.
  6480. debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
  6481. return array();
  6482. }
  6483. if ($selectable) {
  6484. foreach ($emoticons as $index => $emote) {
  6485. if (in_array($emote->altidentifier, $notselectable)) {
  6486. // Skip this one.
  6487. unset($emoticons[$index]);
  6488. }
  6489. }
  6490. }
  6491. return $emoticons;
  6492. }
  6493. /**
  6494. * Converts emoticon object into renderable pix_emoticon object
  6495. *
  6496. * @param stdClass $emoticon emoticon object
  6497. * @param array $attributes explicit HTML attributes to set
  6498. * @return pix_emoticon
  6499. */
  6500. public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
  6501. $stringmanager = get_string_manager();
  6502. if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
  6503. $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
  6504. } else {
  6505. $alt = s($emoticon->text);
  6506. }
  6507. return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
  6508. }
  6509. /**
  6510. * Encodes the array of emoticon objects into a string storable in config table
  6511. *
  6512. * @see self::decode_stored_config()
  6513. * @param array $emoticons array of emtocion objects
  6514. * @return string
  6515. */
  6516. public function encode_stored_config(array $emoticons) {
  6517. return json_encode($emoticons);
  6518. }
  6519. /**
  6520. * Decodes the string into an array of emoticon objects
  6521. *
  6522. * @see self::encode_stored_config()
  6523. * @param string $encoded
  6524. * @return string|null
  6525. */
  6526. public function decode_stored_config($encoded) {
  6527. $decoded = json_decode($encoded);
  6528. if (!is_array($decoded)) {
  6529. return null;
  6530. }
  6531. return $decoded;
  6532. }
  6533. /**
  6534. * Returns default set of emoticons supported by Moodle
  6535. *
  6536. * @return array of sdtClasses
  6537. */
  6538. public function default_emoticons() {
  6539. return array(
  6540. $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
  6541. $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
  6542. $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
  6543. $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
  6544. $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
  6545. $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
  6546. $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
  6547. $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
  6548. $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
  6549. $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
  6550. $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
  6551. $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
  6552. $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
  6553. $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
  6554. $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
  6555. $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
  6556. $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
  6557. $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
  6558. $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
  6559. $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
  6560. $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
  6561. $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
  6562. $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
  6563. $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
  6564. $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
  6565. $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
  6566. $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
  6567. $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
  6568. $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
  6569. $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
  6570. );
  6571. }
  6572. /**
  6573. * Helper method preparing the stdClass with the emoticon properties
  6574. *
  6575. * @param string|array $text or array of strings
  6576. * @param string $imagename to be used by {@link pix_emoticon}
  6577. * @param string $altidentifier alternative string identifier, null for no alt
  6578. * @param string $altcomponent where the alternative string is defined
  6579. * @param string $imagecomponent to be used by {@link pix_emoticon}
  6580. * @return stdClass
  6581. */
  6582. protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
  6583. $altcomponent = 'core_pix', $imagecomponent = 'core') {
  6584. return (object)array(
  6585. 'text' => $text,
  6586. 'imagename' => $imagename,
  6587. 'imagecomponent' => $imagecomponent,
  6588. 'altidentifier' => $altidentifier,
  6589. 'altcomponent' => $altcomponent,
  6590. );
  6591. }
  6592. }
  6593. // ENCRYPTION.
  6594. /**
  6595. * rc4encrypt
  6596. *
  6597. * @param string $data Data to encrypt.
  6598. * @return string The now encrypted data.
  6599. */
  6600. function rc4encrypt($data) {
  6601. return endecrypt(get_site_identifier(), $data, '');
  6602. }
  6603. /**
  6604. * rc4decrypt
  6605. *
  6606. * @param string $data Data to decrypt.
  6607. * @return string The now decrypted data.
  6608. */
  6609. function rc4decrypt($data) {
  6610. return endecrypt(get_site_identifier(), $data, 'de');
  6611. }
  6612. /**
  6613. * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
  6614. *
  6615. * @todo Finish documenting this function
  6616. *
  6617. * @param string $pwd The password to use when encrypting or decrypting
  6618. * @param string $data The data to be decrypted/encrypted
  6619. * @param string $case Either 'de' for decrypt or '' for encrypt
  6620. * @return string
  6621. */
  6622. function endecrypt ($pwd, $data, $case) {
  6623. if ($case == 'de') {
  6624. $data = urldecode($data);
  6625. }
  6626. $key[] = '';
  6627. $box[] = '';
  6628. $pwdlength = strlen($pwd);
  6629. for ($i = 0; $i <= 255; $i++) {
  6630. $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
  6631. $box[$i] = $i;
  6632. }
  6633. $x = 0;
  6634. for ($i = 0; $i <= 255; $i++) {
  6635. $x = ($x + $box[$i] + $key[$i]) % 256;
  6636. $tempswap = $box[$i];
  6637. $box[$i] = $box[$x];
  6638. $box[$x] = $tempswap;
  6639. }
  6640. $cipher = '';
  6641. $a = 0;
  6642. $j = 0;
  6643. for ($i = 0; $i < strlen($data); $i++) {
  6644. $a = ($a + 1) % 256;
  6645. $j = ($j + $box[$a]) % 256;
  6646. $temp = $box[$a];
  6647. $box[$a] = $box[$j];
  6648. $box[$j] = $temp;
  6649. $k = $box[(($box[$a] + $box[$j]) % 256)];
  6650. $cipherby = ord(substr($data, $i, 1)) ^ $k;
  6651. $cipher .= chr($cipherby);
  6652. }
  6653. if ($case == 'de') {
  6654. $cipher = urldecode(urlencode($cipher));
  6655. } else {
  6656. $cipher = urlencode($cipher);
  6657. }
  6658. return $cipher;
  6659. }
  6660. // ENVIRONMENT CHECKING.
  6661. /**
  6662. * This method validates a plug name. It is much faster than calling clean_param.
  6663. *
  6664. * @param string $name a string that might be a plugin name.
  6665. * @return bool if this string is a valid plugin name.
  6666. */
  6667. function is_valid_plugin_name($name) {
  6668. // This does not work for 'mod', bad luck, use any other type.
  6669. return core_component::is_valid_plugin_name('tool', $name);
  6670. }
  6671. /**
  6672. * Get a list of all the plugins of a given type that define a certain API function
  6673. * in a certain file. The plugin component names and function names are returned.
  6674. *
  6675. * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
  6676. * @param string $function the part of the name of the function after the
  6677. * frankenstyle prefix. e.g 'hook' if you are looking for functions with
  6678. * names like report_courselist_hook.
  6679. * @param string $file the name of file within the plugin that defines the
  6680. * function. Defaults to lib.php.
  6681. * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
  6682. * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
  6683. */
  6684. function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
  6685. global $CFG;
  6686. // We don't include here as all plugin types files would be included.
  6687. $plugins = get_plugins_with_function($function, $file, false);
  6688. if (empty($plugins[$plugintype])) {
  6689. return array();
  6690. }
  6691. $allplugins = core_component::get_plugin_list($plugintype);
  6692. // Reformat the array and include the files.
  6693. $pluginfunctions = array();
  6694. foreach ($plugins[$plugintype] as $pluginname => $functionname) {
  6695. // Check that it has not been removed and the file is still available.
  6696. if (!empty($allplugins[$pluginname])) {
  6697. $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
  6698. if (file_exists($filepath)) {
  6699. include_once($filepath);
  6700. // Now that the file is loaded, we must verify the function still exists.
  6701. if (function_exists($functionname)) {
  6702. $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
  6703. } else {
  6704. // Invalidate the cache for next run.
  6705. \cache_helper::invalidate_by_definition('core', 'plugin_functions');
  6706. }
  6707. }
  6708. }
  6709. }
  6710. return $pluginfunctions;
  6711. }
  6712. /**
  6713. * Get a list of all the plugins that define a certain API function in a certain file.
  6714. *
  6715. * @param string $function the part of the name of the function after the
  6716. * frankenstyle prefix. e.g 'hook' if you are looking for functions with
  6717. * names like report_courselist_hook.
  6718. * @param string $file the name of file within the plugin that defines the
  6719. * function. Defaults to lib.php.
  6720. * @param bool $include Whether to include the files that contain the functions or not.
  6721. * @return array with [plugintype][plugin] = functionname
  6722. */
  6723. function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
  6724. global $CFG;
  6725. if (during_initial_install() || isset($CFG->upgraderunning)) {
  6726. // API functions _must not_ be called during an installation or upgrade.
  6727. return [];
  6728. }
  6729. $cache = \cache::make('core', 'plugin_functions');
  6730. // Including both although I doubt that we will find two functions definitions with the same name.
  6731. // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
  6732. $key = $function . '_' . clean_param($file, PARAM_ALPHA);
  6733. $pluginfunctions = $cache->get($key);
  6734. $dirty = false;
  6735. // Use the plugin manager to check that plugins are currently installed.
  6736. $pluginmanager = \core_plugin_manager::instance();
  6737. if ($pluginfunctions !== false) {
  6738. // Checking that the files are still available.
  6739. foreach ($pluginfunctions as $plugintype => $plugins) {
  6740. $allplugins = \core_component::get_plugin_list($plugintype);
  6741. $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
  6742. foreach ($plugins as $plugin => $function) {
  6743. if (!isset($installedplugins[$plugin])) {
  6744. // Plugin code is still present on disk but it is not installed.
  6745. $dirty = true;
  6746. break 2;
  6747. }
  6748. // Cache might be out of sync with the codebase, skip the plugin if it is not available.
  6749. if (empty($allplugins[$plugin])) {
  6750. $dirty = true;
  6751. break 2;
  6752. }
  6753. $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
  6754. if ($include && $fileexists) {
  6755. // Include the files if it was requested.
  6756. include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
  6757. } else if (!$fileexists) {
  6758. // If the file is not available any more it should not be returned.
  6759. $dirty = true;
  6760. break 2;
  6761. }
  6762. // Check if the function still exists in the file.
  6763. if ($include && !function_exists($function)) {
  6764. $dirty = true;
  6765. break 2;
  6766. }
  6767. }
  6768. }
  6769. // If the cache is dirty, we should fall through and let it rebuild.
  6770. if (!$dirty) {
  6771. return $pluginfunctions;
  6772. }
  6773. }
  6774. $pluginfunctions = array();
  6775. // To fill the cached. Also, everything should continue working with cache disabled.
  6776. $plugintypes = \core_component::get_plugin_types();
  6777. foreach ($plugintypes as $plugintype => $unused) {
  6778. // We need to include files here.
  6779. $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
  6780. $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
  6781. foreach ($pluginswithfile as $plugin => $notused) {
  6782. if (!isset($installedplugins[$plugin])) {
  6783. continue;
  6784. }
  6785. $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
  6786. $pluginfunction = false;
  6787. if (function_exists($fullfunction)) {
  6788. // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
  6789. $pluginfunction = $fullfunction;
  6790. } else if ($plugintype === 'mod') {
  6791. // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
  6792. $shortfunction = $plugin . '_' . $function;
  6793. if (function_exists($shortfunction)) {
  6794. $pluginfunction = $shortfunction;
  6795. }
  6796. }
  6797. if ($pluginfunction) {
  6798. if (empty($pluginfunctions[$plugintype])) {
  6799. $pluginfunctions[$plugintype] = array();
  6800. }
  6801. $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
  6802. }
  6803. }
  6804. }
  6805. $cache->set($key, $pluginfunctions);
  6806. return $pluginfunctions;
  6807. }
  6808. /**
  6809. * Lists plugin-like directories within specified directory
  6810. *
  6811. * This function was originally used for standard Moodle plugins, please use
  6812. * new core_component::get_plugin_list() now.
  6813. *
  6814. * This function is used for general directory listing and backwards compatility.
  6815. *
  6816. * @param string $directory relative directory from root
  6817. * @param string $exclude dir name to exclude from the list (defaults to none)
  6818. * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
  6819. * @return array Sorted array of directory names found under the requested parameters
  6820. */
  6821. function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
  6822. global $CFG;
  6823. $plugins = array();
  6824. if (empty($basedir)) {
  6825. $basedir = $CFG->dirroot .'/'. $directory;
  6826. } else {
  6827. $basedir = $basedir .'/'. $directory;
  6828. }
  6829. if ($CFG->debugdeveloper and empty($exclude)) {
  6830. // Make sure devs do not use this to list normal plugins,
  6831. // this is intended for general directories that are not plugins!
  6832. $subtypes = core_component::get_plugin_types();
  6833. if (in_array($basedir, $subtypes)) {
  6834. debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
  6835. }
  6836. unset($subtypes);
  6837. }
  6838. $ignorelist = array_flip(array_filter([
  6839. 'CVS',
  6840. '_vti_cnf',
  6841. 'amd',
  6842. 'classes',
  6843. 'simpletest',
  6844. 'tests',
  6845. 'templates',
  6846. 'yui',
  6847. $exclude,
  6848. ]));
  6849. if (file_exists($basedir) && filetype($basedir) == 'dir') {
  6850. if (!$dirhandle = opendir($basedir)) {
  6851. debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
  6852. return array();
  6853. }
  6854. while (false !== ($dir = readdir($dirhandle))) {
  6855. if (strpos($dir, '.') === 0) {
  6856. // Ignore directories starting with .
  6857. // These are treated as hidden directories.
  6858. continue;
  6859. }
  6860. if (array_key_exists($dir, $ignorelist)) {
  6861. // This directory features on the ignore list.
  6862. continue;
  6863. }
  6864. if (filetype($basedir .'/'. $dir) != 'dir') {
  6865. continue;
  6866. }
  6867. $plugins[] = $dir;
  6868. }
  6869. closedir($dirhandle);
  6870. }
  6871. if ($plugins) {
  6872. asort($plugins);
  6873. }
  6874. return $plugins;
  6875. }
  6876. /**
  6877. * Invoke plugin's callback functions
  6878. *
  6879. * @param string $type plugin type e.g. 'mod'
  6880. * @param string $name plugin name
  6881. * @param string $feature feature name
  6882. * @param string $action feature's action
  6883. * @param array $params parameters of callback function, should be an array
  6884. * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
  6885. * @return mixed
  6886. *
  6887. * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
  6888. */
  6889. function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
  6890. return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
  6891. }
  6892. /**
  6893. * Invoke component's callback functions
  6894. *
  6895. * @param string $component frankenstyle component name, e.g. 'mod_quiz'
  6896. * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
  6897. * @param array $params parameters of callback function
  6898. * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
  6899. * @return mixed
  6900. */
  6901. function component_callback($component, $function, array $params = array(), $default = null) {
  6902. $functionname = component_callback_exists($component, $function);
  6903. if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
  6904. // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
  6905. // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
  6906. // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
  6907. // This check can be removed when minimum PHP version for Moodle is raised to 8.
  6908. debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
  6909. DEBUG_DEVELOPER);
  6910. $params = array_values($params);
  6911. }
  6912. if ($functionname) {
  6913. // Function exists, so just return function result.
  6914. $ret = call_user_func_array($functionname, $params);
  6915. if (is_null($ret)) {
  6916. return $default;
  6917. } else {
  6918. return $ret;
  6919. }
  6920. }
  6921. return $default;
  6922. }
  6923. /**
  6924. * Determine if a component callback exists and return the function name to call. Note that this
  6925. * function will include the required library files so that the functioname returned can be
  6926. * called directly.
  6927. *
  6928. * @param string $component frankenstyle component name, e.g. 'mod_quiz'
  6929. * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
  6930. * @return mixed Complete function name to call if the callback exists or false if it doesn't.
  6931. * @throws coding_exception if invalid component specfied
  6932. */
  6933. function component_callback_exists($component, $function) {
  6934. global $CFG; // This is needed for the inclusions.
  6935. $cleancomponent = clean_param($component, PARAM_COMPONENT);
  6936. if (empty($cleancomponent)) {
  6937. throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
  6938. }
  6939. $component = $cleancomponent;
  6940. list($type, $name) = core_component::normalize_component($component);
  6941. $component = $type . '_' . $name;
  6942. $oldfunction = $name.'_'.$function;
  6943. $function = $component.'_'.$function;
  6944. $dir = core_component::get_component_directory($component);
  6945. if (empty($dir)) {
  6946. throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
  6947. }
  6948. // Load library and look for function.
  6949. if (file_exists($dir.'/lib.php')) {
  6950. require_once($dir.'/lib.php');
  6951. }
  6952. if (!function_exists($function) and function_exists($oldfunction)) {
  6953. if ($type !== 'mod' and $type !== 'core') {
  6954. debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
  6955. }
  6956. $function = $oldfunction;
  6957. }
  6958. if (function_exists($function)) {
  6959. return $function;
  6960. }
  6961. return false;
  6962. }
  6963. /**
  6964. * Call the specified callback method on the provided class.
  6965. *
  6966. * If the callback returns null, then the default value is returned instead.
  6967. * If the class does not exist, then the default value is returned.
  6968. *
  6969. * @param string $classname The name of the class to call upon.
  6970. * @param string $methodname The name of the staticically defined method on the class.
  6971. * @param array $params The arguments to pass into the method.
  6972. * @param mixed $default The default value.
  6973. * @return mixed The return value.
  6974. */
  6975. function component_class_callback($classname, $methodname, array $params, $default = null) {
  6976. if (!class_exists($classname)) {
  6977. return $default;
  6978. }
  6979. if (!method_exists($classname, $methodname)) {
  6980. return $default;
  6981. }
  6982. $fullfunction = $classname . '::' . $methodname;
  6983. $result = call_user_func_array($fullfunction, $params);
  6984. if (null === $result) {
  6985. return $default;
  6986. } else {
  6987. return $result;
  6988. }
  6989. }
  6990. /**
  6991. * Checks whether a plugin supports a specified feature.
  6992. *
  6993. * @param string $type Plugin type e.g. 'mod'
  6994. * @param string $name Plugin name e.g. 'forum'
  6995. * @param string $feature Feature code (FEATURE_xx constant)
  6996. * @param mixed $default default value if feature support unknown
  6997. * @return mixed Feature result (false if not supported, null if feature is unknown,
  6998. * otherwise usually true but may have other feature-specific value such as array)
  6999. * @throws coding_exception
  7000. */
  7001. function plugin_supports($type, $name, $feature, $default = null) {
  7002. global $CFG;
  7003. if ($type === 'mod' and $name === 'NEWMODULE') {
  7004. // Somebody forgot to rename the module template.
  7005. return false;
  7006. }
  7007. $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
  7008. if (empty($component)) {
  7009. throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
  7010. }
  7011. $function = null;
  7012. if ($type === 'mod') {
  7013. // We need this special case because we support subplugins in modules,
  7014. // otherwise it would end up in infinite loop.
  7015. if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
  7016. include_once("$CFG->dirroot/mod/$name/lib.php");
  7017. $function = $component.'_supports';
  7018. if (!function_exists($function)) {
  7019. // Legacy non-frankenstyle function name.
  7020. $function = $name.'_supports';
  7021. }
  7022. }
  7023. } else {
  7024. if (!$path = core_component::get_plugin_directory($type, $name)) {
  7025. // Non existent plugin type.
  7026. return false;
  7027. }
  7028. if (file_exists("$path/lib.php")) {
  7029. include_once("$path/lib.php");
  7030. $function = $component.'_supports';
  7031. }
  7032. }
  7033. if ($function and function_exists($function)) {
  7034. $supports = $function($feature);
  7035. if (is_null($supports)) {
  7036. // Plugin does not know - use default.
  7037. return $default;
  7038. } else {
  7039. return $supports;
  7040. }
  7041. }
  7042. // Plugin does not care, so use default.
  7043. return $default;
  7044. }
  7045. /**
  7046. * Returns true if the current version of PHP is greater that the specified one.
  7047. *
  7048. * @todo Check PHP version being required here is it too low?
  7049. *
  7050. * @param string $version The version of php being tested.
  7051. * @return bool
  7052. */
  7053. function check_php_version($version='5.2.4') {
  7054. return (version_compare(phpversion(), $version) >= 0);
  7055. }
  7056. /**
  7057. * Determine if moodle installation requires update.
  7058. *
  7059. * Checks version numbers of main code and all plugins to see
  7060. * if there are any mismatches.
  7061. *
  7062. * @return bool
  7063. */
  7064. function moodle_needs_upgrading() {
  7065. global $CFG;
  7066. if (empty($CFG->version)) {
  7067. return true;
  7068. }
  7069. // There is no need to purge plugininfo caches here because
  7070. // these caches are not used during upgrade and they are purged after
  7071. // every upgrade.
  7072. if (empty($CFG->allversionshash)) {
  7073. return true;
  7074. }
  7075. $hash = core_component::get_all_versions_hash();
  7076. return ($hash !== $CFG->allversionshash);
  7077. }
  7078. /**
  7079. * Returns the major version of this site
  7080. *
  7081. * Moodle version numbers consist of three numbers separated by a dot, for
  7082. * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
  7083. * called major version. This function extracts the major version from either
  7084. * $CFG->release (default) or eventually from the $release variable defined in
  7085. * the main version.php.
  7086. *
  7087. * @param bool $fromdisk should the version if source code files be used
  7088. * @return string|false the major version like '2.3', false if could not be determined
  7089. */
  7090. function moodle_major_version($fromdisk = false) {
  7091. global $CFG;
  7092. if ($fromdisk) {
  7093. $release = null;
  7094. require($CFG->dirroot.'/version.php');
  7095. if (empty($release)) {
  7096. return false;
  7097. }
  7098. } else {
  7099. if (empty($CFG->release)) {
  7100. return false;
  7101. }
  7102. $release = $CFG->release;
  7103. }
  7104. if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
  7105. return $matches[0];
  7106. } else {
  7107. return false;
  7108. }
  7109. }
  7110. // MISCELLANEOUS.
  7111. /**
  7112. * Gets the system locale
  7113. *
  7114. * @return string Retuns the current locale.
  7115. */
  7116. function moodle_getlocale() {
  7117. global $CFG;
  7118. // Fetch the correct locale based on ostype.
  7119. if ($CFG->ostype == 'WINDOWS') {
  7120. $stringtofetch = 'localewin';
  7121. } else {
  7122. $stringtofetch = 'locale';
  7123. }
  7124. if (!empty($CFG->locale)) { // Override locale for all language packs.
  7125. return $CFG->locale;
  7126. }
  7127. return get_string($stringtofetch, 'langconfig');
  7128. }
  7129. /**
  7130. * Sets the system locale
  7131. *
  7132. * @category string
  7133. * @param string $locale Can be used to force a locale
  7134. */
  7135. function moodle_setlocale($locale='') {
  7136. global $CFG;
  7137. static $currentlocale = ''; // Last locale caching.
  7138. $oldlocale = $currentlocale;
  7139. // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
  7140. if (!empty($locale)) {
  7141. $currentlocale = $locale;
  7142. } else {
  7143. $currentlocale = moodle_getlocale();
  7144. }
  7145. // Do nothing if locale already set up.
  7146. if ($oldlocale == $currentlocale) {
  7147. return;
  7148. }
  7149. // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
  7150. // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
  7151. // Some day, numeric, monetary and other categories should be set too, I think. :-/.
  7152. // Get current values.
  7153. $monetary= setlocale (LC_MONETARY, 0);
  7154. $numeric = setlocale (LC_NUMERIC, 0);
  7155. $ctype = setlocale (LC_CTYPE, 0);
  7156. if ($CFG->ostype != 'WINDOWS') {
  7157. $messages= setlocale (LC_MESSAGES, 0);
  7158. }
  7159. // Set locale to all.
  7160. $result = setlocale (LC_ALL, $currentlocale);
  7161. // If setting of locale fails try the other utf8 or utf-8 variant,
  7162. // some operating systems support both (Debian), others just one (OSX).
  7163. if ($result === false) {
  7164. if (stripos($currentlocale, '.UTF-8') !== false) {
  7165. $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
  7166. setlocale (LC_ALL, $newlocale);
  7167. } else if (stripos($currentlocale, '.UTF8') !== false) {
  7168. $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
  7169. setlocale (LC_ALL, $newlocale);
  7170. }
  7171. }
  7172. // Set old values.
  7173. setlocale (LC_MONETARY, $monetary);
  7174. setlocale (LC_NUMERIC, $numeric);
  7175. if ($CFG->ostype != 'WINDOWS') {
  7176. setlocale (LC_MESSAGES, $messages);
  7177. }
  7178. if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
  7179. // To workaround a well-known PHP problem with Turkish letter Ii.
  7180. setlocale (LC_CTYPE, $ctype);
  7181. }
  7182. }
  7183. /**
  7184. * Count words in a string.
  7185. *
  7186. * Words are defined as things between whitespace.
  7187. *
  7188. * @category string
  7189. * @param string $string The text to be searched for words. May be HTML.
  7190. * @return int The count of words in the specified string
  7191. */
  7192. function count_words($string) {
  7193. // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
  7194. // Also, br is a special case because it definitely delimits a word, but has no close tag.
  7195. $string = preg_replace('~
  7196. ( # Capture the tag we match.
  7197. </ # Start of close tag.
  7198. (?! # Do not match any of these specific close tag names.
  7199. a> | b> | del> | em> | i> |
  7200. ins> | s> | small> |
  7201. strong> | sub> | sup> | u>
  7202. )
  7203. \w+ # But, apart from those execptions, match any tag name.
  7204. > # End of close tag.
  7205. |
  7206. <br> | <br\s*/> # Special cases that are not close tags.
  7207. )
  7208. ~x', '$1 ', $string); // Add a space after the close tag.
  7209. // Now remove HTML tags.
  7210. $string = strip_tags($string);
  7211. // Decode HTML entities.
  7212. $string = html_entity_decode($string);
  7213. // Now, the word count is the number of blocks of characters separated
  7214. // by any sort of space. That seems to be the definition used by all other systems.
  7215. // To be precise about what is considered to separate words:
  7216. // * Anything that Unicode considers a 'Separator'
  7217. // * Anything that Unicode considers a 'Control character'
  7218. // * An em- or en- dash.
  7219. return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
  7220. }
  7221. /**
  7222. * Count letters in a string.
  7223. *
  7224. * Letters are defined as chars not in tags and different from whitespace.
  7225. *
  7226. * @category string
  7227. * @param string $string The text to be searched for letters. May be HTML.
  7228. * @return int The count of letters in the specified text.
  7229. */
  7230. function count_letters($string) {
  7231. $string = strip_tags($string); // Tags are out now.
  7232. $string = html_entity_decode($string);
  7233. $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
  7234. return core_text::strlen($string);
  7235. }
  7236. /**
  7237. * Generate and return a random string of the specified length.
  7238. *
  7239. * @param int $length The length of the string to be created.
  7240. * @return string
  7241. */
  7242. function random_string($length=15) {
  7243. $randombytes = random_bytes_emulate($length);
  7244. $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7245. $pool .= 'abcdefghijklmnopqrstuvwxyz';
  7246. $pool .= '0123456789';
  7247. $poollen = strlen($pool);
  7248. $string = '';
  7249. for ($i = 0; $i < $length; $i++) {
  7250. $rand = ord($randombytes[$i]);
  7251. $string .= substr($pool, ($rand%($poollen)), 1);
  7252. }
  7253. return $string;
  7254. }
  7255. /**
  7256. * Generate a complex random string (useful for md5 salts)
  7257. *
  7258. * This function is based on the above {@link random_string()} however it uses a
  7259. * larger pool of characters and generates a string between 24 and 32 characters
  7260. *
  7261. * @param int $length Optional if set generates a string to exactly this length
  7262. * @return string
  7263. */
  7264. function complex_random_string($length=null) {
  7265. $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  7266. $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
  7267. $poollen = strlen($pool);
  7268. if ($length===null) {
  7269. $length = floor(rand(24, 32));
  7270. }
  7271. $randombytes = random_bytes_emulate($length);
  7272. $string = '';
  7273. for ($i = 0; $i < $length; $i++) {
  7274. $rand = ord($randombytes[$i]);
  7275. $string .= $pool[($rand%$poollen)];
  7276. }
  7277. return $string;
  7278. }
  7279. /**
  7280. * Try to generates cryptographically secure pseudo-random bytes.
  7281. *
  7282. * Note this is achieved by fallbacking between:
  7283. * - PHP 7 random_bytes().
  7284. * - OpenSSL openssl_random_pseudo_bytes().
  7285. * - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
  7286. *
  7287. * @param int $length requested length in bytes
  7288. * @return string binary data
  7289. */
  7290. function random_bytes_emulate($length) {
  7291. global $CFG;
  7292. if ($length <= 0) {
  7293. debugging('Invalid random bytes length', DEBUG_DEVELOPER);
  7294. return '';
  7295. }
  7296. if (function_exists('random_bytes')) {
  7297. // Use PHP 7 goodness.
  7298. $hash = @random_bytes($length);
  7299. if ($hash !== false) {
  7300. return $hash;
  7301. }
  7302. }
  7303. if (function_exists('openssl_random_pseudo_bytes')) {
  7304. // If you have the openssl extension enabled.
  7305. $hash = openssl_random_pseudo_bytes($length);
  7306. if ($hash !== false) {
  7307. return $hash;
  7308. }
  7309. }
  7310. // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
  7311. $staticdata = serialize($CFG) . serialize($_SERVER);
  7312. $hash = '';
  7313. do {
  7314. $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
  7315. } while (strlen($hash) < $length);
  7316. return substr($hash, 0, $length);
  7317. }
  7318. /**
  7319. * Given some text (which may contain HTML) and an ideal length,
  7320. * this function truncates the text neatly on a word boundary if possible
  7321. *
  7322. * @category string
  7323. * @param string $text text to be shortened
  7324. * @param int $ideal ideal string length
  7325. * @param boolean $exact if false, $text will not be cut mid-word
  7326. * @param string $ending The string to append if the passed string is truncated
  7327. * @return string $truncate shortened string
  7328. */
  7329. function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
  7330. // If the plain text is shorter than the maximum length, return the whole text.
  7331. if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
  7332. return $text;
  7333. }
  7334. // Splits on HTML tags. Each open/close/empty tag will be the first thing
  7335. // and only tag in its 'line'.
  7336. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  7337. $totallength = core_text::strlen($ending);
  7338. $truncate = '';
  7339. // This array stores information about open and close tags and their position
  7340. // in the truncated string. Each item in the array is an object with fields
  7341. // ->open (true if open), ->tag (tag name in lower case), and ->pos
  7342. // (byte position in truncated text).
  7343. $tagdetails = array();
  7344. foreach ($lines as $linematchings) {
  7345. // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
  7346. if (!empty($linematchings[1])) {
  7347. // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
  7348. if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
  7349. if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
  7350. // Record closing tag.
  7351. $tagdetails[] = (object) array(
  7352. 'open' => false,
  7353. 'tag' => core_text::strtolower($tagmatchings[1]),
  7354. 'pos' => core_text::strlen($truncate),
  7355. );
  7356. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
  7357. // Record opening tag.
  7358. $tagdetails[] = (object) array(
  7359. 'open' => true,
  7360. 'tag' => core_text::strtolower($tagmatchings[1]),
  7361. 'pos' => core_text::strlen($truncate),
  7362. );
  7363. } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
  7364. $tagdetails[] = (object) array(
  7365. 'open' => true,
  7366. 'tag' => core_text::strtolower('if'),
  7367. 'pos' => core_text::strlen($truncate),
  7368. );
  7369. } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
  7370. $tagdetails[] = (object) array(
  7371. 'open' => false,
  7372. 'tag' => core_text::strtolower('if'),
  7373. 'pos' => core_text::strlen($truncate),
  7374. );
  7375. }
  7376. }
  7377. // Add html-tag to $truncate'd text.
  7378. $truncate .= $linematchings[1];
  7379. }
  7380. // Calculate the length of the plain text part of the line; handle entities as one character.
  7381. $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
  7382. if ($totallength + $contentlength > $ideal) {
  7383. // The number of characters which are left.
  7384. $left = $ideal - $totallength;
  7385. $entitieslength = 0;
  7386. // Search for html entities.
  7387. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $linematchings[2], $entities, PREG_OFFSET_CAPTURE)) {
  7388. // Calculate the real length of all entities in the legal range.
  7389. foreach ($entities[0] as $entity) {
  7390. if ($entity[1]+1-$entitieslength <= $left) {
  7391. $left--;
  7392. $entitieslength += core_text::strlen($entity[0]);
  7393. } else {
  7394. // No more characters left.
  7395. break;
  7396. }
  7397. }
  7398. }
  7399. $breakpos = $left + $entitieslength;
  7400. // If the words shouldn't be cut in the middle...
  7401. if (!$exact) {
  7402. // Search the last occurence of a space.
  7403. for (; $breakpos > 0; $breakpos--) {
  7404. if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
  7405. if ($char === '.' or $char === ' ') {
  7406. $breakpos += 1;
  7407. break;
  7408. } else if (strlen($char) > 2) {
  7409. // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
  7410. $breakpos += 1;
  7411. break;
  7412. }
  7413. }
  7414. }
  7415. }
  7416. if ($breakpos == 0) {
  7417. // This deals with the test_shorten_text_no_spaces case.
  7418. $breakpos = $left + $entitieslength;
  7419. } else if ($breakpos > $left + $entitieslength) {
  7420. // This deals with the previous for loop breaking on the first char.
  7421. $breakpos = $left + $entitieslength;
  7422. }
  7423. $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
  7424. // Maximum length is reached, so get off the loop.
  7425. break;
  7426. } else {
  7427. $truncate .= $linematchings[2];
  7428. $totallength += $contentlength;
  7429. }
  7430. // If the maximum length is reached, get off the loop.
  7431. if ($totallength >= $ideal) {
  7432. break;
  7433. }
  7434. }
  7435. // Add the defined ending to the text.
  7436. $truncate .= $ending;
  7437. // Now calculate the list of open html tags based on the truncate position.
  7438. $opentags = array();
  7439. foreach ($tagdetails as $taginfo) {
  7440. if ($taginfo->open) {
  7441. // Add tag to the beginning of $opentags list.
  7442. array_unshift($opentags, $taginfo->tag);
  7443. } else {
  7444. // Can have multiple exact same open tags, close the last one.
  7445. $pos = array_search($taginfo->tag, array_reverse($opentags, true));
  7446. if ($pos !== false) {
  7447. unset($opentags[$pos]);
  7448. }
  7449. }
  7450. }
  7451. // Close all unclosed html-tags.
  7452. foreach ($opentags as $tag) {
  7453. if ($tag === 'if') {
  7454. $truncate .= '<!--<![endif]-->';
  7455. } else {
  7456. $truncate .= '</' . $tag . '>';
  7457. }
  7458. }
  7459. return $truncate;
  7460. }
  7461. /**
  7462. * Shortens a given filename by removing characters positioned after the ideal string length.
  7463. * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
  7464. * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
  7465. *
  7466. * @param string $filename file name
  7467. * @param int $length ideal string length
  7468. * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
  7469. * @return string $shortened shortened file name
  7470. */
  7471. function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
  7472. $shortened = $filename;
  7473. // Extract a part of the filename if it's char size exceeds the ideal string length.
  7474. if (core_text::strlen($filename) > $length) {
  7475. // Exclude extension if present in filename.
  7476. $mimetypes = get_mimetypes_array();
  7477. $extension = pathinfo($filename, PATHINFO_EXTENSION);
  7478. if ($extension && !empty($mimetypes[$extension])) {
  7479. $basename = pathinfo($filename, PATHINFO_FILENAME);
  7480. $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
  7481. $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
  7482. $shortened .= '.' . $extension;
  7483. } else {
  7484. $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
  7485. $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
  7486. }
  7487. }
  7488. return $shortened;
  7489. }
  7490. /**
  7491. * Shortens a given array of filenames by removing characters positioned after the ideal string length.
  7492. *
  7493. * @param array $path The paths to reduce the length.
  7494. * @param int $length Ideal string length
  7495. * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
  7496. * @return array $result Shortened paths in array.
  7497. */
  7498. function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
  7499. $result = null;
  7500. $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
  7501. $carry[] = shorten_filename($singlepath, $length, $includehash);
  7502. return $carry;
  7503. }, []);
  7504. return $result;
  7505. }
  7506. /**
  7507. * Given dates in seconds, how many weeks is the date from startdate
  7508. * The first week is 1, the second 2 etc ...
  7509. *
  7510. * @param int $startdate Timestamp for the start date
  7511. * @param int $thedate Timestamp for the end date
  7512. * @return string
  7513. */
  7514. function getweek ($startdate, $thedate) {
  7515. if ($thedate < $startdate) {
  7516. return 0;
  7517. }
  7518. return floor(($thedate - $startdate) / WEEKSECS) + 1;
  7519. }
  7520. /**
  7521. * Returns a randomly generated password of length $maxlen. inspired by
  7522. *
  7523. * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
  7524. * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
  7525. *
  7526. * @param int $maxlen The maximum size of the password being generated.
  7527. * @return string
  7528. */
  7529. function generate_password($maxlen=10) {
  7530. global $CFG;
  7531. if (empty($CFG->passwordpolicy)) {
  7532. $fillers = PASSWORD_DIGITS;
  7533. $wordlist = file($CFG->wordlist);
  7534. $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  7535. $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  7536. $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
  7537. $password = $word1 . $filler1 . $word2;
  7538. } else {
  7539. $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
  7540. $digits = $CFG->minpassworddigits;
  7541. $lower = $CFG->minpasswordlower;
  7542. $upper = $CFG->minpasswordupper;
  7543. $nonalphanum = $CFG->minpasswordnonalphanum;
  7544. $total = $lower + $upper + $digits + $nonalphanum;
  7545. // Var minlength should be the greater one of the two ( $minlen and $total ).
  7546. $minlen = $minlen < $total ? $total : $minlen;
  7547. // Var maxlen can never be smaller than minlen.
  7548. $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
  7549. $additional = $maxlen - $total;
  7550. // Make sure we have enough characters to fulfill
  7551. // complexity requirements.
  7552. $passworddigits = PASSWORD_DIGITS;
  7553. while ($digits > strlen($passworddigits)) {
  7554. $passworddigits .= PASSWORD_DIGITS;
  7555. }
  7556. $passwordlower = PASSWORD_LOWER;
  7557. while ($lower > strlen($passwordlower)) {
  7558. $passwordlower .= PASSWORD_LOWER;
  7559. }
  7560. $passwordupper = PASSWORD_UPPER;
  7561. while ($upper > strlen($passwordupper)) {
  7562. $passwordupper .= PASSWORD_UPPER;
  7563. }
  7564. $passwordnonalphanum = PASSWORD_NONALPHANUM;
  7565. while ($nonalphanum > strlen($passwordnonalphanum)) {
  7566. $passwordnonalphanum .= PASSWORD_NONALPHANUM;
  7567. }
  7568. // Now mix and shuffle it all.
  7569. $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
  7570. substr(str_shuffle ($passwordupper), 0, $upper) .
  7571. substr(str_shuffle ($passworddigits), 0, $digits) .
  7572. substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
  7573. substr(str_shuffle ($passwordlower .
  7574. $passwordupper .
  7575. $passworddigits .
  7576. $passwordnonalphanum), 0 , $additional));
  7577. }
  7578. return substr ($password, 0, $maxlen);
  7579. }
  7580. /**
  7581. * Given a float, prints it nicely.
  7582. * Localized floats must not be used in calculations!
  7583. *
  7584. * The stripzeros feature is intended for making numbers look nicer in small
  7585. * areas where it is not necessary to indicate the degree of accuracy by showing
  7586. * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
  7587. * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
  7588. *
  7589. * @param float $float The float to print
  7590. * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
  7591. * @param bool $localized use localized decimal separator
  7592. * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
  7593. * the decimal point are always striped if $decimalpoints is -1.
  7594. * @return string locale float
  7595. */
  7596. function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
  7597. if (is_null($float)) {
  7598. return '';
  7599. }
  7600. if ($localized) {
  7601. $separator = get_string('decsep', 'langconfig');
  7602. } else {
  7603. $separator = '.';
  7604. }
  7605. if ($decimalpoints == -1) {
  7606. // The following counts the number of decimals.
  7607. // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
  7608. $floatval = floatval($float);
  7609. for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
  7610. }
  7611. $result = number_format($float, $decimalpoints, $separator, '');
  7612. if ($stripzeros) {
  7613. // Remove zeros and final dot if not needed.
  7614. $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
  7615. }
  7616. return $result;
  7617. }
  7618. /**
  7619. * Converts locale specific floating point/comma number back to standard PHP float value
  7620. * Do NOT try to do any math operations before this conversion on any user submitted floats!
  7621. *
  7622. * @param string $localefloat locale aware float representation
  7623. * @param bool $strict If true, then check the input and return false if it is not a valid number.
  7624. * @return mixed float|bool - false or the parsed float.
  7625. */
  7626. function unformat_float($localefloat, $strict = false) {
  7627. $localefloat = trim($localefloat);
  7628. if ($localefloat == '') {
  7629. return null;
  7630. }
  7631. $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
  7632. $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
  7633. if ($strict && !is_numeric($localefloat)) {
  7634. return false;
  7635. }
  7636. return (float)$localefloat;
  7637. }
  7638. /**
  7639. * Given a simple array, this shuffles it up just like shuffle()
  7640. * Unlike PHP's shuffle() this function works on any machine.
  7641. *
  7642. * @param array $array The array to be rearranged
  7643. * @return array
  7644. */
  7645. function swapshuffle($array) {
  7646. $last = count($array) - 1;
  7647. for ($i = 0; $i <= $last; $i++) {
  7648. $from = rand(0, $last);
  7649. $curr = $array[$i];
  7650. $array[$i] = $array[$from];
  7651. $array[$from] = $curr;
  7652. }
  7653. return $array;
  7654. }
  7655. /**
  7656. * Like {@link swapshuffle()}, but works on associative arrays
  7657. *
  7658. * @param array $array The associative array to be rearranged
  7659. * @return array
  7660. */
  7661. function swapshuffle_assoc($array) {
  7662. $newarray = array();
  7663. $newkeys = swapshuffle(array_keys($array));
  7664. foreach ($newkeys as $newkey) {
  7665. $newarray[$newkey] = $array[$newkey];
  7666. }
  7667. return $newarray;
  7668. }
  7669. /**
  7670. * Given an arbitrary array, and a number of draws,
  7671. * this function returns an array with that amount
  7672. * of items. The indexes are retained.
  7673. *
  7674. * @todo Finish documenting this function
  7675. *
  7676. * @param array $array
  7677. * @param int $draws
  7678. * @return array
  7679. */
  7680. function draw_rand_array($array, $draws) {
  7681. $return = array();
  7682. $last = count($array);
  7683. if ($draws > $last) {
  7684. $draws = $last;
  7685. }
  7686. while ($draws > 0) {
  7687. $last--;
  7688. $keys = array_keys($array);
  7689. $rand = rand(0, $last);
  7690. $return[$keys[$rand]] = $array[$keys[$rand]];
  7691. unset($array[$keys[$rand]]);
  7692. $draws--;
  7693. }
  7694. return $return;
  7695. }
  7696. /**
  7697. * Calculate the difference between two microtimes
  7698. *
  7699. * @param string $a The first Microtime
  7700. * @param string $b The second Microtime
  7701. * @return string
  7702. */
  7703. function microtime_diff($a, $b) {
  7704. list($adec, $asec) = explode(' ', $a);
  7705. list($bdec, $bsec) = explode(' ', $b);
  7706. return $bsec - $asec + $bdec - $adec;
  7707. }
  7708. /**
  7709. * Given a list (eg a,b,c,d,e) this function returns
  7710. * an array of 1->a, 2->b, 3->c etc
  7711. *
  7712. * @param string $list The string to explode into array bits
  7713. * @param string $separator The separator used within the list string
  7714. * @return array The now assembled array
  7715. */
  7716. function make_menu_from_list($list, $separator=',') {
  7717. $array = array_reverse(explode($separator, $list), true);
  7718. foreach ($array as $key => $item) {
  7719. $outarray[$key+1] = trim($item);
  7720. }
  7721. return $outarray;
  7722. }
  7723. /**
  7724. * Creates an array that represents all the current grades that
  7725. * can be chosen using the given grading type.
  7726. *
  7727. * Negative numbers
  7728. * are scales, zero is no grade, and positive numbers are maximum
  7729. * grades.
  7730. *
  7731. * @todo Finish documenting this function or better deprecated this completely!
  7732. *
  7733. * @param int $gradingtype
  7734. * @return array
  7735. */
  7736. function make_grades_menu($gradingtype) {
  7737. global $DB;
  7738. $grades = array();
  7739. if ($gradingtype < 0) {
  7740. if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
  7741. return make_menu_from_list($scale->scale);
  7742. }
  7743. } else if ($gradingtype > 0) {
  7744. for ($i=$gradingtype; $i>=0; $i--) {
  7745. $grades[$i] = $i .' / '. $gradingtype;
  7746. }
  7747. return $grades;
  7748. }
  7749. return $grades;
  7750. }
  7751. /**
  7752. * make_unique_id_code
  7753. *
  7754. * @todo Finish documenting this function
  7755. *
  7756. * @uses $_SERVER
  7757. * @param string $extra Extra string to append to the end of the code
  7758. * @return string
  7759. */
  7760. function make_unique_id_code($extra = '') {
  7761. $hostname = 'unknownhost';
  7762. if (!empty($_SERVER['HTTP_HOST'])) {
  7763. $hostname = $_SERVER['HTTP_HOST'];
  7764. } else if (!empty($_ENV['HTTP_HOST'])) {
  7765. $hostname = $_ENV['HTTP_HOST'];
  7766. } else if (!empty($_SERVER['SERVER_NAME'])) {
  7767. $hostname = $_SERVER['SERVER_NAME'];
  7768. } else if (!empty($_ENV['SERVER_NAME'])) {
  7769. $hostname = $_ENV['SERVER_NAME'];
  7770. }
  7771. $date = gmdate("ymdHis");
  7772. $random = random_string(6);
  7773. if ($extra) {
  7774. return $hostname .'+'. $date .'+'. $random .'+'. $extra;
  7775. } else {
  7776. return $hostname .'+'. $date .'+'. $random;
  7777. }
  7778. }
  7779. /**
  7780. * Function to check the passed address is within the passed subnet
  7781. *
  7782. * The parameter is a comma separated string of subnet definitions.
  7783. * Subnet strings can be in one of three formats:
  7784. * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
  7785. * 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group)
  7786. * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
  7787. * Code for type 1 modified from user posted comments by mediator at
  7788. * {@link http://au.php.net/manual/en/function.ip2long.php}
  7789. *
  7790. * @param string $addr The address you are checking
  7791. * @param string $subnetstr The string of subnet addresses
  7792. * @return bool
  7793. */
  7794. function address_in_subnet($addr, $subnetstr) {
  7795. if ($addr == '0.0.0.0') {
  7796. return false;
  7797. }
  7798. $subnets = explode(',', $subnetstr);
  7799. $found = false;
  7800. $addr = trim($addr);
  7801. $addr = cleanremoteaddr($addr, false); // Normalise.
  7802. if ($addr === null) {
  7803. return false;
  7804. }
  7805. $addrparts = explode(':', $addr);
  7806. $ipv6 = strpos($addr, ':');
  7807. foreach ($subnets as $subnet) {
  7808. $subnet = trim($subnet);
  7809. if ($subnet === '') {
  7810. continue;
  7811. }
  7812. if (strpos($subnet, '/') !== false) {
  7813. // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
  7814. list($ip, $mask) = explode('/', $subnet);
  7815. $mask = trim($mask);
  7816. if (!is_number($mask)) {
  7817. continue; // Incorect mask number, eh?
  7818. }
  7819. $ip = cleanremoteaddr($ip, false); // Normalise.
  7820. if ($ip === null) {
  7821. continue;
  7822. }
  7823. if (strpos($ip, ':') !== false) {
  7824. // IPv6.
  7825. if (!$ipv6) {
  7826. continue;
  7827. }
  7828. if ($mask > 128 or $mask < 0) {
  7829. continue; // Nonsense.
  7830. }
  7831. if ($mask == 0) {
  7832. return true; // Any address.
  7833. }
  7834. if ($mask == 128) {
  7835. if ($ip === $addr) {
  7836. return true;
  7837. }
  7838. continue;
  7839. }
  7840. $ipparts = explode(':', $ip);
  7841. $modulo = $mask % 16;
  7842. $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
  7843. $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
  7844. if (implode(':', $ipnet) === implode(':', $addrnet)) {
  7845. if ($modulo == 0) {
  7846. return true;
  7847. }
  7848. $pos = ($mask-$modulo)/16;
  7849. $ipnet = hexdec($ipparts[$pos]);
  7850. $addrnet = hexdec($addrparts[$pos]);
  7851. $mask = 0xffff << (16 - $modulo);
  7852. if (($addrnet & $mask) == ($ipnet & $mask)) {
  7853. return true;
  7854. }
  7855. }
  7856. } else {
  7857. // IPv4.
  7858. if ($ipv6) {
  7859. continue;
  7860. }
  7861. if ($mask > 32 or $mask < 0) {
  7862. continue; // Nonsense.
  7863. }
  7864. if ($mask == 0) {
  7865. return true;
  7866. }
  7867. if ($mask == 32) {
  7868. if ($ip === $addr) {
  7869. return true;
  7870. }
  7871. continue;
  7872. }
  7873. $mask = 0xffffffff << (32 - $mask);
  7874. if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
  7875. return true;
  7876. }
  7877. }
  7878. } else if (strpos($subnet, '-') !== false) {
  7879. // 2: xxx.xxx.xxx.xxx-yyy or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
  7880. $parts = explode('-', $subnet);
  7881. if (count($parts) != 2) {
  7882. continue;
  7883. }
  7884. if (strpos($subnet, ':') !== false) {
  7885. // IPv6.
  7886. if (!$ipv6) {
  7887. continue;
  7888. }
  7889. $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
  7890. if ($ipstart === null) {
  7891. continue;
  7892. }
  7893. $ipparts = explode(':', $ipstart);
  7894. $start = hexdec(array_pop($ipparts));
  7895. $ipparts[] = trim($parts[1]);
  7896. $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
  7897. if ($ipend === null) {
  7898. continue;
  7899. }
  7900. $ipparts[7] = '';
  7901. $ipnet = implode(':', $ipparts);
  7902. if (strpos($addr, $ipnet) !== 0) {
  7903. continue;
  7904. }
  7905. $ipparts = explode(':', $ipend);
  7906. $end = hexdec($ipparts[7]);
  7907. $addrend = hexdec($addrparts[7]);
  7908. if (($addrend >= $start) and ($addrend <= $end)) {
  7909. return true;
  7910. }
  7911. } else {
  7912. // IPv4.
  7913. if ($ipv6) {
  7914. continue;
  7915. }
  7916. $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
  7917. if ($ipstart === null) {
  7918. continue;
  7919. }
  7920. $ipparts = explode('.', $ipstart);
  7921. $ipparts[3] = trim($parts[1]);
  7922. $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
  7923. if ($ipend === null) {
  7924. continue;
  7925. }
  7926. if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
  7927. return true;
  7928. }
  7929. }
  7930. } else {
  7931. // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
  7932. if (strpos($subnet, ':') !== false) {
  7933. // IPv6.
  7934. if (!$ipv6) {
  7935. continue;
  7936. }
  7937. $parts = explode(':', $subnet);
  7938. $count = count($parts);
  7939. if ($parts[$count-1] === '') {
  7940. unset($parts[$count-1]); // Trim trailing :'s.
  7941. $count--;
  7942. $subnet = implode('.', $parts);
  7943. }
  7944. $isip = cleanremoteaddr($subnet, false); // Normalise.
  7945. if ($isip !== null) {
  7946. if ($isip === $addr) {
  7947. return true;
  7948. }
  7949. continue;
  7950. } else if ($count > 8) {
  7951. continue;
  7952. }
  7953. $zeros = array_fill(0, 8-$count, '0');
  7954. $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
  7955. if (address_in_subnet($addr, $subnet)) {
  7956. return true;
  7957. }
  7958. } else {
  7959. // IPv4.
  7960. if ($ipv6) {
  7961. continue;
  7962. }
  7963. $parts = explode('.', $subnet);
  7964. $count = count($parts);
  7965. if ($parts[$count-1] === '') {
  7966. unset($parts[$count-1]); // Trim trailing .
  7967. $count--;
  7968. $subnet = implode('.', $parts);
  7969. }
  7970. if ($count == 4) {
  7971. $subnet = cleanremoteaddr($subnet, false); // Normalise.
  7972. if ($subnet === $addr) {
  7973. return true;
  7974. }
  7975. continue;
  7976. } else if ($count > 4) {
  7977. continue;
  7978. }
  7979. $zeros = array_fill(0, 4-$count, '0');
  7980. $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
  7981. if (address_in_subnet($addr, $subnet)) {
  7982. return true;
  7983. }
  7984. }
  7985. }
  7986. }
  7987. return false;
  7988. }
  7989. /**
  7990. * For outputting debugging info
  7991. *
  7992. * @param string $string The string to write
  7993. * @param string $eol The end of line char(s) to use
  7994. * @param string $sleep Period to make the application sleep
  7995. * This ensures any messages have time to display before redirect
  7996. */
  7997. function mtrace($string, $eol="\n", $sleep=0) {
  7998. global $CFG;
  7999. if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
  8000. $fn = $CFG->mtrace_wrapper;
  8001. $fn($string, $eol);
  8002. return;
  8003. } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
  8004. // We must explicitly call the add_line function here.
  8005. // Uses of fwrite to STDOUT are not picked up by ob_start.
  8006. if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
  8007. fwrite(STDOUT, $output);
  8008. }
  8009. } else {
  8010. echo $string . $eol;
  8011. }
  8012. // Flush again.
  8013. flush();
  8014. // Delay to keep message on user's screen in case of subsequent redirect.
  8015. if ($sleep) {
  8016. sleep($sleep);
  8017. }
  8018. }
  8019. /**
  8020. * Replace 1 or more slashes or backslashes to 1 slash
  8021. *
  8022. * @param string $path The path to strip
  8023. * @return string the path with double slashes removed
  8024. */
  8025. function cleardoubleslashes ($path) {
  8026. return preg_replace('/(\/|\\\){1,}/', '/', $path);
  8027. }
  8028. /**
  8029. * Is the current ip in a given list?
  8030. *
  8031. * @param string $list
  8032. * @return bool
  8033. */
  8034. function remoteip_in_list($list) {
  8035. $clientip = getremoteaddr(null);
  8036. if (!$clientip) {
  8037. // Ensure access on cli.
  8038. return true;
  8039. }
  8040. return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
  8041. }
  8042. /**
  8043. * Returns most reliable client address
  8044. *
  8045. * @param string $default If an address can't be determined, then return this
  8046. * @return string The remote IP address
  8047. */
  8048. function getremoteaddr($default='0.0.0.0') {
  8049. global $CFG;
  8050. if (!isset($CFG->getremoteaddrconf)) {
  8051. // This will happen, for example, before just after the upgrade, as the
  8052. // user is redirected to the admin screen.
  8053. $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
  8054. } else {
  8055. $variablestoskip = $CFG->getremoteaddrconf;
  8056. }
  8057. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
  8058. if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  8059. $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
  8060. return $address ? $address : $default;
  8061. }
  8062. }
  8063. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
  8064. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  8065. $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
  8066. $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
  8067. global $CFG;
  8068. return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
  8069. });
  8070. // Multiple proxies can append values to this header including an
  8071. // untrusted original request header so we must only trust the last ip.
  8072. $address = end($forwardedaddresses);
  8073. if (substr_count($address, ":") > 1) {
  8074. // Remove port and brackets from IPv6.
  8075. if (preg_match("/\[(.*)\]:/", $address, $matches)) {
  8076. $address = $matches[1];
  8077. }
  8078. } else {
  8079. // Remove port from IPv4.
  8080. if (substr_count($address, ":") == 1) {
  8081. $parts = explode(":", $address);
  8082. $address = $parts[0];
  8083. }
  8084. }
  8085. $address = cleanremoteaddr($address);
  8086. return $address ? $address : $default;
  8087. }
  8088. }
  8089. if (!empty($_SERVER['REMOTE_ADDR'])) {
  8090. $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
  8091. return $address ? $address : $default;
  8092. } else {
  8093. return $default;
  8094. }
  8095. }
  8096. /**
  8097. * Cleans an ip address. Internal addresses are now allowed.
  8098. * (Originally local addresses were not allowed.)
  8099. *
  8100. * @param string $addr IPv4 or IPv6 address
  8101. * @param bool $compress use IPv6 address compression
  8102. * @return string normalised ip address string, null if error
  8103. */
  8104. function cleanremoteaddr($addr, $compress=false) {
  8105. $addr = trim($addr);
  8106. if (strpos($addr, ':') !== false) {
  8107. // Can be only IPv6.
  8108. $parts = explode(':', $addr);
  8109. $count = count($parts);
  8110. if (strpos($parts[$count-1], '.') !== false) {
  8111. // Legacy ipv4 notation.
  8112. $last = array_pop($parts);
  8113. $ipv4 = cleanremoteaddr($last, true);
  8114. if ($ipv4 === null) {
  8115. return null;
  8116. }
  8117. $bits = explode('.', $ipv4);
  8118. $parts[] = dechex($bits[0]).dechex($bits[1]);
  8119. $parts[] = dechex($bits[2]).dechex($bits[3]);
  8120. $count = count($parts);
  8121. $addr = implode(':', $parts);
  8122. }
  8123. if ($count < 3 or $count > 8) {
  8124. return null; // Severly malformed.
  8125. }
  8126. if ($count != 8) {
  8127. if (strpos($addr, '::') === false) {
  8128. return null; // Malformed.
  8129. }
  8130. // Uncompress.
  8131. $insertat = array_search('', $parts, true);
  8132. $missing = array_fill(0, 1 + 8 - $count, '0');
  8133. array_splice($parts, $insertat, 1, $missing);
  8134. foreach ($parts as $key => $part) {
  8135. if ($part === '') {
  8136. $parts[$key] = '0';
  8137. }
  8138. }
  8139. }
  8140. $adr = implode(':', $parts);
  8141. if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
  8142. return null; // Incorrect format - sorry.
  8143. }
  8144. // Normalise 0s and case.
  8145. $parts = array_map('hexdec', $parts);
  8146. $parts = array_map('dechex', $parts);
  8147. $result = implode(':', $parts);
  8148. if (!$compress) {
  8149. return $result;
  8150. }
  8151. if ($result === '0:0:0:0:0:0:0:0') {
  8152. return '::'; // All addresses.
  8153. }
  8154. $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
  8155. if ($compressed !== $result) {
  8156. return $compressed;
  8157. }
  8158. $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
  8159. if ($compressed !== $result) {
  8160. return $compressed;
  8161. }
  8162. $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
  8163. if ($compressed !== $result) {
  8164. return $compressed;
  8165. }
  8166. return $result;
  8167. }
  8168. // First get all things that look like IPv4 addresses.
  8169. $parts = array();
  8170. if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
  8171. return null;
  8172. }
  8173. unset($parts[0]);
  8174. foreach ($parts as $key => $match) {
  8175. if ($match > 255) {
  8176. return null;
  8177. }
  8178. $parts[$key] = (int)$match; // Normalise 0s.
  8179. }
  8180. return implode('.', $parts);
  8181. }
  8182. /**
  8183. * Is IP address a public address?
  8184. *
  8185. * @param string $ip The ip to check
  8186. * @return bool true if the ip is public
  8187. */
  8188. function ip_is_public($ip) {
  8189. return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
  8190. }
  8191. /**
  8192. * This function will make a complete copy of anything it's given,
  8193. * regardless of whether it's an object or not.
  8194. *
  8195. * @param mixed $thing Something you want cloned
  8196. * @return mixed What ever it is you passed it
  8197. */
  8198. function fullclone($thing) {
  8199. return unserialize(serialize($thing));
  8200. }
  8201. /**
  8202. * Used to make sure that $min <= $value <= $max
  8203. *
  8204. * Make sure that value is between min, and max
  8205. *
  8206. * @param int $min The minimum value
  8207. * @param int $value The value to check
  8208. * @param int $max The maximum value
  8209. * @return int
  8210. */
  8211. function bounded_number($min, $value, $max) {
  8212. if ($value < $min) {
  8213. return $min;
  8214. }
  8215. if ($value > $max) {
  8216. return $max;
  8217. }
  8218. return $value;
  8219. }
  8220. /**
  8221. * Check if there is a nested array within the passed array
  8222. *
  8223. * @param array $array
  8224. * @return bool true if there is a nested array false otherwise
  8225. */
  8226. function array_is_nested($array) {
  8227. foreach ($array as $value) {
  8228. if (is_array($value)) {
  8229. return true;
  8230. }
  8231. }
  8232. return false;
  8233. }
  8234. /**
  8235. * get_performance_info() pairs up with init_performance_info()
  8236. * loaded in setup.php. Returns an array with 'html' and 'txt'
  8237. * values ready for use, and each of the individual stats provided
  8238. * separately as well.
  8239. *
  8240. * @return array
  8241. */
  8242. function get_performance_info() {
  8243. global $CFG, $PERF, $DB, $PAGE;
  8244. $info = array();
  8245. $info['txt'] = me() . ' '; // Holds log-friendly representation.
  8246. $info['html'] = '';
  8247. if (!empty($CFG->themedesignermode)) {
  8248. // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
  8249. $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
  8250. }
  8251. $info['html'] .= '<ul class="list-unstyled row mx-md-0">'; // Holds userfriendly HTML representation.
  8252. $info['realtime'] = microtime_diff($PERF->starttime, microtime());
  8253. $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
  8254. $info['txt'] .= 'time: '.$info['realtime'].'s ';
  8255. // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
  8256. $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
  8257. if (function_exists('memory_get_usage')) {
  8258. $info['memory_total'] = memory_get_usage();
  8259. $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
  8260. $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
  8261. $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
  8262. $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
  8263. }
  8264. if (function_exists('memory_get_peak_usage')) {
  8265. $info['memory_peak'] = memory_get_peak_usage();
  8266. $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
  8267. $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
  8268. }
  8269. $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
  8270. $inc = get_included_files();
  8271. $info['includecount'] = count($inc);
  8272. $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
  8273. $info['txt'] .= 'includecount: '.$info['includecount'].' ';
  8274. if (!empty($CFG->early_install_lang) or empty($PAGE)) {
  8275. // We can not track more performance before installation or before PAGE init, sorry.
  8276. return $info;
  8277. }
  8278. $filtermanager = filter_manager::instance();
  8279. if (method_exists($filtermanager, 'get_performance_summary')) {
  8280. list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
  8281. $info = array_merge($filterinfo, $info);
  8282. foreach ($filterinfo as $key => $value) {
  8283. $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
  8284. $info['txt'] .= "$key: $value ";
  8285. }
  8286. }
  8287. $stringmanager = get_string_manager();
  8288. if (method_exists($stringmanager, 'get_performance_summary')) {
  8289. list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
  8290. $info = array_merge($filterinfo, $info);
  8291. foreach ($filterinfo as $key => $value) {
  8292. $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
  8293. $info['txt'] .= "$key: $value ";
  8294. }
  8295. }
  8296. if (!empty($PERF->logwrites)) {
  8297. $info['logwrites'] = $PERF->logwrites;
  8298. $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
  8299. $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
  8300. }
  8301. $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
  8302. $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
  8303. $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
  8304. if ($DB->want_read_slave()) {
  8305. $info['dbreads_slave'] = $DB->perf_get_reads_slave();
  8306. $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
  8307. $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
  8308. }
  8309. $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
  8310. $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
  8311. $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
  8312. if (function_exists('posix_times')) {
  8313. $ptimes = posix_times();
  8314. if (is_array($ptimes)) {
  8315. foreach ($ptimes as $key => $val) {
  8316. $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
  8317. }
  8318. $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
  8319. $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
  8320. $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
  8321. }
  8322. }
  8323. // Grab the load average for the last minute.
  8324. // /proc will only work under some linux configurations
  8325. // while uptime is there under MacOSX/Darwin and other unices.
  8326. if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
  8327. list($serverload) = explode(' ', $loadavg[0]);
  8328. unset($loadavg);
  8329. } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
  8330. if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
  8331. $serverload = $matches[1];
  8332. } else {
  8333. trigger_error('Could not parse uptime output!');
  8334. }
  8335. }
  8336. if (!empty($serverload)) {
  8337. $info['serverload'] = $serverload;
  8338. $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
  8339. $info['txt'] .= "serverload: {$info['serverload']} ";
  8340. }
  8341. // Display size of session if session started.
  8342. if ($si = \core\session\manager::get_performance_info()) {
  8343. $info['sessionsize'] = $si['size'];
  8344. $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
  8345. $info['txt'] .= $si['txt'];
  8346. }
  8347. $info['html'] .= '</ul>';
  8348. $html = '';
  8349. if ($stats = cache_helper::get_stats()) {
  8350. $table = new html_table();
  8351. $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
  8352. $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
  8353. $table->data = [];
  8354. $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
  8355. $text = 'Caches used (hits/misses/sets): ';
  8356. $hits = 0;
  8357. $misses = 0;
  8358. $sets = 0;
  8359. $maxstores = 0;
  8360. // We want to align static caches into their own column.
  8361. $hasstatic = false;
  8362. foreach ($stats as $definition => $details) {
  8363. $numstores = count($details['stores']);
  8364. $first = key($details['stores']);
  8365. if ($first !== cache_store::STATIC_ACCEL) {
  8366. $numstores++; // Add a blank space for the missing static store.
  8367. }
  8368. $maxstores = max($maxstores, $numstores);
  8369. }
  8370. $storec = 0;
  8371. while ($storec++ < ($maxstores - 2)) {
  8372. if ($storec == ($maxstores - 2)) {
  8373. $table->head[] = get_string('mappingfinal', 'cache');
  8374. } else {
  8375. $table->head[] = "Store $storec";
  8376. }
  8377. $table->align[] = 'left';
  8378. $table->align[] = 'right';
  8379. $table->align[] = 'right';
  8380. $table->align[] = 'right';
  8381. $table->align[] = 'right';
  8382. $table->head[] = 'H';
  8383. $table->head[] = 'M';
  8384. $table->head[] = 'S';
  8385. $table->head[] = 'I/O';
  8386. }
  8387. ksort($stats);
  8388. foreach ($stats as $definition => $details) {
  8389. switch ($details['mode']) {
  8390. case cache_store::MODE_APPLICATION:
  8391. $modeclass = 'application';
  8392. $mode = ' <span title="application cache">App</span>';
  8393. break;
  8394. case cache_store::MODE_SESSION:
  8395. $modeclass = 'session';
  8396. $mode = ' <span title="session cache">Ses</span>';
  8397. break;
  8398. case cache_store::MODE_REQUEST:
  8399. $modeclass = 'request';
  8400. $mode = ' <span title="request cache">Req</span>';
  8401. break;
  8402. }
  8403. $row = [$mode, $definition];
  8404. $text .= "$definition {";
  8405. $storec = 0;
  8406. foreach ($details['stores'] as $store => $data) {
  8407. if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
  8408. $row[] = '';
  8409. $row[] = '';
  8410. $row[] = '';
  8411. $storec++;
  8412. }
  8413. $hits += $data['hits'];
  8414. $misses += $data['misses'];
  8415. $sets += $data['sets'];
  8416. if ($data['hits'] == 0 and $data['misses'] > 0) {
  8417. $cachestoreclass = 'nohits bg-danger';
  8418. } else if ($data['hits'] < $data['misses']) {
  8419. $cachestoreclass = 'lowhits bg-warning text-dark';
  8420. } else {
  8421. $cachestoreclass = 'hihits';
  8422. }
  8423. $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
  8424. $cell = new html_table_cell($store);
  8425. $cell->attributes = ['class' => $cachestoreclass];
  8426. $row[] = $cell;
  8427. $cell = new html_table_cell($data['hits']);
  8428. $cell->attributes = ['class' => $cachestoreclass];
  8429. $row[] = $cell;
  8430. $cell = new html_table_cell($data['misses']);
  8431. $cell->attributes = ['class' => $cachestoreclass];
  8432. $row[] = $cell;
  8433. if ($store !== cache_store::STATIC_ACCEL) {
  8434. // The static cache is never set.
  8435. $cell = new html_table_cell($data['sets']);
  8436. $cell->attributes = ['class' => $cachestoreclass];
  8437. $row[] = $cell;
  8438. if ($data['hits'] || $data['sets']) {
  8439. if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
  8440. $size = '-';
  8441. } else {
  8442. $size = display_size($data['iobytes'], 1, 'KB');
  8443. if ($data['iobytes'] >= 10 * 1024) {
  8444. $cachestoreclass = ' bg-warning text-dark';
  8445. }
  8446. }
  8447. } else {
  8448. $size = '';
  8449. }
  8450. $cell = new html_table_cell($size);
  8451. $cell->attributes = ['class' => $cachestoreclass];
  8452. $row[] = $cell;
  8453. }
  8454. $storec++;
  8455. }
  8456. while ($storec++ < $maxstores) {
  8457. $row[] = '';
  8458. $row[] = '';
  8459. $row[] = '';
  8460. $row[] = '';
  8461. $row[] = '';
  8462. }
  8463. $text .= '} ';
  8464. $table->data[] = $row;
  8465. }
  8466. $html .= html_writer::table($table);
  8467. // Now lets also show sub totals for each cache store.
  8468. $storetotals = [];
  8469. $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
  8470. foreach ($stats as $definition => $details) {
  8471. foreach ($details['stores'] as $store => $data) {
  8472. if (!array_key_exists($store, $storetotals)) {
  8473. $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
  8474. }
  8475. $storetotals[$store]['class'] = $data['class'];
  8476. $storetotals[$store]['hits'] += $data['hits'];
  8477. $storetotals[$store]['misses'] += $data['misses'];
  8478. $storetotals[$store]['sets'] += $data['sets'];
  8479. $storetotal['hits'] += $data['hits'];
  8480. $storetotal['misses'] += $data['misses'];
  8481. $storetotal['sets'] += $data['sets'];
  8482. if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
  8483. $storetotals[$store]['iobytes'] += $data['iobytes'];
  8484. $storetotal['iobytes'] += $data['iobytes'];
  8485. }
  8486. }
  8487. }
  8488. $table = new html_table();
  8489. $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
  8490. $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
  8491. $table->data = [];
  8492. $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
  8493. ksort($storetotals);
  8494. foreach ($storetotals as $store => $data) {
  8495. $row = [];
  8496. if ($data['hits'] == 0 and $data['misses'] > 0) {
  8497. $cachestoreclass = 'nohits bg-danger';
  8498. } else if ($data['hits'] < $data['misses']) {
  8499. $cachestoreclass = 'lowhits bg-warning text-dark';
  8500. } else {
  8501. $cachestoreclass = 'hihits';
  8502. }
  8503. $cell = new html_table_cell($store);
  8504. $cell->attributes = ['class' => $cachestoreclass];
  8505. $row[] = $cell;
  8506. $cell = new html_table_cell($data['class']);
  8507. $cell->attributes = ['class' => $cachestoreclass];
  8508. $row[] = $cell;
  8509. $cell = new html_table_cell($data['hits']);
  8510. $cell->attributes = ['class' => $cachestoreclass];
  8511. $row[] = $cell;
  8512. $cell = new html_table_cell($data['misses']);
  8513. $cell->attributes = ['class' => $cachestoreclass];
  8514. $row[] = $cell;
  8515. $cell = new html_table_cell($data['sets']);
  8516. $cell->attributes = ['class' => $cachestoreclass];
  8517. $row[] = $cell;
  8518. if ($data['hits'] || $data['sets']) {
  8519. if ($data['iobytes']) {
  8520. $size = display_size($data['iobytes'], 1, 'KB');
  8521. } else {
  8522. $size = '-';
  8523. }
  8524. } else {
  8525. $size = '';
  8526. }
  8527. $cell = new html_table_cell($size);
  8528. $cell->attributes = ['class' => $cachestoreclass];
  8529. $row[] = $cell;
  8530. $table->data[] = $row;
  8531. }
  8532. if (!empty($storetotal['iobytes'])) {
  8533. $size = display_size($storetotal['iobytes'], 1, 'KB');
  8534. } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
  8535. $size = '-';
  8536. } else {
  8537. $size = '';
  8538. }
  8539. $row = [
  8540. get_string('total'),
  8541. '',
  8542. $storetotal['hits'],
  8543. $storetotal['misses'],
  8544. $storetotal['sets'],
  8545. $size,
  8546. ];
  8547. $table->data[] = $row;
  8548. $html .= html_writer::table($table);
  8549. $info['cachesused'] = "$hits / $misses / $sets";
  8550. $info['html'] .= $html;
  8551. $info['txt'] .= $text.'. ';
  8552. } else {
  8553. $info['cachesused'] = '0 / 0 / 0';
  8554. $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
  8555. $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
  8556. }
  8557. $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto mt-3">'.$info['html'].'</div>';
  8558. return $info;
  8559. }
  8560. /**
  8561. * Renames a file or directory to a unique name within the same directory.
  8562. *
  8563. * This function is designed to avoid any potential race conditions, and select an unused name.
  8564. *
  8565. * @param string $filepath Original filepath
  8566. * @param string $prefix Prefix to use for the temporary name
  8567. * @return string|bool New file path or false if failed
  8568. * @since Moodle 3.10
  8569. */
  8570. function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
  8571. $dir = dirname($filepath);
  8572. $basename = $dir . '/' . $prefix;
  8573. $limit = 0;
  8574. while ($limit < 100) {
  8575. // Select a new name based on a random number.
  8576. $newfilepath = $basename . md5(mt_rand());
  8577. // Attempt a rename to that new name.
  8578. if (@rename($filepath, $newfilepath)) {
  8579. return $newfilepath;
  8580. }
  8581. // The first time, do some sanity checks, maybe it is failing for a good reason and there
  8582. // is no point trying 100 times if so.
  8583. if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
  8584. return false;
  8585. }
  8586. $limit++;
  8587. }
  8588. return false;
  8589. }
  8590. /**
  8591. * Delete directory or only its content
  8592. *
  8593. * @param string $dir directory path
  8594. * @param bool $contentonly
  8595. * @return bool success, true also if dir does not exist
  8596. */
  8597. function remove_dir($dir, $contentonly=false) {
  8598. if (!is_dir($dir)) {
  8599. // Nothing to do.
  8600. return true;
  8601. }
  8602. if (!$contentonly) {
  8603. // Start by renaming the directory; this will guarantee that other processes don't write to it
  8604. // while it is in the process of being deleted.
  8605. $tempdir = rename_to_unused_name($dir);
  8606. if ($tempdir) {
  8607. // If the rename was successful then delete the $tempdir instead.
  8608. $dir = $tempdir;
  8609. }
  8610. // If the rename fails, we will continue through and attempt to delete the directory
  8611. // without renaming it since that is likely to at least delete most of the files.
  8612. }
  8613. if (!$handle = opendir($dir)) {
  8614. return false;
  8615. }
  8616. $result = true;
  8617. while (false!==($item = readdir($handle))) {
  8618. if ($item != '.' && $item != '..') {
  8619. if (is_dir($dir.'/'.$item)) {
  8620. $result = remove_dir($dir.'/'.$item) && $result;
  8621. } else {
  8622. $result = unlink($dir.'/'.$item) && $result;
  8623. }
  8624. }
  8625. }
  8626. closedir($handle);
  8627. if ($contentonly) {
  8628. clearstatcache(); // Make sure file stat cache is properly invalidated.
  8629. return $result;
  8630. }
  8631. $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
  8632. clearstatcache(); // Make sure file stat cache is properly invalidated.
  8633. return $result;
  8634. }
  8635. /**
  8636. * Detect if an object or a class contains a given property
  8637. * will take an actual object or the name of a class
  8638. *
  8639. * @param mix $obj Name of class or real object to test
  8640. * @param string $property name of property to find
  8641. * @return bool true if property exists
  8642. */
  8643. function object_property_exists( $obj, $property ) {
  8644. if (is_string( $obj )) {
  8645. $properties = get_class_vars( $obj );
  8646. } else {
  8647. $properties = get_object_vars( $obj );
  8648. }
  8649. return array_key_exists( $property, $properties );
  8650. }
  8651. /**
  8652. * Converts an object into an associative array
  8653. *
  8654. * This function converts an object into an associative array by iterating
  8655. * over its public properties. Because this function uses the foreach
  8656. * construct, Iterators are respected. It works recursively on arrays of objects.
  8657. * Arrays and simple values are returned as is.
  8658. *
  8659. * If class has magic properties, it can implement IteratorAggregate
  8660. * and return all available properties in getIterator()
  8661. *
  8662. * @param mixed $var
  8663. * @return array
  8664. */
  8665. function convert_to_array($var) {
  8666. $result = array();
  8667. // Loop over elements/properties.
  8668. foreach ($var as $key => $value) {
  8669. // Recursively convert objects.
  8670. if (is_object($value) || is_array($value)) {
  8671. $result[$key] = convert_to_array($value);
  8672. } else {
  8673. // Simple values are untouched.
  8674. $result[$key] = $value;
  8675. }
  8676. }
  8677. return $result;
  8678. }
  8679. /**
  8680. * Detect a custom script replacement in the data directory that will
  8681. * replace an existing moodle script
  8682. *
  8683. * @return string|bool full path name if a custom script exists, false if no custom script exists
  8684. */
  8685. function custom_script_path() {
  8686. global $CFG, $SCRIPT;
  8687. if ($SCRIPT === null) {
  8688. // Probably some weird external script.
  8689. return false;
  8690. }
  8691. $scriptpath = $CFG->customscripts . $SCRIPT;
  8692. // Check the custom script exists.
  8693. if (file_exists($scriptpath) and is_file($scriptpath)) {
  8694. return $scriptpath;
  8695. } else {
  8696. return false;
  8697. }
  8698. }
  8699. /**
  8700. * Returns whether or not the user object is a remote MNET user. This function
  8701. * is in moodlelib because it does not rely on loading any of the MNET code.
  8702. *
  8703. * @param object $user A valid user object
  8704. * @return bool True if the user is from a remote Moodle.
  8705. */
  8706. function is_mnet_remote_user($user) {
  8707. global $CFG;
  8708. if (!isset($CFG->mnet_localhost_id)) {
  8709. include_once($CFG->dirroot . '/mnet/lib.php');
  8710. $env = new mnet_environment();
  8711. $env->init();
  8712. unset($env);
  8713. }
  8714. return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
  8715. }
  8716. /**
  8717. * This function will search for browser prefereed languages, setting Moodle
  8718. * to use the best one available if $SESSION->lang is undefined
  8719. */
  8720. function setup_lang_from_browser() {
  8721. global $CFG, $SESSION, $USER;
  8722. if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
  8723. // Lang is defined in session or user profile, nothing to do.
  8724. return;
  8725. }
  8726. if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
  8727. return;
  8728. }
  8729. // Extract and clean langs from headers.
  8730. $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  8731. $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
  8732. $rawlangs = explode(',', $rawlangs); // Convert to array.
  8733. $langs = array();
  8734. $order = 1.0;
  8735. foreach ($rawlangs as $lang) {
  8736. if (strpos($lang, ';') === false) {
  8737. $langs[(string)$order] = $lang;
  8738. $order = $order-0.01;
  8739. } else {
  8740. $parts = explode(';', $lang);
  8741. $pos = strpos($parts[1], '=');
  8742. $langs[substr($parts[1], $pos+1)] = $parts[0];
  8743. }
  8744. }
  8745. krsort($langs, SORT_NUMERIC);
  8746. // Look for such langs under standard locations.
  8747. foreach ($langs as $lang) {
  8748. // Clean it properly for include.
  8749. $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
  8750. if (get_string_manager()->translation_exists($lang, false)) {
  8751. // Lang exists, set it in session.
  8752. $SESSION->lang = $lang;
  8753. // We have finished. Go out.
  8754. break;
  8755. }
  8756. }
  8757. return;
  8758. }
  8759. /**
  8760. * Check if $url matches anything in proxybypass list
  8761. *
  8762. * Any errors just result in the proxy being used (least bad)
  8763. *
  8764. * @param string $url url to check
  8765. * @return boolean true if we should bypass the proxy
  8766. */
  8767. function is_proxybypass( $url ) {
  8768. global $CFG;
  8769. // Sanity check.
  8770. if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
  8771. return false;
  8772. }
  8773. // Get the host part out of the url.
  8774. if (!$host = parse_url( $url, PHP_URL_HOST )) {
  8775. return false;
  8776. }
  8777. // Get the possible bypass hosts into an array.
  8778. $matches = explode( ',', $CFG->proxybypass );
  8779. // Check for a match.
  8780. // (IPs need to match the left hand side and hosts the right of the url,
  8781. // but we can recklessly check both as there can't be a false +ve).
  8782. foreach ($matches as $match) {
  8783. $match = trim($match);
  8784. // Try for IP match (Left side).
  8785. $lhs = substr($host, 0, strlen($match));
  8786. if (strcasecmp($match, $lhs)==0) {
  8787. return true;
  8788. }
  8789. // Try for host match (Right side).
  8790. $rhs = substr($host, -strlen($match));
  8791. if (strcasecmp($match, $rhs)==0) {
  8792. return true;
  8793. }
  8794. }
  8795. // Nothing matched.
  8796. return false;
  8797. }
  8798. /**
  8799. * Check if the passed navigation is of the new style
  8800. *
  8801. * @param mixed $navigation
  8802. * @return bool true for yes false for no
  8803. */
  8804. function is_newnav($navigation) {
  8805. if (is_array($navigation) && !empty($navigation['newnav'])) {
  8806. return true;
  8807. } else {
  8808. return false;
  8809. }
  8810. }
  8811. /**
  8812. * Checks whether the given variable name is defined as a variable within the given object.
  8813. *
  8814. * This will NOT work with stdClass objects, which have no class variables.
  8815. *
  8816. * @param string $var The variable name
  8817. * @param object $object The object to check
  8818. * @return boolean
  8819. */
  8820. function in_object_vars($var, $object) {
  8821. $classvars = get_class_vars(get_class($object));
  8822. $classvars = array_keys($classvars);
  8823. return in_array($var, $classvars);
  8824. }
  8825. /**
  8826. * Returns an array without repeated objects.
  8827. * This function is similar to array_unique, but for arrays that have objects as values
  8828. *
  8829. * @param array $array
  8830. * @param bool $keepkeyassoc
  8831. * @return array
  8832. */
  8833. function object_array_unique($array, $keepkeyassoc = true) {
  8834. $duplicatekeys = array();
  8835. $tmp = array();
  8836. foreach ($array as $key => $val) {
  8837. // Convert objects to arrays, in_array() does not support objects.
  8838. if (is_object($val)) {
  8839. $val = (array)$val;
  8840. }
  8841. if (!in_array($val, $tmp)) {
  8842. $tmp[] = $val;
  8843. } else {
  8844. $duplicatekeys[] = $key;
  8845. }
  8846. }
  8847. foreach ($duplicatekeys as $key) {
  8848. unset($array[$key]);
  8849. }
  8850. return $keepkeyassoc ? $array : array_values($array);
  8851. }
  8852. /**
  8853. * Is a userid the primary administrator?
  8854. *
  8855. * @param int $userid int id of user to check
  8856. * @return boolean
  8857. */
  8858. function is_primary_admin($userid) {
  8859. $primaryadmin = get_admin();
  8860. if ($userid == $primaryadmin->id) {
  8861. return true;
  8862. } else {
  8863. return false;
  8864. }
  8865. }
  8866. /**
  8867. * Returns the site identifier
  8868. *
  8869. * @return string $CFG->siteidentifier, first making sure it is properly initialised.
  8870. */
  8871. function get_site_identifier() {
  8872. global $CFG;
  8873. // Check to see if it is missing. If so, initialise it.
  8874. if (empty($CFG->siteidentifier)) {
  8875. set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
  8876. }
  8877. // Return it.
  8878. return $CFG->siteidentifier;
  8879. }
  8880. /**
  8881. * Check whether the given password has no more than the specified
  8882. * number of consecutive identical characters.
  8883. *
  8884. * @param string $password password to be checked against the password policy
  8885. * @param integer $maxchars maximum number of consecutive identical characters
  8886. * @return bool
  8887. */
  8888. function check_consecutive_identical_characters($password, $maxchars) {
  8889. if ($maxchars < 1) {
  8890. return true; // Zero 0 is to disable this check.
  8891. }
  8892. if (strlen($password) <= $maxchars) {
  8893. return true; // Too short to fail this test.
  8894. }
  8895. $previouschar = '';
  8896. $consecutivecount = 1;
  8897. foreach (str_split($password) as $char) {
  8898. if ($char != $previouschar) {
  8899. $consecutivecount = 1;
  8900. } else {
  8901. $consecutivecount++;
  8902. if ($consecutivecount > $maxchars) {
  8903. return false; // Check failed already.
  8904. }
  8905. }
  8906. $previouschar = $char;
  8907. }
  8908. return true;
  8909. }
  8910. /**
  8911. * Helper function to do partial function binding.
  8912. * so we can use it for preg_replace_callback, for example
  8913. * this works with php functions, user functions, static methods and class methods
  8914. * it returns you a callback that you can pass on like so:
  8915. *
  8916. * $callback = partial('somefunction', $arg1, $arg2);
  8917. * or
  8918. * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
  8919. * or even
  8920. * $obj = new someclass();
  8921. * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
  8922. *
  8923. * and then the arguments that are passed through at calltime are appended to the argument list.
  8924. *
  8925. * @param mixed $function a php callback
  8926. * @param mixed $arg1,... $argv arguments to partially bind with
  8927. * @return array Array callback
  8928. */
  8929. function partial() {
  8930. if (!class_exists('partial')) {
  8931. /**
  8932. * Used to manage function binding.
  8933. * @copyright 2009 Penny Leach
  8934. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  8935. */
  8936. class partial{
  8937. /** @var array */
  8938. public $values = array();
  8939. /** @var string The function to call as a callback. */
  8940. public $func;
  8941. /**
  8942. * Constructor
  8943. * @param string $func
  8944. * @param array $args
  8945. */
  8946. public function __construct($func, $args) {
  8947. $this->values = $args;
  8948. $this->func = $func;
  8949. }
  8950. /**
  8951. * Calls the callback function.
  8952. * @return mixed
  8953. */
  8954. public function method() {
  8955. $args = func_get_args();
  8956. return call_user_func_array($this->func, array_merge($this->values, $args));
  8957. }
  8958. }
  8959. }
  8960. $args = func_get_args();
  8961. $func = array_shift($args);
  8962. $p = new partial($func, $args);
  8963. return array($p, 'method');
  8964. }
  8965. /**
  8966. * helper function to load up and initialise the mnet environment
  8967. * this must be called before you use mnet functions.
  8968. *
  8969. * @return mnet_environment the equivalent of old $MNET global
  8970. */
  8971. function get_mnet_environment() {
  8972. global $CFG;
  8973. require_once($CFG->dirroot . '/mnet/lib.php');
  8974. static $instance = null;
  8975. if (empty($instance)) {
  8976. $instance = new mnet_environment();
  8977. $instance->init();
  8978. }
  8979. return $instance;
  8980. }
  8981. /**
  8982. * during xmlrpc server code execution, any code wishing to access
  8983. * information about the remote peer must use this to get it.
  8984. *
  8985. * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
  8986. */
  8987. function get_mnet_remote_client() {
  8988. if (!defined('MNET_SERVER')) {
  8989. debugging(get_string('notinxmlrpcserver', 'mnet'));
  8990. return false;
  8991. }
  8992. global $MNET_REMOTE_CLIENT;
  8993. if (isset($MNET_REMOTE_CLIENT)) {
  8994. return $MNET_REMOTE_CLIENT;
  8995. }
  8996. return false;
  8997. }
  8998. /**
  8999. * during the xmlrpc server code execution, this will be called
  9000. * to setup the object returned by {@link get_mnet_remote_client}
  9001. *
  9002. * @param mnet_remote_client $client the client to set up
  9003. * @throws moodle_exception
  9004. */
  9005. function set_mnet_remote_client($client) {
  9006. if (!defined('MNET_SERVER')) {
  9007. throw new moodle_exception('notinxmlrpcserver', 'mnet');
  9008. }
  9009. global $MNET_REMOTE_CLIENT;
  9010. $MNET_REMOTE_CLIENT = $client;
  9011. }
  9012. /**
  9013. * return the jump url for a given remote user
  9014. * this is used for rewriting forum post links in emails, etc
  9015. *
  9016. * @param stdclass $user the user to get the idp url for
  9017. */
  9018. function mnet_get_idp_jump_url($user) {
  9019. global $CFG;
  9020. static $mnetjumps = array();
  9021. if (!array_key_exists($user->mnethostid, $mnetjumps)) {
  9022. $idp = mnet_get_peer_host($user->mnethostid);
  9023. $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
  9024. $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
  9025. }
  9026. return $mnetjumps[$user->mnethostid];
  9027. }
  9028. /**
  9029. * Gets the homepage to use for the current user
  9030. *
  9031. * @return int One of HOMEPAGE_*
  9032. */
  9033. function get_home_page() {
  9034. global $CFG;
  9035. if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
  9036. if ($CFG->defaulthomepage == HOMEPAGE_MY) {
  9037. return HOMEPAGE_MY;
  9038. } else {
  9039. return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
  9040. }
  9041. }
  9042. return HOMEPAGE_SITE;
  9043. }
  9044. /**
  9045. * Gets the name of a course to be displayed when showing a list of courses.
  9046. * By default this is just $course->fullname but user can configure it. The
  9047. * result of this function should be passed through print_string.
  9048. * @param stdClass|core_course_list_element $course Moodle course object
  9049. * @return string Display name of course (either fullname or short + fullname)
  9050. */
  9051. function get_course_display_name_for_list($course) {
  9052. global $CFG;
  9053. if (!empty($CFG->courselistshortnames)) {
  9054. if (!($course instanceof stdClass)) {
  9055. $course = (object)convert_to_array($course);
  9056. }
  9057. return get_string('courseextendednamedisplay', '', $course);
  9058. } else {
  9059. return $course->fullname;
  9060. }
  9061. }
  9062. /**
  9063. * Safe analogue of unserialize() that can only parse arrays
  9064. *
  9065. * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
  9066. * Note: If any string (key or value) has semicolon (;) as part of the string parsing will fail.
  9067. * This is a simple method to substitute unnecessary unserialize() in code and not intended to cover all possible cases.
  9068. *
  9069. * @param string $expression
  9070. * @return array|bool either parsed array or false if parsing was impossible.
  9071. */
  9072. function unserialize_array($expression) {
  9073. $subs = [];
  9074. // Find nested arrays, parse them and store in $subs , substitute with special string.
  9075. while (preg_match('/([\^;\}])(a:\d+:\{[^\{\}]*\})/', $expression, $matches) && strlen($matches[2]) < strlen($expression)) {
  9076. $key = '--SUB' . count($subs) . '--';
  9077. $subs[$key] = unserialize_array($matches[2]);
  9078. if ($subs[$key] === false) {
  9079. return false;
  9080. }
  9081. $expression = str_replace($matches[2], $key . ';', $expression);
  9082. }
  9083. // Check the expression is an array.
  9084. if (!preg_match('/^a:(\d+):\{([^\}]*)\}$/', $expression, $matches1)) {
  9085. return false;
  9086. }
  9087. // Get the size and elements of an array (key;value;key;value;....).
  9088. $parts = explode(';', $matches1[2]);
  9089. $size = intval($matches1[1]);
  9090. if (count($parts) < $size * 2 + 1) {
  9091. return false;
  9092. }
  9093. // Analyze each part and make sure it is an integer or string or a substitute.
  9094. $value = [];
  9095. for ($i = 0; $i < $size * 2; $i++) {
  9096. if (preg_match('/^i:(\d+)$/', $parts[$i], $matches2)) {
  9097. $parts[$i] = (int)$matches2[1];
  9098. } else if (preg_match('/^s:(\d+):"(.*)"$/', $parts[$i], $matches3) && strlen($matches3[2]) == (int)$matches3[1]) {
  9099. $parts[$i] = $matches3[2];
  9100. } else if (preg_match('/^--SUB\d+--$/', $parts[$i])) {
  9101. $parts[$i] = $subs[$parts[$i]];
  9102. } else {
  9103. return false;
  9104. }
  9105. }
  9106. // Combine keys and values.
  9107. for ($i = 0; $i < $size * 2; $i += 2) {
  9108. $value[$parts[$i]] = $parts[$i+1];
  9109. }
  9110. return $value;
  9111. }
  9112. /**
  9113. * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
  9114. *
  9115. * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
  9116. * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
  9117. * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
  9118. *
  9119. * @param string $input
  9120. * @return stdClass
  9121. */
  9122. function unserialize_object(string $input): stdClass {
  9123. $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
  9124. return (object) $instance;
  9125. }
  9126. /**
  9127. * The lang_string class
  9128. *
  9129. * This special class is used to create an object representation of a string request.
  9130. * It is special because processing doesn't occur until the object is first used.
  9131. * The class was created especially to aid performance in areas where strings were
  9132. * required to be generated but were not necessarily used.
  9133. * As an example the admin tree when generated uses over 1500 strings, of which
  9134. * normally only 1/3 are ever actually printed at any time.
  9135. * The performance advantage is achieved by not actually processing strings that
  9136. * arn't being used, as such reducing the processing required for the page.
  9137. *
  9138. * How to use the lang_string class?
  9139. * There are two methods of using the lang_string class, first through the
  9140. * forth argument of the get_string function, and secondly directly.
  9141. * The following are examples of both.
  9142. * 1. Through get_string calls e.g.
  9143. * $string = get_string($identifier, $component, $a, true);
  9144. * $string = get_string('yes', 'moodle', null, true);
  9145. * 2. Direct instantiation
  9146. * $string = new lang_string($identifier, $component, $a, $lang);
  9147. * $string = new lang_string('yes');
  9148. *
  9149. * How do I use a lang_string object?
  9150. * The lang_string object makes use of a magic __toString method so that you
  9151. * are able to use the object exactly as you would use a string in most cases.
  9152. * This means you are able to collect it into a variable and then directly
  9153. * echo it, or concatenate it into another string, or similar.
  9154. * The other thing you can do is manually get the string by calling the
  9155. * lang_strings out method e.g.
  9156. * $string = new lang_string('yes');
  9157. * $string->out();
  9158. * Also worth noting is that the out method can take one argument, $lang which
  9159. * allows the developer to change the language on the fly.
  9160. *
  9161. * When should I use a lang_string object?
  9162. * The lang_string object is designed to be used in any situation where a
  9163. * string may not be needed, but needs to be generated.
  9164. * The admin tree is a good example of where lang_string objects should be
  9165. * used.
  9166. * A more practical example would be any class that requries strings that may
  9167. * not be printed (after all classes get renderer by renderers and who knows
  9168. * what they will do ;))
  9169. *
  9170. * When should I not use a lang_string object?
  9171. * Don't use lang_strings when you are going to use a string immediately.
  9172. * There is no need as it will be processed immediately and there will be no
  9173. * advantage, and in fact perhaps a negative hit as a class has to be
  9174. * instantiated for a lang_string object, however get_string won't require
  9175. * that.
  9176. *
  9177. * Limitations:
  9178. * 1. You cannot use a lang_string object as an array offset. Doing so will
  9179. * result in PHP throwing an error. (You can use it as an object property!)
  9180. *
  9181. * @package core
  9182. * @category string
  9183. * @copyright 2011 Sam Hemelryk
  9184. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  9185. */
  9186. class lang_string {
  9187. /** @var string The strings identifier */
  9188. protected $identifier;
  9189. /** @var string The strings component. Default '' */
  9190. protected $component = '';
  9191. /** @var array|stdClass Any arguments required for the string. Default null */
  9192. protected $a = null;
  9193. /** @var string The language to use when processing the string. Default null */
  9194. protected $lang = null;
  9195. /** @var string The processed string (once processed) */
  9196. protected $string = null;
  9197. /**
  9198. * A special boolean. If set to true then the object has been woken up and
  9199. * cannot be regenerated. If this is set then $this->string MUST be used.
  9200. * @var bool
  9201. */
  9202. protected $forcedstring = false;
  9203. /**
  9204. * Constructs a lang_string object
  9205. *
  9206. * This function should do as little processing as possible to ensure the best
  9207. * performance for strings that won't be used.
  9208. *
  9209. * @param string $identifier The strings identifier
  9210. * @param string $component The strings component
  9211. * @param stdClass|array $a Any arguments the string requires
  9212. * @param string $lang The language to use when processing the string.
  9213. * @throws coding_exception
  9214. */
  9215. public function __construct($identifier, $component = '', $a = null, $lang = null) {
  9216. if (empty($component)) {
  9217. $component = 'moodle';
  9218. }
  9219. $this->identifier = $identifier;
  9220. $this->component = $component;
  9221. $this->lang = $lang;
  9222. // We MUST duplicate $a to ensure that it if it changes by reference those
  9223. // changes are not carried across.
  9224. // To do this we always ensure $a or its properties/values are strings
  9225. // and that any properties/values that arn't convertable are forgotten.
  9226. if ($a !== null) {
  9227. if (is_scalar($a)) {
  9228. $this->a = $a;
  9229. } else if ($a instanceof lang_string) {
  9230. $this->a = $a->out();
  9231. } else if (is_object($a) or is_array($a)) {
  9232. $a = (array)$a;
  9233. $this->a = array();
  9234. foreach ($a as $key => $value) {
  9235. // Make sure conversion errors don't get displayed (results in '').
  9236. if (is_array($value)) {
  9237. $this->a[$key] = '';
  9238. } else if (is_object($value)) {
  9239. if (method_exists($value, '__toString')) {
  9240. $this->a[$key] = $value->__toString();
  9241. } else {
  9242. $this->a[$key] = '';
  9243. }
  9244. } else {
  9245. $this->a[$key] = (string)$value;
  9246. }
  9247. }
  9248. }
  9249. }
  9250. if (debugging(false, DEBUG_DEVELOPER)) {
  9251. if (clean_param($this->identifier, PARAM_STRINGID) == '') {
  9252. throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
  9253. }
  9254. if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
  9255. throw new coding_exception('Invalid string compontent. Please check your string definition');
  9256. }
  9257. if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
  9258. debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
  9259. }
  9260. }
  9261. }
  9262. /**
  9263. * Processes the string.
  9264. *
  9265. * This function actually processes the string, stores it in the string property
  9266. * and then returns it.
  9267. * You will notice that this function is VERY similar to the get_string method.
  9268. * That is because it is pretty much doing the same thing.
  9269. * However as this function is an upgrade it isn't as tolerant to backwards
  9270. * compatibility.
  9271. *
  9272. * @return string
  9273. * @throws coding_exception
  9274. */
  9275. protected function get_string() {
  9276. global $CFG;
  9277. // Check if we need to process the string.
  9278. if ($this->string === null) {
  9279. // Check the quality of the identifier.
  9280. if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
  9281. throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition', DEBUG_DEVELOPER);
  9282. }
  9283. // Process the string.
  9284. $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
  9285. // Debugging feature lets you display string identifier and component.
  9286. if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
  9287. $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
  9288. }
  9289. }
  9290. // Return the string.
  9291. return $this->string;
  9292. }
  9293. /**
  9294. * Returns the string
  9295. *
  9296. * @param string $lang The langauge to use when processing the string
  9297. * @return string
  9298. */
  9299. public function out($lang = null) {
  9300. if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
  9301. if ($this->forcedstring) {
  9302. debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
  9303. return $this->get_string();
  9304. }
  9305. $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
  9306. return $translatedstring->out();
  9307. }
  9308. return $this->get_string();
  9309. }
  9310. /**
  9311. * Magic __toString method for printing a string
  9312. *
  9313. * @return string
  9314. */
  9315. public function __toString() {
  9316. return $this->get_string();
  9317. }
  9318. /**
  9319. * Magic __set_state method used for var_export
  9320. *
  9321. * @param array $array
  9322. * @return self
  9323. */
  9324. public static function __set_state(array $array): self {
  9325. $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
  9326. $tmp->string = $array['string'];
  9327. $tmp->forcedstring = $array['forcedstring'];
  9328. return $tmp;
  9329. }
  9330. /**
  9331. * Prepares the lang_string for sleep and stores only the forcedstring and
  9332. * string properties... the string cannot be regenerated so we need to ensure
  9333. * it is generated for this.
  9334. *
  9335. * @return string
  9336. */
  9337. public function __sleep() {
  9338. $this->get_string();
  9339. $this->forcedstring = true;
  9340. return array('forcedstring', 'string', 'lang');
  9341. }
  9342. /**
  9343. * Returns the identifier.
  9344. *
  9345. * @return string
  9346. */
  9347. public function get_identifier() {
  9348. return $this->identifier;
  9349. }
  9350. /**
  9351. * Returns the component.
  9352. *
  9353. * @return string
  9354. */
  9355. public function get_component() {
  9356. return $this->component;
  9357. }
  9358. }
  9359. /**
  9360. * Get human readable name describing the given callable.
  9361. *
  9362. * This performs syntax check only to see if the given param looks like a valid function, method or closure.
  9363. * It does not check if the callable actually exists.
  9364. *
  9365. * @param callable|string|array $callable
  9366. * @return string|bool Human readable name of callable, or false if not a valid callable.
  9367. */
  9368. function get_callable_name($callable) {
  9369. if (!is_callable($callable, true, $name)) {
  9370. return false;
  9371. } else {
  9372. return $name;
  9373. }
  9374. }
  9375. /**
  9376. * Tries to guess if $CFG->wwwroot is publicly accessible or not.
  9377. * Never put your faith on this function and rely on its accuracy as there might be false positives.
  9378. * It just performs some simple checks, and mainly is used for places where we want to hide some options
  9379. * such as site registration when $CFG->wwwroot is not publicly accessible.
  9380. * Good thing is there is no false negative.
  9381. * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
  9382. *
  9383. * @return bool
  9384. */
  9385. function site_is_public() {
  9386. global $CFG;
  9387. // Return early if site admin has forced this setting.
  9388. if (isset($CFG->site_is_public)) {
  9389. return (bool)$CFG->site_is_public;
  9390. }
  9391. $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
  9392. if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
  9393. $ispublic = false;
  9394. } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
  9395. $ispublic = false;
  9396. } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
  9397. $ispublic = false;
  9398. } else {
  9399. $ispublic = true;
  9400. }
  9401. return $ispublic;
  9402. }