PageRenderTime 52ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 2ms

/lib/moodlelib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 9736 lines | 5500 code | 1191 blank | 3045 comment | 1334 complexity | 857d5a9c71af7fb935f408b6c4dc9501 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-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 plus the chars in quotes: "_-" allowed
  68. * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
  69. */
  70. define('PARAM_ALPHAEXT', 'alphaext');
  71. /**
  72. * PARAM_ALPHANUM - expected numbers and letters only.
  73. */
  74. define('PARAM_ALPHANUM', 'alphanum');
  75. /**
  76. * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
  77. */
  78. define('PARAM_ALPHANUMEXT', 'alphanumext');
  79. /**
  80. * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
  81. */
  82. define('PARAM_AUTH', 'auth');
  83. /**
  84. * PARAM_BASE64 - Base 64 encoded format
  85. */
  86. define('PARAM_BASE64', 'base64');
  87. /**
  88. * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
  89. */
  90. define('PARAM_BOOL', 'bool');
  91. /**
  92. * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
  93. * checked against the list of capabilities in the database.
  94. */
  95. define('PARAM_CAPABILITY', 'capability');
  96. /**
  97. * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
  98. * to use this. The normal mode of operation is to use PARAM_RAW when recieving
  99. * the input (required/optional_param or formslib) and then sanitse 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. * Instead, do something like
  118. * $rawvalue = required_param('name', PARAM_RAW);
  119. * // ... other code including require_login, which sets current lang ...
  120. * $realvalue = unformat_float($rawvalue);
  121. * // ... then use $realvalue
  122. */
  123. define('PARAM_FLOAT', 'float');
  124. /**
  125. * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
  126. */
  127. define('PARAM_HOST', 'host');
  128. /**
  129. * PARAM_INT - integers only, use when expecting only numbers.
  130. */
  131. define('PARAM_INT', 'int');
  132. /**
  133. * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
  134. */
  135. define('PARAM_LANG', 'lang');
  136. /**
  137. * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
  138. * others! Implies PARAM_URL!)
  139. */
  140. define('PARAM_LOCALURL', 'localurl');
  141. /**
  142. * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
  143. */
  144. define('PARAM_NOTAGS', 'notags');
  145. /**
  146. * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
  147. * traversals note: the leading slash is not removed, window drive letter is not allowed
  148. */
  149. define('PARAM_PATH', 'path');
  150. /**
  151. * PARAM_PEM - Privacy Enhanced Mail format
  152. */
  153. define('PARAM_PEM', 'pem');
  154. /**
  155. * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
  156. */
  157. define('PARAM_PERMISSION', 'permission');
  158. /**
  159. * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
  160. */
  161. define('PARAM_RAW', 'raw');
  162. /**
  163. * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
  164. */
  165. define('PARAM_RAW_TRIMMED', 'raw_trimmed');
  166. /**
  167. * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
  168. */
  169. define('PARAM_SAFEDIR', 'safedir');
  170. /**
  171. * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
  172. */
  173. define('PARAM_SAFEPATH', 'safepath');
  174. /**
  175. * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
  176. */
  177. define('PARAM_SEQUENCE', 'sequence');
  178. /**
  179. * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
  180. */
  181. define('PARAM_TAG', 'tag');
  182. /**
  183. * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
  184. */
  185. define('PARAM_TAGLIST', 'taglist');
  186. /**
  187. * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
  188. */
  189. define('PARAM_TEXT', 'text');
  190. /**
  191. * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
  192. */
  193. define('PARAM_THEME', 'theme');
  194. /**
  195. * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
  196. * http://localhost.localdomain/ is ok.
  197. */
  198. define('PARAM_URL', 'url');
  199. /**
  200. * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
  201. * accounts, do NOT use when syncing with external systems!!
  202. */
  203. define('PARAM_USERNAME', 'username');
  204. /**
  205. * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
  206. */
  207. define('PARAM_STRINGID', 'stringid');
  208. // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
  209. /**
  210. * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
  211. * It was one of the first types, that is why it is abused so much ;-)
  212. * @deprecated since 2.0
  213. */
  214. define('PARAM_CLEAN', 'clean');
  215. /**
  216. * PARAM_INTEGER - deprecated alias for PARAM_INT
  217. * @deprecated since 2.0
  218. */
  219. define('PARAM_INTEGER', 'int');
  220. /**
  221. * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
  222. * @deprecated since 2.0
  223. */
  224. define('PARAM_NUMBER', 'float');
  225. /**
  226. * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
  227. * NOTE: originally alias for PARAM_APLHA
  228. * @deprecated since 2.0
  229. */
  230. define('PARAM_ACTION', 'alphanumext');
  231. /**
  232. * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
  233. * NOTE: originally alias for PARAM_APLHA
  234. * @deprecated since 2.0
  235. */
  236. define('PARAM_FORMAT', 'alphanumext');
  237. /**
  238. * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
  239. * @deprecated since 2.0
  240. */
  241. define('PARAM_MULTILANG', 'text');
  242. /**
  243. * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
  244. * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
  245. * America/Port-au-Prince)
  246. */
  247. define('PARAM_TIMEZONE', 'timezone');
  248. /**
  249. * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
  250. */
  251. define('PARAM_CLEANFILE', 'file');
  252. /**
  253. * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
  254. * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
  255. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  256. * NOTE: numbers and underscores are strongly discouraged in plugin names!
  257. */
  258. define('PARAM_COMPONENT', 'component');
  259. /**
  260. * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
  261. * It is usually used together with context id and component.
  262. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  263. */
  264. define('PARAM_AREA', 'area');
  265. /**
  266. * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
  267. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  268. * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
  269. */
  270. define('PARAM_PLUGIN', 'plugin');
  271. // Web Services.
  272. /**
  273. * VALUE_REQUIRED - if the parameter is not supplied, there is an error
  274. */
  275. define('VALUE_REQUIRED', 1);
  276. /**
  277. * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
  278. */
  279. define('VALUE_OPTIONAL', 2);
  280. /**
  281. * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
  282. */
  283. define('VALUE_DEFAULT', 0);
  284. /**
  285. * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
  286. */
  287. define('NULL_NOT_ALLOWED', false);
  288. /**
  289. * NULL_ALLOWED - the parameter can be set to null in the database
  290. */
  291. define('NULL_ALLOWED', true);
  292. // Page types.
  293. /**
  294. * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
  295. */
  296. define('PAGE_COURSE_VIEW', 'course-view');
  297. /** Get remote addr constant */
  298. define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
  299. /** Get remote addr constant */
  300. define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
  301. // Blog access level constant declaration.
  302. define ('BLOG_USER_LEVEL', 1);
  303. define ('BLOG_GROUP_LEVEL', 2);
  304. define ('BLOG_COURSE_LEVEL', 3);
  305. define ('BLOG_SITE_LEVEL', 4);
  306. define ('BLOG_GLOBAL_LEVEL', 5);
  307. // Tag constants.
  308. /**
  309. * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
  310. * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
  311. * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
  312. *
  313. * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
  314. */
  315. define('TAG_MAX_LENGTH', 50);
  316. // Password policy constants.
  317. define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
  318. define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  319. define ('PASSWORD_DIGITS', '0123456789');
  320. define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
  321. // Feature constants.
  322. // Used for plugin_supports() to report features that are, or are not, supported by a module.
  323. /** True if module can provide a grade */
  324. define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
  325. /** True if module supports outcomes */
  326. define('FEATURE_GRADE_OUTCOMES', 'outcomes');
  327. /** True if module supports advanced grading methods */
  328. define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
  329. /** True if module controls the grade visibility over the gradebook */
  330. define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
  331. /** True if module supports plagiarism plugins */
  332. define('FEATURE_PLAGIARISM', 'plagiarism');
  333. /** True if module has code to track whether somebody viewed it */
  334. define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
  335. /** True if module has custom completion rules */
  336. define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
  337. /** True if module has no 'view' page (like label) */
  338. define('FEATURE_NO_VIEW_LINK', 'viewlink');
  339. /** True if module supports outcomes */
  340. define('FEATURE_IDNUMBER', 'idnumber');
  341. /** True if module supports groups */
  342. define('FEATURE_GROUPS', 'groups');
  343. /** True if module supports groupings */
  344. define('FEATURE_GROUPINGS', 'groupings');
  345. /** True if module supports groupmembersonly */
  346. define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
  347. /** Type of module */
  348. define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
  349. /** True if module supports intro editor */
  350. define('FEATURE_MOD_INTRO', 'mod_intro');
  351. /** True if module has default completion */
  352. define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
  353. define('FEATURE_COMMENT', 'comment');
  354. define('FEATURE_RATE', 'rate');
  355. /** True if module supports backup/restore of moodle2 format */
  356. define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
  357. /** True if module can show description on course main page */
  358. define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
  359. /** True if module uses the question bank */
  360. define('FEATURE_USES_QUESTIONS', 'usesquestions');
  361. /** Unspecified module archetype */
  362. define('MOD_ARCHETYPE_OTHER', 0);
  363. /** Resource-like type module */
  364. define('MOD_ARCHETYPE_RESOURCE', 1);
  365. /** Assignment module archetype */
  366. define('MOD_ARCHETYPE_ASSIGNMENT', 2);
  367. /** System (not user-addable) module archetype */
  368. define('MOD_ARCHETYPE_SYSTEM', 3);
  369. /** Return this from modname_get_types callback to use default display in activity chooser */
  370. define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
  371. /**
  372. * Security token used for allowing access
  373. * from external application such as web services.
  374. * Scripts do not use any session, performance is relatively
  375. * low because we need to load access info in each request.
  376. * Scripts are executed in parallel.
  377. */
  378. define('EXTERNAL_TOKEN_PERMANENT', 0);
  379. /**
  380. * Security token used for allowing access
  381. * of embedded applications, the code is executed in the
  382. * active user session. Token is invalidated after user logs out.
  383. * Scripts are executed serially - normal session locking is used.
  384. */
  385. define('EXTERNAL_TOKEN_EMBEDDED', 1);
  386. /**
  387. * The home page should be the site home
  388. */
  389. define('HOMEPAGE_SITE', 0);
  390. /**
  391. * The home page should be the users my page
  392. */
  393. define('HOMEPAGE_MY', 1);
  394. /**
  395. * The home page can be chosen by the user
  396. */
  397. define('HOMEPAGE_USER', 2);
  398. /**
  399. * Hub directory url (should be moodle.org)
  400. */
  401. define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
  402. /**
  403. * Moodle.org url (should be moodle.org)
  404. */
  405. define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
  406. /**
  407. * Moodle mobile app service name
  408. */
  409. define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
  410. /**
  411. * Indicates the user has the capabilities required to ignore activity and course file size restrictions
  412. */
  413. define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
  414. /**
  415. * Course display settings: display all sections on one page.
  416. */
  417. define('COURSE_DISPLAY_SINGLEPAGE', 0);
  418. /**
  419. * Course display settings: split pages into a page per section.
  420. */
  421. define('COURSE_DISPLAY_MULTIPAGE', 1);
  422. /**
  423. * Authentication constant: String used in password field when password is not stored.
  424. */
  425. define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
  426. // PARAMETER HANDLING.
  427. /**
  428. * Returns a particular value for the named variable, taken from
  429. * POST or GET. If the parameter doesn't exist then an error is
  430. * thrown because we require this variable.
  431. *
  432. * This function should be used to initialise all required values
  433. * in a script that are based on parameters. Usually it will be
  434. * used like this:
  435. * $id = required_param('id', PARAM_INT);
  436. *
  437. * Please note the $type parameter is now required and the value can not be array.
  438. *
  439. * @param string $parname the name of the page parameter we want
  440. * @param string $type expected type of parameter
  441. * @return mixed
  442. * @throws coding_exception
  443. */
  444. function required_param($parname, $type) {
  445. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  446. throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
  447. }
  448. // POST has precedence.
  449. if (isset($_POST[$parname])) {
  450. $param = $_POST[$parname];
  451. } else if (isset($_GET[$parname])) {
  452. $param = $_GET[$parname];
  453. } else {
  454. print_error('missingparam', '', '', $parname);
  455. }
  456. if (is_array($param)) {
  457. debugging('Invalid array parameter detected in required_param(): '.$parname);
  458. // TODO: switch to fatal error in Moodle 2.3.
  459. return required_param_array($parname, $type);
  460. }
  461. return clean_param($param, $type);
  462. }
  463. /**
  464. * Returns a particular array value for the named variable, taken from
  465. * POST or GET. If the parameter doesn't exist then an error is
  466. * thrown because we require this variable.
  467. *
  468. * This function should be used to initialise all required values
  469. * in a script that are based on parameters. Usually it will be
  470. * used like this:
  471. * $ids = required_param_array('ids', PARAM_INT);
  472. *
  473. * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
  474. *
  475. * @param string $parname the name of the page parameter we want
  476. * @param string $type expected type of parameter
  477. * @return array
  478. * @throws coding_exception
  479. */
  480. function required_param_array($parname, $type) {
  481. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  482. throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
  483. }
  484. // POST has precedence.
  485. if (isset($_POST[$parname])) {
  486. $param = $_POST[$parname];
  487. } else if (isset($_GET[$parname])) {
  488. $param = $_GET[$parname];
  489. } else {
  490. print_error('missingparam', '', '', $parname);
  491. }
  492. if (!is_array($param)) {
  493. print_error('missingparam', '', '', $parname);
  494. }
  495. $result = array();
  496. foreach ($param as $key => $value) {
  497. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  498. debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
  499. continue;
  500. }
  501. $result[$key] = clean_param($value, $type);
  502. }
  503. return $result;
  504. }
  505. /**
  506. * Returns a particular value for the named variable, taken from
  507. * POST or GET, otherwise returning a given default.
  508. *
  509. * This function should be used to initialise all optional values
  510. * in a script that are based on parameters. Usually it will be
  511. * used like this:
  512. * $name = optional_param('name', 'Fred', PARAM_TEXT);
  513. *
  514. * Please note the $type parameter is now required and the value can not be array.
  515. *
  516. * @param string $parname the name of the page parameter we want
  517. * @param mixed $default the default value to return if nothing is found
  518. * @param string $type expected type of parameter
  519. * @return mixed
  520. * @throws coding_exception
  521. */
  522. function optional_param($parname, $default, $type) {
  523. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  524. throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
  525. }
  526. if (!isset($default)) {
  527. $default = null;
  528. }
  529. // POST has precedence.
  530. if (isset($_POST[$parname])) {
  531. $param = $_POST[$parname];
  532. } else if (isset($_GET[$parname])) {
  533. $param = $_GET[$parname];
  534. } else {
  535. return $default;
  536. }
  537. if (is_array($param)) {
  538. debugging('Invalid array parameter detected in required_param(): '.$parname);
  539. // TODO: switch to $default in Moodle 2.3.
  540. return optional_param_array($parname, $default, $type);
  541. }
  542. return clean_param($param, $type);
  543. }
  544. /**
  545. * Returns a particular array value for the named variable, taken from
  546. * POST or GET, otherwise returning a given default.
  547. *
  548. * This function should be used to initialise all optional values
  549. * in a script that are based on parameters. Usually it will be
  550. * used like this:
  551. * $ids = optional_param('id', array(), PARAM_INT);
  552. *
  553. * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
  554. *
  555. * @param string $parname the name of the page parameter we want
  556. * @param mixed $default the default value to return if nothing is found
  557. * @param string $type expected type of parameter
  558. * @return array
  559. * @throws coding_exception
  560. */
  561. function optional_param_array($parname, $default, $type) {
  562. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  563. throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
  564. }
  565. // POST has precedence.
  566. if (isset($_POST[$parname])) {
  567. $param = $_POST[$parname];
  568. } else if (isset($_GET[$parname])) {
  569. $param = $_GET[$parname];
  570. } else {
  571. return $default;
  572. }
  573. if (!is_array($param)) {
  574. debugging('optional_param_array() expects array parameters only: '.$parname);
  575. return $default;
  576. }
  577. $result = array();
  578. foreach ($param as $key => $value) {
  579. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  580. debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
  581. continue;
  582. }
  583. $result[$key] = clean_param($value, $type);
  584. }
  585. return $result;
  586. }
  587. /**
  588. * Strict validation of parameter values, the values are only converted
  589. * to requested PHP type. Internally it is using clean_param, the values
  590. * before and after cleaning must be equal - otherwise
  591. * an invalid_parameter_exception is thrown.
  592. * Objects and classes are not accepted.
  593. *
  594. * @param mixed $param
  595. * @param string $type PARAM_ constant
  596. * @param bool $allownull are nulls valid value?
  597. * @param string $debuginfo optional debug information
  598. * @return mixed the $param value converted to PHP type
  599. * @throws invalid_parameter_exception if $param is not of given type
  600. */
  601. function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
  602. if (is_null($param)) {
  603. if ($allownull == NULL_ALLOWED) {
  604. return null;
  605. } else {
  606. throw new invalid_parameter_exception($debuginfo);
  607. }
  608. }
  609. if (is_array($param) or is_object($param)) {
  610. throw new invalid_parameter_exception($debuginfo);
  611. }
  612. $cleaned = clean_param($param, $type);
  613. if ($type == PARAM_FLOAT) {
  614. // Do not detect precision loss here.
  615. if (is_float($param) or is_int($param)) {
  616. // These always fit.
  617. } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
  618. throw new invalid_parameter_exception($debuginfo);
  619. }
  620. } else if ((string)$param !== (string)$cleaned) {
  621. // Conversion to string is usually lossless.
  622. throw new invalid_parameter_exception($debuginfo);
  623. }
  624. return $cleaned;
  625. }
  626. /**
  627. * Makes sure array contains only the allowed types, this function does not validate array key names!
  628. *
  629. * <code>
  630. * $options = clean_param($options, PARAM_INT);
  631. * </code>
  632. *
  633. * @param array $param the variable array we are cleaning
  634. * @param string $type expected format of param after cleaning.
  635. * @param bool $recursive clean recursive arrays
  636. * @return array
  637. * @throws coding_exception
  638. */
  639. function clean_param_array(array $param = null, $type, $recursive = false) {
  640. // Convert null to empty array.
  641. $param = (array)$param;
  642. foreach ($param as $key => $value) {
  643. if (is_array($value)) {
  644. if ($recursive) {
  645. $param[$key] = clean_param_array($value, $type, true);
  646. } else {
  647. throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
  648. }
  649. } else {
  650. $param[$key] = clean_param($value, $type);
  651. }
  652. }
  653. return $param;
  654. }
  655. /**
  656. * Used by {@link optional_param()} and {@link required_param()} to
  657. * clean the variables and/or cast to specific types, based on
  658. * an options field.
  659. * <code>
  660. * $course->format = clean_param($course->format, PARAM_ALPHA);
  661. * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
  662. * </code>
  663. *
  664. * @param mixed $param the variable we are cleaning
  665. * @param string $type expected format of param after cleaning.
  666. * @return mixed
  667. * @throws coding_exception
  668. */
  669. function clean_param($param, $type) {
  670. global $CFG;
  671. if (is_array($param)) {
  672. throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
  673. } else if (is_object($param)) {
  674. if (method_exists($param, '__toString')) {
  675. $param = $param->__toString();
  676. } else {
  677. throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
  678. }
  679. }
  680. switch ($type) {
  681. case PARAM_RAW:
  682. // No cleaning at all.
  683. $param = fix_utf8($param);
  684. return $param;
  685. case PARAM_RAW_TRIMMED:
  686. // No cleaning, but strip leading and trailing whitespace.
  687. $param = fix_utf8($param);
  688. return trim($param);
  689. case PARAM_CLEAN:
  690. // General HTML cleaning, try to use more specific type if possible this is deprecated!
  691. // Please use more specific type instead.
  692. if (is_numeric($param)) {
  693. return $param;
  694. }
  695. $param = fix_utf8($param);
  696. // Sweep for scripts, etc.
  697. return clean_text($param);
  698. case PARAM_CLEANHTML:
  699. // Clean html fragment.
  700. $param = fix_utf8($param);
  701. // Sweep for scripts, etc.
  702. $param = clean_text($param, FORMAT_HTML);
  703. return trim($param);
  704. case PARAM_INT:
  705. // Convert to integer.
  706. return (int)$param;
  707. case PARAM_FLOAT:
  708. // Convert to float.
  709. return (float)$param;
  710. case PARAM_ALPHA:
  711. // Remove everything not `a-z`.
  712. return preg_replace('/[^a-zA-Z]/i', '', $param);
  713. case PARAM_ALPHAEXT:
  714. // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
  715. return preg_replace('/[^a-zA-Z_-]/i', '', $param);
  716. case PARAM_ALPHANUM:
  717. // Remove everything not `a-zA-Z0-9`.
  718. return preg_replace('/[^A-Za-z0-9]/i', '', $param);
  719. case PARAM_ALPHANUMEXT:
  720. // Remove everything not `a-zA-Z0-9_-`.
  721. return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
  722. case PARAM_SEQUENCE:
  723. // Remove everything not `0-9,`.
  724. return preg_replace('/[^0-9,]/i', '', $param);
  725. case PARAM_BOOL:
  726. // Convert to 1 or 0.
  727. $tempstr = strtolower($param);
  728. if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
  729. $param = 1;
  730. } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
  731. $param = 0;
  732. } else {
  733. $param = empty($param) ? 0 : 1;
  734. }
  735. return $param;
  736. case PARAM_NOTAGS:
  737. // Strip all tags.
  738. $param = fix_utf8($param);
  739. return strip_tags($param);
  740. case PARAM_TEXT:
  741. // Leave only tags needed for multilang.
  742. $param = fix_utf8($param);
  743. // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
  744. // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
  745. do {
  746. if (strpos($param, '</lang>') !== false) {
  747. // Old and future mutilang syntax.
  748. $param = strip_tags($param, '<lang>');
  749. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  750. break;
  751. }
  752. $open = false;
  753. foreach ($matches[0] as $match) {
  754. if ($match === '</lang>') {
  755. if ($open) {
  756. $open = false;
  757. continue;
  758. } else {
  759. break 2;
  760. }
  761. }
  762. if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
  763. break 2;
  764. } else {
  765. $open = true;
  766. }
  767. }
  768. if ($open) {
  769. break;
  770. }
  771. return $param;
  772. } else if (strpos($param, '</span>') !== false) {
  773. // Current problematic multilang syntax.
  774. $param = strip_tags($param, '<span>');
  775. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  776. break;
  777. }
  778. $open = false;
  779. foreach ($matches[0] as $match) {
  780. if ($match === '</span>') {
  781. if ($open) {
  782. $open = false;
  783. continue;
  784. } else {
  785. break 2;
  786. }
  787. }
  788. if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
  789. break 2;
  790. } else {
  791. $open = true;
  792. }
  793. }
  794. if ($open) {
  795. break;
  796. }
  797. return $param;
  798. }
  799. } while (false);
  800. // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
  801. return strip_tags($param);
  802. case PARAM_COMPONENT:
  803. // We do not want any guessing here, either the name is correct or not
  804. // please note only normalised component names are accepted.
  805. if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
  806. return '';
  807. }
  808. if (strpos($param, '__') !== false) {
  809. return '';
  810. }
  811. if (strpos($param, 'mod_') === 0) {
  812. // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
  813. if (substr_count($param, '_') != 1) {
  814. return '';
  815. }
  816. }
  817. return $param;
  818. case PARAM_PLUGIN:
  819. case PARAM_AREA:
  820. // We do not want any guessing here, either the name is correct or not.
  821. if (!is_valid_plugin_name($param)) {
  822. return '';
  823. }
  824. return $param;
  825. case PARAM_SAFEDIR:
  826. // Remove everything not a-zA-Z0-9_- .
  827. return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
  828. case PARAM_SAFEPATH:
  829. // Remove everything not a-zA-Z0-9/_- .
  830. return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
  831. case PARAM_FILE:
  832. // Strip all suspicious characters from filename.
  833. $param = fix_utf8($param);
  834. $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
  835. if ($param === '.' || $param === '..') {
  836. $param = '';
  837. }
  838. return $param;
  839. case PARAM_PATH:
  840. // Strip all suspicious characters from file path.
  841. $param = fix_utf8($param);
  842. $param = str_replace('\\', '/', $param);
  843. // Explode the path and clean each element using the PARAM_FILE rules.
  844. $breadcrumb = explode('/', $param);
  845. foreach ($breadcrumb as $key => $crumb) {
  846. if ($crumb === '.' && $key === 0) {
  847. // Special condition to allow for relative current path such as ./currentdirfile.txt.
  848. } else {
  849. $crumb = clean_param($crumb, PARAM_FILE);
  850. }
  851. $breadcrumb[$key] = $crumb;
  852. }
  853. $param = implode('/', $breadcrumb);
  854. // Remove multiple current path (./././) and multiple slashes (///).
  855. $param = preg_replace('~//+~', '/', $param);
  856. $param = preg_replace('~/(\./)+~', '/', $param);
  857. return $param;
  858. case PARAM_HOST:
  859. // Allow FQDN or IPv4 dotted quad.
  860. $param = preg_replace('/[^\.\d\w-]/', '', $param );
  861. // Match ipv4 dotted quad.
  862. if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
  863. // Confirm values are ok.
  864. if ( $match[0] > 255
  865. || $match[1] > 255
  866. || $match[3] > 255
  867. || $match[4] > 255 ) {
  868. // Hmmm, what kind of dotted quad is this?
  869. $param = '';
  870. }
  871. } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
  872. && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
  873. && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
  874. ) {
  875. // All is ok - $param is respected.
  876. } else {
  877. // All is not ok...
  878. $param='';
  879. }
  880. return $param;
  881. case PARAM_URL: // Allow safe ftp, http, mailto urls.
  882. $param = fix_utf8($param);
  883. include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
  884. if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
  885. // All is ok, param is respected.
  886. } else {
  887. // Not really ok.
  888. $param ='';
  889. }
  890. return $param;
  891. case PARAM_LOCALURL:
  892. // Allow http absolute, root relative and relative URLs within wwwroot.
  893. $param = clean_param($param, PARAM_URL);
  894. if (!empty($param)) {
  895. if (preg_match(':^/:', $param)) {
  896. // Root-relative, ok!
  897. } else if (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i', $param)) {
  898. // Absolute, and matches our wwwroot.
  899. } else {
  900. // Relative - let's make sure there are no tricks.
  901. if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
  902. // Looks ok.
  903. } else {
  904. $param = '';
  905. }
  906. }
  907. }
  908. return $param;
  909. case PARAM_PEM:
  910. $param = trim($param);
  911. // PEM formatted strings may contain letters/numbers and the symbols:
  912. // forward slash: /
  913. // plus sign: +
  914. // equal sign: =
  915. // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
  916. if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
  917. list($wholething, $body) = $matches;
  918. unset($wholething, $matches);
  919. $b64 = clean_param($body, PARAM_BASE64);
  920. if (!empty($b64)) {
  921. return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
  922. } else {
  923. return '';
  924. }
  925. }
  926. return '';
  927. case PARAM_BASE64:
  928. if (!empty($param)) {
  929. // PEM formatted strings may contain letters/numbers and the symbols
  930. // forward slash: /
  931. // plus sign: +
  932. // equal sign: =.
  933. if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
  934. return '';
  935. }
  936. $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
  937. // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
  938. // than (or equal to) 64 characters long.
  939. for ($i=0, $j=count($lines); $i < $j; $i++) {
  940. if ($i + 1 == $j) {
  941. if (64 < strlen($lines[$i])) {
  942. return '';
  943. }
  944. continue;
  945. }
  946. if (64 != strlen($lines[$i])) {
  947. return '';
  948. }
  949. }
  950. return implode("\n", $lines);
  951. } else {
  952. return '';
  953. }
  954. case PARAM_TAG:
  955. $param = fix_utf8($param);
  956. // Please note it is not safe to use the tag name directly anywhere,
  957. // it must be processed with s(), urlencode() before embedding anywhere.
  958. // Remove some nasties.
  959. $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
  960. // Convert many whitespace chars into one.
  961. $param = preg_replace('/\s+/', ' ', $param);
  962. $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
  963. return $param;
  964. case PARAM_TAGLIST:
  965. $param = fix_utf8($param);
  966. $tags = explode(',', $param);
  967. $result = array();
  968. foreach ($tags as $tag) {
  969. $res = clean_param($tag, PARAM_TAG);
  970. if ($res !== '') {
  971. $result[] = $res;
  972. }
  973. }
  974. if ($result) {
  975. return implode(',', $result);
  976. } else {
  977. return '';
  978. }
  979. case PARAM_CAPABILITY:
  980. if (get_capability_info($param)) {
  981. return $param;
  982. } else {
  983. return '';
  984. }
  985. case PARAM_PERMISSION:
  986. $param = (int)$param;
  987. if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
  988. return $param;
  989. } else {
  990. return CAP_INHERIT;
  991. }
  992. case PARAM_AUTH:
  993. $param = clean_param($param, PARAM_PLUGIN);
  994. if (empty($param)) {
  995. return '';
  996. } else if (exists_auth_plugin($param)) {
  997. return $param;
  998. } else {
  999. return '';
  1000. }
  1001. case PARAM_LANG:
  1002. $param = clean_param($param, PARAM_SAFEDIR);
  1003. if (get_string_manager()->translation_exists($param)) {
  1004. return $param;
  1005. } else {
  1006. // Specified language is not installed or param malformed.
  1007. return '';
  1008. }
  1009. case PARAM_THEME:
  1010. $param = clean_param($param, PARAM_PLUGIN);
  1011. if (empty($param)) {
  1012. return '';
  1013. } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
  1014. return $param;
  1015. } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
  1016. return $param;
  1017. } else {
  1018. // Specified theme is not installed.
  1019. return '';
  1020. }
  1021. case PARAM_USERNAME:
  1022. $param = fix_utf8($param);
  1023. $param = str_replace(" " , "", $param);
  1024. // Convert uppercase to lowercase MDL-16919.
  1025. $param = core_text::strtolower($param);
  1026. if (empty($CFG->extendedusernamechars)) {
  1027. // Regular expression, eliminate all chars EXCEPT:
  1028. // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
  1029. $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
  1030. }
  1031. return $param;
  1032. case PARAM_EMAIL:
  1033. $param = fix_utf8($param);
  1034. if (validate_email($param)) {
  1035. return $param;
  1036. } else {
  1037. return '';
  1038. }
  1039. case PARAM_STRINGID:
  1040. if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
  1041. return $param;
  1042. } else {
  1043. return '';
  1044. }
  1045. case PARAM_TIMEZONE:
  1046. // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
  1047. $param = fix_utf8($param);
  1048. $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
  1049. if (preg_match($timezonepattern, $param)) {
  1050. return $param;
  1051. } else {
  1052. return '';
  1053. }
  1054. default:
  1055. // Doh! throw error, switched parameters in optional_param or another serious problem.
  1056. print_error("unknownparamtype", '', '', $type);
  1057. }
  1058. }
  1059. /**
  1060. * Makes sure the data is using valid utf8, invalid characters are discarded.
  1061. *
  1062. * Note: this function is not intended for full objects with methods and private properties.
  1063. *
  1064. * @param mixed $value
  1065. * @return mixed with proper utf-8 encoding
  1066. */
  1067. function fix_utf8($value) {
  1068. if (is_null($value) or $value === '') {
  1069. return $value;
  1070. } else if (is_string($value)) {
  1071. if ((string)(int)$value === $value) {
  1072. // Shortcut.
  1073. return $value;
  1074. }
  1075. // No null bytes expected in our data, so let's remove it.
  1076. $value = str_replace("\0", '', $value);
  1077. // Note: this duplicates min_fix_utf8() intentionally.
  1078. static $buggyiconv = null;
  1079. if ($buggyiconv === null) {
  1080. $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
  1081. }
  1082. if ($buggyiconv) {
  1083. if (function_exists('mb_convert_encoding')) {
  1084. $subst = mb_substitute_character();
  1085. mb_substitute_character('');
  1086. $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
  1087. mb_substitute_character($subst);
  1088. } else {
  1089. // Warn admins on admin/index.php page.
  1090. $result = $value;
  1091. }
  1092. } else {
  1093. $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
  1094. }
  1095. return $result;
  1096. } else if (is_array($value)) {
  1097. foreach ($value as $k => $v) {
  1098. $value[$k] = fix_utf8($v);
  1099. }
  1100. return $value;
  1101. } else if (is_object($value)) {
  1102. // Do not modify original.
  1103. $value = clone($value);
  1104. foreach ($value as $k => $v) {
  1105. $value->$k = fix_utf8($v);
  1106. }
  1107. return $value;
  1108. } else {
  1109. // This is some other type, no utf-8 here.
  1110. return $value;
  1111. }
  1112. }
  1113. /**
  1114. * Return true if given value is integer or string with integer value
  1115. *
  1116. * @param mixed $value String or Int
  1117. * @return bool true if number, false if not
  1118. */
  1119. function is_number($value) {
  1120. if (is_int($value)) {
  1121. return true;
  1122. } else if (is_string($value)) {
  1123. return ((string)(int)$value) === $value;
  1124. } else {
  1125. return false;
  1126. }
  1127. }
  1128. /**
  1129. * Returns host part from url.
  1130. *
  1131. * @param string $url full url
  1132. * @return string host, null if not found
  1133. */
  1134. function get_host_from_url($url) {
  1135. preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
  1136. if ($matches) {
  1137. return $matches[1];
  1138. }
  1139. return null;
  1140. }
  1141. /**
  1142. * Tests whether anything was returned by text editor
  1143. *
  1144. * This function is useful for testing whether something you got back from
  1145. * the HTML editor actually contains anything. Sometimes the HTML editor
  1146. * appear to be empty, but actually you get back a <br> tag or something.
  1147. *
  1148. * @param string $string a string containing HTML.
  1149. * @return boolean does the string contain any actual content - that is text,
  1150. * images, objects, etc.
  1151. */
  1152. function html_is_blank($string) {
  1153. return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
  1154. }
  1155. /**
  1156. * Set a key in global configuration
  1157. *
  1158. * Set a key/value pair in both this session's {@link $CFG} global variable
  1159. * and in the 'config' database table for future sessions.
  1160. *
  1161. * Can also be used to update keys for plugin-scoped configs in config_plugin table.
  1162. * In that case it doesn't affect $CFG.
  1163. *
  1164. * A NULL value will delete the entry.
  1165. *
  1166. * NOTE: this function is called from lib/db/upgrade.php
  1167. *
  1168. * @param string $name the key to set
  1169. * @param string $value the value to set (without magic quotes)
  1170. * @param string $plugin (optional) the plugin scope, default null
  1171. * @return bool true or exception
  1172. */
  1173. function set_config($name, $value, $plugin=null) {
  1174. global $CFG, $DB;
  1175. if (empty($plugin)) {
  1176. if (!array_key_exists($name, $CFG->config_php_settings)) {
  1177. // So it's defined for this invocation at least.
  1178. if (is_null($value)) {
  1179. unset($CFG->$name);
  1180. } else {
  1181. // Settings from db are always strings.
  1182. $CFG->$name = (string)$value;
  1183. }
  1184. }
  1185. if ($DB->get_field('config', 'name', array('name' => $name))) {
  1186. if ($value === null) {
  1187. $DB->delete_records('config', array('name' => $name));
  1188. } else {
  1189. $DB->set_field('config', 'value', $value, array('name' => $name));
  1190. }
  1191. } else {
  1192. if ($value !== null) {
  1193. $config = new stdClass();
  1194. $config->name = $name;
  1195. $config->value = $value;
  1196. $DB->insert_record('config', $config, false);
  1197. }
  1198. }
  1199. if ($name === 'siteidentifier') {
  1200. cache_helper::update_site_identifier($value);
  1201. }
  1202. cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
  1203. } else {
  1204. // Plugin scope.
  1205. if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
  1206. if ($value===null) {
  1207. $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
  1208. } else {
  1209. $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
  1210. }
  1211. } else {
  1212. if ($value !== null) {
  1213. $config = new stdClass();
  1214. $config->plugin = $plugin;
  1215. $config->name = $name;
  1216. $config->value = $value;
  1217. $DB->insert_record('config_plugins', $config, false);
  1218. }
  1219. }
  1220. cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
  1221. }
  1222. return true;
  1223. }
  1224. /**
  1225. * Get configuration values from the global config table
  1226. * or the config_plugins table.
  1227. *
  1228. * If called with one parameter, it will load all the config
  1229. * variables for one plugin, and return them as an object.
  1230. *
  1231. * If called with 2 parameters it will return a string single
  1232. * value or false if the value is not found.
  1233. *
  1234. * NOTE: this function is called from lib/db/upgrade.php
  1235. *
  1236. * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
  1237. * that we need only fetch it once per request.
  1238. * @param string $plugin full component name
  1239. * @param string $name default null
  1240. * @return mixed hash-like object or single value, return false no config found
  1241. * @throws dml_exception
  1242. */
  1243. function get_config($plugin, $name = null) {
  1244. global $CFG, $DB;
  1245. static $siteidentifier = null;
  1246. if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
  1247. $forced =& $CFG->config_php_settings;
  1248. $iscore = true;
  1249. $plugin = 'core';
  1250. } else {
  1251. if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
  1252. $forced =& $CFG->forced_plugin_settings[$plugin];
  1253. } else {
  1254. $forced = array();
  1255. }
  1256. $iscore = false;
  1257. }
  1258. if ($siteidentifier === null) {
  1259. try {
  1260. // This may fail during installation.
  1261. // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
  1262. // install the database.
  1263. $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
  1264. } catch (dml_exception $ex) {
  1265. // Set siteidentifier to false. We don't want to trip this continually.
  1266. $siteidentifier = false;
  1267. throw $ex;
  1268. }
  1269. }
  1270. if (!empty($name)) {
  1271. if (array_key_exists($name, $forced)) {
  1272. return (string)$forced[$name];
  1273. } else if ($name === 'siteidentifier' && $plugin == 'core') {
  1274. return $siteidentifier;
  1275. }
  1276. }
  1277. $cache = cache::make('core', 'config');
  1278. $result = $cache->get($plugin);
  1279. if ($result === false) {
  1280. // The user is after a recordset.
  1281. if (!$iscore) {
  1282. $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
  1283. } else {
  1284. // This part is not really used any more, but anyway...
  1285. $result = $DB->get_records_menu('config', array(), '', 'name,value');;
  1286. }
  1287. $cache->set($plugin, $result);
  1288. }
  1289. if (!empty($name)) {
  1290. if (array_key_exists($name, $result)) {
  1291. return $result[$name];
  1292. }
  1293. return false;
  1294. }
  1295. if ($plugin === 'core') {
  1296. $result['siteidentifier'] = $siteidentifier;
  1297. }
  1298. foreach ($forced as $key => $value) {
  1299. if (is_null($value) or is_array($value) or is_object($value)) {
  1300. // We do not want any extra mess here, just real settings that could be saved in db.
  1301. unset($result[$key]);
  1302. } else {
  1303. // Convert to string as if it went through the DB.
  1304. $result[$key] = (string)$value;
  1305. }
  1306. }
  1307. return (object)$result;
  1308. }
  1309. /**
  1310. * Removes a key from global configuration.
  1311. *
  1312. * NOTE: this function is called from lib/db/upgrade.php
  1313. *
  1314. * @param string $name the key to set
  1315. * @param string $plugin (optional) the plugin scope
  1316. * @return boolean whether the operation succeeded.
  1317. */
  1318. function unset_config($name, $plugin=null) {
  1319. global $CFG, $DB;
  1320. if (empty($plugin)) {
  1321. unset($CFG->$name);
  1322. $DB->delete_records('config', array('name' => $name));
  1323. cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
  1324. } else {
  1325. $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
  1326. cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
  1327. }
  1328. return true;
  1329. }
  1330. /**
  1331. * Remove all the config variables for a given plugin.
  1332. *
  1333. * NOTE: this function is called from lib/db/upgrade.php
  1334. *
  1335. * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
  1336. * @return boolean whether the operation succeeded.
  1337. */
  1338. function unset_all_config_for_plugin($plugin) {
  1339. global $DB;
  1340. // Delete from the obvious config_plugins first.
  1341. $DB->delete_records('config_plugins', array('plugin' => $plugin));
  1342. // Next delete any suspect settings from config.
  1343. $like = $DB->sql_like('name', '?', true, true, false, '|');
  1344. $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
  1345. $DB->delete_records_select('config', $like, $params);
  1346. // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
  1347. cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
  1348. return true;
  1349. }
  1350. /**
  1351. * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
  1352. *
  1353. * All users are verified if they still have the necessary capability.
  1354. *
  1355. * @param string $value the value of the config setting.
  1356. * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
  1357. * @param bool $includeadmins include administrators.
  1358. * @return array of user objects.
  1359. */
  1360. function get_users_from_config($value, $capability, $includeadmins = true) {
  1361. if (empty($value) or $value === '$@NONE@$') {
  1362. return array();
  1363. }
  1364. // We have to make sure that users still have the necessary capability,
  1365. // it should be faster to fetch them all first and then test if they are present
  1366. // instead of validating them one-by-one.
  1367. $users = get_users_by_capability(context_system::instance(), $capability);
  1368. if ($includeadmins) {
  1369. $admins = get_admins();
  1370. foreach ($admins as $admin) {
  1371. $users[$admin->id] = $admin;
  1372. }
  1373. }
  1374. if ($value === '$@ALL@$') {
  1375. return $users;
  1376. }
  1377. $result = array(); // Result in correct order.
  1378. $allowed = explode(',', $value);
  1379. foreach ($allowed as $uid) {
  1380. if (isset($users[$uid])) {
  1381. $user = $users[$uid];
  1382. $result[$user->id] = $user;
  1383. }
  1384. }
  1385. return $result;
  1386. }
  1387. /**
  1388. * Invalidates browser caches and cached data in temp.
  1389. *
  1390. * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
  1391. * {@link phpunit_util::reset_dataroot()}
  1392. *
  1393. * @return void
  1394. */
  1395. function purge_all_caches() {
  1396. global $CFG, $DB;
  1397. reset_text_filters_cache();
  1398. js_reset_all_caches();
  1399. theme_reset_all_caches();
  1400. get_string_manager()->reset_caches();
  1401. core_text::reset_caches();
  1402. if (class_exists('core_plugin_manager')) {
  1403. core_plugin_manager::reset_caches();
  1404. }
  1405. // Bump up cacherev field for all courses.
  1406. try {
  1407. increment_revision_number('course', 'cacherev', '');
  1408. } catch (moodle_exception $e) {
  1409. // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
  1410. }
  1411. $DB->reset_caches();
  1412. cache_helper::purge_all();
  1413. // Purge all other caches: rss, simplepie, etc.
  1414. remove_dir($CFG->cachedir.'', true);
  1415. // Make sure cache dir is writable, throws exception if not.
  1416. make_cache_directory('');
  1417. // This is the only place where we purge local caches, we are only adding files there.
  1418. // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
  1419. remove_dir($CFG->localcachedir, true);
  1420. set_config('localcachedirpurged', time());
  1421. make_localcache_directory('', true);
  1422. }
  1423. /**
  1424. * Get volatile flags
  1425. *
  1426. * @param string $type
  1427. * @param int $changedsince default null
  1428. * @return array records array
  1429. */
  1430. function get_cache_flags($type, $changedsince = null) {
  1431. global $DB;
  1432. $params = array('type' => $type, 'expiry' => time());
  1433. $sqlwhere = "flagtype = :type AND expiry >= :expiry";
  1434. if ($changedsince !== null) {
  1435. $params['changedsince'] = $changedsince;
  1436. $sqlwhere .= " AND timemodified > :changedsince";
  1437. }
  1438. $cf = array();
  1439. if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
  1440. foreach ($flags as $flag) {
  1441. $cf[$flag->name] = $flag->value;
  1442. }
  1443. }
  1444. return $cf;
  1445. }
  1446. /**
  1447. * Get volatile flags
  1448. *
  1449. * @param string $type
  1450. * @param string $name
  1451. * @param int $changedsince default null
  1452. * @return string|false The cache flag value or false
  1453. */
  1454. function get_cache_flag($type, $name, $changedsince=null) {
  1455. global $DB;
  1456. $params = array('type' => $type, 'name' => $name, 'expiry' => time());
  1457. $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
  1458. if ($changedsince !== null) {
  1459. $params['changedsince'] = $changedsince;
  1460. $sqlwhere .= " AND timemodified > :changedsince";
  1461. }
  1462. return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
  1463. }
  1464. /**
  1465. * Set a volatile flag
  1466. *
  1467. * @param string $type the "type" namespace for the key
  1468. * @param string $name the key to set
  1469. * @param string $value the value to set (without magic quotes) - null will remove the flag
  1470. * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
  1471. * @return bool Always returns true
  1472. */
  1473. function set_cache_flag($type, $name, $value, $expiry = null) {
  1474. global $DB;
  1475. $timemodified = time();
  1476. if ($expiry === null || $expiry < $timemodified) {
  1477. $expiry = $timemodified + 24 * 60 * 60;
  1478. } else {
  1479. $expiry = (int)$expiry;
  1480. }
  1481. if ($value === null) {
  1482. unset_cache_flag($type, $name);
  1483. return true;
  1484. }
  1485. if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
  1486. // This is a potential problem in DEBUG_DEVELOPER.
  1487. if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
  1488. return true; // No need to update.
  1489. }
  1490. $f->value = $value;
  1491. $f->expiry = $expiry;
  1492. $f->timemodified = $timemodified;
  1493. $DB->update_record('cache_flags', $f);
  1494. } else {
  1495. $f = new stdClass();
  1496. $f->flagtype = $type;
  1497. $f->name = $name;
  1498. $f->value = $value;
  1499. $f->expiry = $expiry;
  1500. $f->timemodified = $timemodified;
  1501. $DB->insert_record('cache_flags', $f);
  1502. }
  1503. return true;
  1504. }
  1505. /**
  1506. * Removes a single volatile flag
  1507. *
  1508. * @param string $type the "type" namespace for the key
  1509. * @param string $name the key to set
  1510. * @return bool
  1511. */
  1512. function unset_cache_flag($type, $name) {
  1513. global $DB;
  1514. $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
  1515. return true;
  1516. }
  1517. /**
  1518. * Garbage-collect volatile flags
  1519. *
  1520. * @return bool Always returns true
  1521. */
  1522. function gc_cache_flags() {
  1523. global $DB;
  1524. $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
  1525. return true;
  1526. }
  1527. // USER PREFERENCE API.
  1528. /**
  1529. * Refresh user preference cache. This is used most often for $USER
  1530. * object that is stored in session, but it also helps with performance in cron script.
  1531. *
  1532. * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
  1533. *
  1534. * @package core
  1535. * @category preference
  1536. * @access public
  1537. * @param stdClass $user User object. Preferences are preloaded into 'preference' property
  1538. * @param int $cachelifetime Cache life time on the current page (in seconds)
  1539. * @throws coding_exception
  1540. * @return null
  1541. */
  1542. function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
  1543. global $DB;
  1544. // Static cache, we need to check on each page load, not only every 2 minutes.
  1545. static $loadedusers = array();
  1546. if (!isset($user->id)) {
  1547. throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
  1548. }
  1549. if (empty($user->id) or isguestuser($user->id)) {
  1550. // No permanent storage for not-logged-in users and guest.
  1551. if (!isset($user->preference)) {
  1552. $user->preference = array();
  1553. }
  1554. return;
  1555. }
  1556. $timenow = time();
  1557. if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
  1558. // Already loaded at least once on this page. Are we up to date?
  1559. if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
  1560. // No need to reload - we are on the same page and we loaded prefs just a moment ago.
  1561. return;
  1562. } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
  1563. // No change since the lastcheck on this page.
  1564. $user->preference['_lastloaded'] = $timenow;
  1565. return;
  1566. }
  1567. }
  1568. // OK, so we have to reload all preferences.
  1569. $loadedusers[$user->id] = true;
  1570. $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
  1571. $user->preference['_lastloaded'] = $timenow;
  1572. }
  1573. /**
  1574. * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
  1575. *
  1576. * NOTE: internal function, do not call from other code.
  1577. *
  1578. * @package core
  1579. * @access private
  1580. * @param integer $userid the user whose prefs were changed.
  1581. */
  1582. function mark_user_preferences_changed($userid) {
  1583. global $CFG;
  1584. if (empty($userid) or isguestuser($userid)) {
  1585. // No cache flags for guest and not-logged-in users.
  1586. return;
  1587. }
  1588. set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
  1589. }
  1590. /**
  1591. * Sets a preference for the specified user.
  1592. *
  1593. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1594. *
  1595. * @package core
  1596. * @category preference
  1597. * @access public
  1598. * @param string $name The key to set as preference for the specified user
  1599. * @param string $value The value to set for the $name key in the specified user's
  1600. * record, null means delete current value.
  1601. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1602. * @throws coding_exception
  1603. * @return bool Always true or exception
  1604. */
  1605. function set_user_preference($name, $value, $user = null) {
  1606. global $USER, $DB;
  1607. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1608. throw new coding_exception('Invalid preference name in set_user_preference() call');
  1609. }
  1610. if (is_null($value)) {
  1611. // Null means delete current.
  1612. return unset_user_preference($name, $user);
  1613. } else if (is_object($value)) {
  1614. throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
  1615. } else if (is_array($value)) {
  1616. throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
  1617. }
  1618. // Value column maximum length is 1333 characters.
  1619. $value = (string)$value;
  1620. if (core_text::strlen($value) > 1333) {
  1621. throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
  1622. }
  1623. if (is_null($user)) {
  1624. $user = $USER;
  1625. } else if (isset($user->id)) {
  1626. // It is a valid object.
  1627. } else if (is_numeric($user)) {
  1628. $user = (object)array('id' => (int)$user);
  1629. } else {
  1630. throw new coding_exception('Invalid $user parameter in set_user_preference() call');
  1631. }
  1632. check_user_preferences_loaded($user);
  1633. if (empty($user->id) or isguestuser($user->id)) {
  1634. // No permanent storage for not-logged-in users and guest.
  1635. $user->preference[$name] = $value;
  1636. return true;
  1637. }
  1638. if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
  1639. if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
  1640. // Preference already set to this value.
  1641. return true;
  1642. }
  1643. $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
  1644. } else {
  1645. $preference = new stdClass();
  1646. $preference->userid = $user->id;
  1647. $preference->name = $name;
  1648. $preference->value = $value;
  1649. $DB->insert_record('user_preferences', $preference);
  1650. }
  1651. // Update value in cache.
  1652. $user->preference[$name] = $value;
  1653. // Set reload flag for other sessions.
  1654. mark_user_preferences_changed($user->id);
  1655. return true;
  1656. }
  1657. /**
  1658. * Sets a whole array of preferences for the current user
  1659. *
  1660. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1661. *
  1662. * @package core
  1663. * @category preference
  1664. * @access public
  1665. * @param array $prefarray An array of key/value pairs to be set
  1666. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1667. * @return bool Always true or exception
  1668. */
  1669. function set_user_preferences(array $prefarray, $user = null) {
  1670. foreach ($prefarray as $name => $value) {
  1671. set_user_preference($name, $value, $user);
  1672. }
  1673. return true;
  1674. }
  1675. /**
  1676. * Unsets a preference completely by deleting it from the database
  1677. *
  1678. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1679. *
  1680. * @package core
  1681. * @category preference
  1682. * @access public
  1683. * @param string $name The key to unset as preference for the specified user
  1684. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1685. * @throws coding_exception
  1686. * @return bool Always true or exception
  1687. */
  1688. function unset_user_preference($name, $user = null) {
  1689. global $USER, $DB;
  1690. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1691. throw new coding_exception('Invalid preference name in unset_user_preference() call');
  1692. }
  1693. if (is_null($user)) {
  1694. $user = $USER;
  1695. } else if (isset($user->id)) {
  1696. // It is a valid object.
  1697. } else if (is_numeric($user)) {
  1698. $user = (object)array('id' => (int)$user);
  1699. } else {
  1700. throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
  1701. }
  1702. check_user_preferences_loaded($user);
  1703. if (empty($user->id) or isguestuser($user->id)) {
  1704. // No permanent storage for not-logged-in user and guest.
  1705. unset($user->preference[$name]);
  1706. return true;
  1707. }
  1708. // Delete from DB.
  1709. $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
  1710. // Delete the preference from cache.
  1711. unset($user->preference[$name]);
  1712. // Set reload flag for other sessions.
  1713. mark_user_preferences_changed($user->id);
  1714. return true;
  1715. }
  1716. /**
  1717. * Used to fetch user preference(s)
  1718. *
  1719. * If no arguments are supplied this function will return
  1720. * all of the current user preferences as an array.
  1721. *
  1722. * If a name is specified then this function
  1723. * attempts to return that particular preference value. If
  1724. * none is found, then the optional value $default is returned,
  1725. * otherwise null.
  1726. *
  1727. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1728. *
  1729. * @package core
  1730. * @category preference
  1731. * @access public
  1732. * @param string $name Name of the key to use in finding a preference value
  1733. * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
  1734. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1735. * @throws coding_exception
  1736. * @return string|mixed|null A string containing the value of a single preference. An
  1737. * array with all of the preferences or null
  1738. */
  1739. function get_user_preferences($name = null, $default = null, $user = null) {
  1740. global $USER;
  1741. if (is_null($name)) {
  1742. // All prefs.
  1743. } else if (is_numeric($name) or $name === '_lastloaded') {
  1744. throw new coding_exception('Invalid preference name in get_user_preferences() call');
  1745. }
  1746. if (is_null($user)) {
  1747. $user = $USER;
  1748. } else if (isset($user->id)) {
  1749. // Is a valid object.
  1750. } else if (is_numeric($user)) {
  1751. $user = (object)array('id' => (int)$user);
  1752. } else {
  1753. throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
  1754. }
  1755. check_user_preferences_loaded($user);
  1756. if (empty($name)) {
  1757. // All values.
  1758. return $user->preference;
  1759. } else if (isset($user->preference[$name])) {
  1760. // The single string value.
  1761. return $user->preference[$name];
  1762. } else {
  1763. // Default value (null if not specified).
  1764. return $default;
  1765. }
  1766. }
  1767. // FUNCTIONS FOR HANDLING TIME.
  1768. /**
  1769. * Given date parts in user time produce a GMT timestamp.
  1770. *
  1771. * @package core
  1772. * @category time
  1773. * @param int $year The year part to create timestamp of
  1774. * @param int $month The month part to create timestamp of
  1775. * @param int $day The day part to create timestamp of
  1776. * @param int $hour The hour part to create timestamp of
  1777. * @param int $minute The minute part to create timestamp of
  1778. * @param int $second The second part to create timestamp of
  1779. * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
  1780. * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1781. * @param bool $applydst Toggle Daylight Saving Time, default true, will be
  1782. * applied only if timezone is 99 or string.
  1783. * @return int GMT timestamp
  1784. */
  1785. function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
  1786. // Save input timezone, required for dst offset check.
  1787. $passedtimezone = $timezone;
  1788. $timezone = get_user_timezone_offset($timezone);
  1789. if (abs($timezone) > 13) {
  1790. // Server time.
  1791. $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
  1792. } else {
  1793. $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
  1794. $time = usertime($time, $timezone);
  1795. // Apply dst for string timezones or if 99 then try dst offset with user's default timezone.
  1796. if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
  1797. $time -= dst_offset_on($time, $passedtimezone);
  1798. }
  1799. }
  1800. return $time;
  1801. }
  1802. /**
  1803. * Format a date/time (seconds) as weeks, days, hours etc as needed
  1804. *
  1805. * Given an amount of time in seconds, returns string
  1806. * formatted nicely as weeks, days, hours etc as needed
  1807. *
  1808. * @package core
  1809. * @category time
  1810. * @uses MINSECS
  1811. * @uses HOURSECS
  1812. * @uses DAYSECS
  1813. * @uses YEARSECS
  1814. * @param int $totalsecs Time in seconds
  1815. * @param stdClass $str Should be a time object
  1816. * @return string A nicely formatted date/time string
  1817. */
  1818. function format_time($totalsecs, $str = null) {
  1819. $totalsecs = abs($totalsecs);
  1820. if (!$str) {
  1821. // Create the str structure the slow way.
  1822. $str = new stdClass();
  1823. $str->day = get_string('day');
  1824. $str->days = get_string('days');
  1825. $str->hour = get_string('hour');
  1826. $str->hours = get_string('hours');
  1827. $str->min = get_string('min');
  1828. $str->mins = get_string('mins');
  1829. $str->sec = get_string('sec');
  1830. $str->secs = get_string('secs');
  1831. $str->year = get_string('year');
  1832. $str->years = get_string('years');
  1833. }
  1834. $years = floor($totalsecs/YEARSECS);
  1835. $remainder = $totalsecs - ($years*YEARSECS);
  1836. $days = floor($remainder/DAYSECS);
  1837. $remainder = $totalsecs - ($days*DAYSECS);
  1838. $hours = floor($remainder/HOURSECS);
  1839. $remainder = $remainder - ($hours*HOURSECS);
  1840. $mins = floor($remainder/MINSECS);
  1841. $secs = $remainder - ($mins*MINSECS);
  1842. $ss = ($secs == 1) ? $str->sec : $str->secs;
  1843. $sm = ($mins == 1) ? $str->min : $str->mins;
  1844. $sh = ($hours == 1) ? $str->hour : $str->hours;
  1845. $sd = ($days == 1) ? $str->day : $str->days;
  1846. $sy = ($years == 1) ? $str->year : $str->years;
  1847. $oyears = '';
  1848. $odays = '';
  1849. $ohours = '';
  1850. $omins = '';
  1851. $osecs = '';
  1852. if ($years) {
  1853. $oyears = $years .' '. $sy;
  1854. }
  1855. if ($days) {
  1856. $odays = $days .' '. $sd;
  1857. }
  1858. if ($hours) {
  1859. $ohours = $hours .' '. $sh;
  1860. }
  1861. if ($mins) {
  1862. $omins = $mins .' '. $sm;
  1863. }
  1864. if ($secs) {
  1865. $osecs = $secs .' '. $ss;
  1866. }
  1867. if ($years) {
  1868. return trim($oyears .' '. $odays);
  1869. }
  1870. if ($days) {
  1871. return trim($odays .' '. $ohours);
  1872. }
  1873. if ($hours) {
  1874. return trim($ohours .' '. $omins);
  1875. }
  1876. if ($mins) {
  1877. return trim($omins .' '. $osecs);
  1878. }
  1879. if ($secs) {
  1880. return $osecs;
  1881. }
  1882. return get_string('now');
  1883. }
  1884. /**
  1885. * Returns a formatted string that represents a date in user time.
  1886. *
  1887. * @package core
  1888. * @category time
  1889. * @param int $date the timestamp in UTC, as obtained from the database.
  1890. * @param string $format strftime format. You should probably get this using
  1891. * get_string('strftime...', 'langconfig');
  1892. * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
  1893. * not 99 then daylight saving will not be added.
  1894. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1895. * @param bool $fixday If true (default) then the leading zero from %d is removed.
  1896. * If false then the leading zero is maintained.
  1897. * @param bool $fixhour If true (default) then the leading zero from %I is removed.
  1898. * @return string the formatted date/time.
  1899. */
  1900. function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
  1901. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  1902. return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
  1903. }
  1904. /**
  1905. * Returns a formatted date ensuring it is UTF-8.
  1906. *
  1907. * If we are running under Windows convert to Windows encoding and then back to UTF-8
  1908. * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
  1909. *
  1910. * This function does not do any calculation regarding the user preferences and should
  1911. * therefore receive the final date timestamp, format and timezone. Timezone being only used
  1912. * to differentiate the use of server time or not (strftime() against gmstrftime()).
  1913. *
  1914. * @param int $date the timestamp.
  1915. * @param string $format strftime format.
  1916. * @param int|float $tz the numerical timezone, typically returned by {@link get_user_timezone_offset()}.
  1917. * @return string the formatted date/time.
  1918. * @since 2.3.3
  1919. */
  1920. function date_format_string($date, $format, $tz = 99) {
  1921. global $CFG;
  1922. $localewincharset = null;
  1923. // Get the calendar type user is using.
  1924. if ($CFG->ostype == 'WINDOWS') {
  1925. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  1926. $localewincharset = $calendartype->locale_win_charset();
  1927. }
  1928. if (abs($tz) > 13) {
  1929. if ($localewincharset) {
  1930. $format = core_text::convert($format, 'utf-8', $localewincharset);
  1931. $datestring = strftime($format, $date);
  1932. $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
  1933. } else {
  1934. $datestring = strftime($format, $date);
  1935. }
  1936. } else {
  1937. if ($localewincharset) {
  1938. $format = core_text::convert($format, 'utf-8', $localewincharset);
  1939. $datestring = gmstrftime($format, $date);
  1940. $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
  1941. } else {
  1942. $datestring = gmstrftime($format, $date);
  1943. }
  1944. }
  1945. return $datestring;
  1946. }
  1947. /**
  1948. * Given a $time timestamp in GMT (seconds since epoch),
  1949. * returns an array that represents the date in user time
  1950. *
  1951. * @package core
  1952. * @category time
  1953. * @uses HOURSECS
  1954. * @param int $time Timestamp in GMT
  1955. * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
  1956. * dst offset is applied {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1957. * @return array An array that represents the date in user time
  1958. */
  1959. function usergetdate($time, $timezone=99) {
  1960. // Save input timezone, required for dst offset check.
  1961. $passedtimezone = $timezone;
  1962. $timezone = get_user_timezone_offset($timezone);
  1963. if (abs($timezone) > 13) {
  1964. // Server time.
  1965. return getdate($time);
  1966. }
  1967. // Add daylight saving offset for string timezones only, as we can't get dst for
  1968. // float values. if timezone is 99 (user default timezone), then try update dst.
  1969. if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
  1970. $time += dst_offset_on($time, $passedtimezone);
  1971. }
  1972. $time += intval((float)$timezone * HOURSECS);
  1973. $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
  1974. // Be careful to ensure the returned array matches that produced by getdate() above.
  1975. list(
  1976. $getdate['month'],
  1977. $getdate['weekday'],
  1978. $getdate['yday'],
  1979. $getdate['year'],
  1980. $getdate['mon'],
  1981. $getdate['wday'],
  1982. $getdate['mday'],
  1983. $getdate['hours'],
  1984. $getdate['minutes'],
  1985. $getdate['seconds']
  1986. ) = explode('_', $datestring);
  1987. // Set correct datatype to match with getdate().
  1988. $getdate['seconds'] = (int)$getdate['seconds'];
  1989. $getdate['yday'] = (int)$getdate['yday'] - 1; // The function gmstrftime returns 0 through 365.
  1990. $getdate['year'] = (int)$getdate['year'];
  1991. $getdate['mon'] = (int)$getdate['mon'];
  1992. $getdate['wday'] = (int)$getdate['wday'];
  1993. $getdate['mday'] = (int)$getdate['mday'];
  1994. $getdate['hours'] = (int)$getdate['hours'];
  1995. $getdate['minutes'] = (int)$getdate['minutes'];
  1996. return $getdate;
  1997. }
  1998. /**
  1999. * Given a GMT timestamp (seconds since epoch), offsets it by
  2000. * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
  2001. *
  2002. * @package core
  2003. * @category time
  2004. * @uses HOURSECS
  2005. * @param int $date Timestamp in GMT
  2006. * @param float|int|string $timezone timezone to calculate GMT time offset before
  2007. * calculating user time, 99 is default user timezone
  2008. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2009. * @return int
  2010. */
  2011. function usertime($date, $timezone=99) {
  2012. $timezone = get_user_timezone_offset($timezone);
  2013. if (abs($timezone) > 13) {
  2014. return $date;
  2015. }
  2016. return $date - (int)($timezone * HOURSECS);
  2017. }
  2018. /**
  2019. * Given a time, return the GMT timestamp of the most recent midnight
  2020. * for the current user.
  2021. *
  2022. * @package core
  2023. * @category time
  2024. * @param int $date Timestamp in GMT
  2025. * @param float|int|string $timezone timezone to calculate GMT time offset before
  2026. * calculating user midnight time, 99 is default user timezone
  2027. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2028. * @return int Returns a GMT timestamp
  2029. */
  2030. function usergetmidnight($date, $timezone=99) {
  2031. $userdate = usergetdate($date, $timezone);
  2032. // Time of midnight of this user's day, in GMT.
  2033. return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
  2034. }
  2035. /**
  2036. * Returns a string that prints the user's timezone
  2037. *
  2038. * @package core
  2039. * @category time
  2040. * @param float|int|string $timezone timezone to calculate GMT time offset before
  2041. * calculating user timezone, 99 is default user timezone
  2042. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2043. * @return string
  2044. */
  2045. function usertimezone($timezone=99) {
  2046. $tz = get_user_timezone($timezone);
  2047. if (!is_float($tz)) {
  2048. return $tz;
  2049. }
  2050. if (abs($tz) > 13) {
  2051. // Server time.
  2052. return get_string('serverlocaltime');
  2053. }
  2054. if ($tz == intval($tz)) {
  2055. // Don't show .0 for whole hours.
  2056. $tz = intval($tz);
  2057. }
  2058. if ($tz == 0) {
  2059. return 'UTC';
  2060. } else if ($tz > 0) {
  2061. return 'UTC+'.$tz;
  2062. } else {
  2063. return 'UTC'.$tz;
  2064. }
  2065. }
  2066. /**
  2067. * Returns a float which represents the user's timezone difference from GMT in hours
  2068. * Checks various settings and picks the most dominant of those which have a value
  2069. *
  2070. * @package core
  2071. * @category time
  2072. * @param float|int|string $tz timezone to calculate GMT time offset for user,
  2073. * 99 is default user timezone
  2074. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2075. * @return float
  2076. */
  2077. function get_user_timezone_offset($tz = 99) {
  2078. $tz = get_user_timezone($tz);
  2079. if (is_float($tz)) {
  2080. return $tz;
  2081. } else {
  2082. $tzrecord = get_timezone_record($tz);
  2083. if (empty($tzrecord)) {
  2084. return 99.0;
  2085. }
  2086. return (float)$tzrecord->gmtoff / HOURMINS;
  2087. }
  2088. }
  2089. /**
  2090. * Returns an int which represents the systems's timezone difference from GMT in seconds
  2091. *
  2092. * @package core
  2093. * @category time
  2094. * @param float|int|string $tz timezone for which offset is required.
  2095. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2096. * @return int|bool if found, false is timezone 99 or error
  2097. */
  2098. function get_timezone_offset($tz) {
  2099. if ($tz == 99) {
  2100. return false;
  2101. }
  2102. if (is_numeric($tz)) {
  2103. return intval($tz * 60*60);
  2104. }
  2105. if (!$tzrecord = get_timezone_record($tz)) {
  2106. return false;
  2107. }
  2108. return intval($tzrecord->gmtoff * 60);
  2109. }
  2110. /**
  2111. * Returns a float or a string which denotes the user's timezone
  2112. * 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)
  2113. * means that for this timezone there are also DST rules to be taken into account
  2114. * Checks various settings and picks the most dominant of those which have a value
  2115. *
  2116. * @package core
  2117. * @category time
  2118. * @param float|int|string $tz timezone to calculate GMT time offset before
  2119. * calculating user timezone, 99 is default user timezone
  2120. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2121. * @return float|string
  2122. */
  2123. function get_user_timezone($tz = 99) {
  2124. global $USER, $CFG;
  2125. $timezones = array(
  2126. $tz,
  2127. isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
  2128. isset($USER->timezone) ? $USER->timezone : 99,
  2129. isset($CFG->timezone) ? $CFG->timezone : 99,
  2130. );
  2131. $tz = 99;
  2132. // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
  2133. while (((empty($tz) && !is_numeric($tz)) || $tz == 99) && $next = each($timezones)) {
  2134. $tz = $next['value'];
  2135. }
  2136. return is_numeric($tz) ? (float) $tz : $tz;
  2137. }
  2138. /**
  2139. * Returns cached timezone record for given $timezonename
  2140. *
  2141. * @package core
  2142. * @param string $timezonename name of the timezone
  2143. * @return stdClass|bool timezonerecord or false
  2144. */
  2145. function get_timezone_record($timezonename) {
  2146. global $DB;
  2147. static $cache = null;
  2148. if ($cache === null) {
  2149. $cache = array();
  2150. }
  2151. if (isset($cache[$timezonename])) {
  2152. return $cache[$timezonename];
  2153. }
  2154. return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
  2155. WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
  2156. }
  2157. /**
  2158. * Build and store the users Daylight Saving Time (DST) table
  2159. *
  2160. * @package core
  2161. * @param int $fromyear Start year for the table, defaults to 1971
  2162. * @param int $toyear End year for the table, defaults to 2035
  2163. * @param int|float|string $strtimezone timezone to check if dst should be applied.
  2164. * @return bool
  2165. */
  2166. function calculate_user_dst_table($fromyear = null, $toyear = null, $strtimezone = null) {
  2167. global $SESSION, $DB;
  2168. $usertz = get_user_timezone($strtimezone);
  2169. if (is_float($usertz)) {
  2170. // Trivial timezone, no DST.
  2171. return false;
  2172. }
  2173. if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
  2174. // We have pre-calculated values, but the user's effective TZ has changed in the meantime, so reset.
  2175. unset($SESSION->dst_offsets);
  2176. unset($SESSION->dst_range);
  2177. }
  2178. if (!empty($SESSION->dst_offsets) && empty($fromyear) && empty($toyear)) {
  2179. // Repeat calls which do not request specific year ranges stop here, we have already calculated the table.
  2180. // This will be the return path most of the time, pretty light computationally.
  2181. return true;
  2182. }
  2183. // Reaching here means we either need to extend our table or create it from scratch.
  2184. // Remember which TZ we calculated these changes for.
  2185. $SESSION->dst_offsettz = $usertz;
  2186. if (empty($SESSION->dst_offsets)) {
  2187. // If we 're creating from scratch, put the two guard elements in there.
  2188. $SESSION->dst_offsets = array(1 => null, 0 => null);
  2189. }
  2190. if (empty($SESSION->dst_range)) {
  2191. // If creating from scratch.
  2192. $from = max((empty($fromyear) ? intval(date('Y')) - 3 : $fromyear), 1971);
  2193. $to = min((empty($toyear) ? intval(date('Y')) + 3 : $toyear), 2035);
  2194. // Fill in the array with the extra years we need to process.
  2195. $yearstoprocess = array();
  2196. for ($i = $from; $i <= $to; ++$i) {
  2197. $yearstoprocess[] = $i;
  2198. }
  2199. // Take note of which years we have processed for future calls.
  2200. $SESSION->dst_range = array($from, $to);
  2201. } else {
  2202. // If needing to extend the table, do the same.
  2203. $yearstoprocess = array();
  2204. $from = max((empty($fromyear) ? $SESSION->dst_range[0] : $fromyear), 1971);
  2205. $to = min((empty($toyear) ? $SESSION->dst_range[1] : $toyear), 2035);
  2206. if ($from < $SESSION->dst_range[0]) {
  2207. // Take note of which years we need to process and then note that we have processed them for future calls.
  2208. for ($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
  2209. $yearstoprocess[] = $i;
  2210. }
  2211. $SESSION->dst_range[0] = $from;
  2212. }
  2213. if ($to > $SESSION->dst_range[1]) {
  2214. // Take note of which years we need to process and then note that we have processed them for future calls.
  2215. for ($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
  2216. $yearstoprocess[] = $i;
  2217. }
  2218. $SESSION->dst_range[1] = $to;
  2219. }
  2220. }
  2221. if (empty($yearstoprocess)) {
  2222. // This means that there was a call requesting a SMALLER range than we have already calculated.
  2223. return true;
  2224. }
  2225. // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
  2226. // Also, the array is sorted in descending timestamp order!
  2227. // Get DB data.
  2228. static $presetscache = array();
  2229. if (!isset($presetscache[$usertz])) {
  2230. $presetscache[$usertz] = $DB->get_records('timezone', array('name' => $usertz),
  2231. 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, '.
  2232. 'std_startday, std_weekday, std_skipweeks, std_time');
  2233. }
  2234. if (empty($presetscache[$usertz])) {
  2235. return false;
  2236. }
  2237. // Remove ending guard (first element of the array).
  2238. reset($SESSION->dst_offsets);
  2239. unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
  2240. // Add all required change timestamps.
  2241. foreach ($yearstoprocess as $y) {
  2242. // Find the record which is in effect for the year $y.
  2243. foreach ($presetscache[$usertz] as $year => $preset) {
  2244. if ($year <= $y) {
  2245. break;
  2246. }
  2247. }
  2248. $changes = dst_changes_for_year($y, $preset);
  2249. if ($changes === null) {
  2250. continue;
  2251. }
  2252. if ($changes['dst'] != 0) {
  2253. $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
  2254. }
  2255. if ($changes['std'] != 0) {
  2256. $SESSION->dst_offsets[$changes['std']] = 0;
  2257. }
  2258. }
  2259. // Put in a guard element at the top.
  2260. $maxtimestamp = max(array_keys($SESSION->dst_offsets));
  2261. $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = null; // DAYSECS is arbitrary, any "small" number will do.
  2262. // Sort again.
  2263. krsort($SESSION->dst_offsets);
  2264. return true;
  2265. }
  2266. /**
  2267. * Calculates the required DST change and returns a Timestamp Array
  2268. *
  2269. * @package core
  2270. * @category time
  2271. * @uses HOURSECS
  2272. * @uses MINSECS
  2273. * @param int|string $year Int or String Year to focus on
  2274. * @param object $timezone Instatiated Timezone object
  2275. * @return array|null Array dst => xx, 0 => xx, std => yy, 1 => yy or null
  2276. */
  2277. function dst_changes_for_year($year, $timezone) {
  2278. if ($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 &&
  2279. $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
  2280. return null;
  2281. }
  2282. $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
  2283. $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
  2284. list($dsthour, $dstmin) = explode(':', $timezone->dst_time);
  2285. list($stdhour, $stdmin) = explode(':', $timezone->std_time);
  2286. $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
  2287. $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
  2288. // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
  2289. // This has the advantage of being able to have negative values for hour, i.e. for timezones
  2290. // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
  2291. $timedst += $dsthour * HOURSECS + $dstmin * MINSECS;
  2292. $timestd += $stdhour * HOURSECS + $stdmin * MINSECS;
  2293. return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
  2294. }
  2295. /**
  2296. * Calculates the Daylight Saving Offset for a given date/time (timestamp)
  2297. * - Note: Daylight saving only works for string timezones and not for float.
  2298. *
  2299. * @package core
  2300. * @category time
  2301. * @param int $time must NOT be compensated at all, it has to be a pure timestamp
  2302. * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
  2303. * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2304. * @return int
  2305. */
  2306. function dst_offset_on($time, $strtimezone = null) {
  2307. global $SESSION;
  2308. if (!calculate_user_dst_table(null, null, $strtimezone) || empty($SESSION->dst_offsets)) {
  2309. return 0;
  2310. }
  2311. reset($SESSION->dst_offsets);
  2312. while (list($from, $offset) = each($SESSION->dst_offsets)) {
  2313. if ($from <= $time) {
  2314. break;
  2315. }
  2316. }
  2317. // This is the normal return path.
  2318. if ($offset !== null) {
  2319. return $offset;
  2320. }
  2321. // Reaching this point means we haven't calculated far enough, do it now:
  2322. // Calculate extra DST changes if needed and recurse. The recursion always
  2323. // moves toward the stopping condition, so will always end.
  2324. if ($from == 0) {
  2325. // We need a year smaller than $SESSION->dst_range[0].
  2326. if ($SESSION->dst_range[0] == 1971) {
  2327. return 0;
  2328. }
  2329. calculate_user_dst_table($SESSION->dst_range[0] - 5, null, $strtimezone);
  2330. return dst_offset_on($time, $strtimezone);
  2331. } else {
  2332. // We need a year larger than $SESSION->dst_range[1].
  2333. if ($SESSION->dst_range[1] == 2035) {
  2334. return 0;
  2335. }
  2336. calculate_user_dst_table(null, $SESSION->dst_range[1] + 5, $strtimezone);
  2337. return dst_offset_on($time, $strtimezone);
  2338. }
  2339. }
  2340. /**
  2341. * Calculates when the day appears in specific month
  2342. *
  2343. * @package core
  2344. * @category time
  2345. * @param int $startday starting day of the month
  2346. * @param int $weekday The day when week starts (normally taken from user preferences)
  2347. * @param int $month The month whose day is sought
  2348. * @param int $year The year of the month whose day is sought
  2349. * @return int
  2350. */
  2351. function find_day_in_month($startday, $weekday, $month, $year) {
  2352. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2353. $daysinmonth = days_in_month($month, $year);
  2354. $daysinweek = count($calendartype->get_weekdays());
  2355. if ($weekday == -1) {
  2356. // Don't care about weekday, so return:
  2357. // abs($startday) if $startday != -1
  2358. // $daysinmonth otherwise.
  2359. return ($startday == -1) ? $daysinmonth : abs($startday);
  2360. }
  2361. // From now on we 're looking for a specific weekday.
  2362. // Give "end of month" its actual value, since we know it.
  2363. if ($startday == -1) {
  2364. $startday = -1 * $daysinmonth;
  2365. }
  2366. // Starting from day $startday, the sign is the direction.
  2367. if ($startday < 1) {
  2368. $startday = abs($startday);
  2369. $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
  2370. // This is the last such weekday of the month.
  2371. $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
  2372. if ($lastinmonth > $daysinmonth) {
  2373. $lastinmonth -= $daysinweek;
  2374. }
  2375. // Find the first such weekday <= $startday.
  2376. while ($lastinmonth > $startday) {
  2377. $lastinmonth -= $daysinweek;
  2378. }
  2379. return $lastinmonth;
  2380. } else {
  2381. $indexweekday = dayofweek($startday, $month, $year);
  2382. $diff = $weekday - $indexweekday;
  2383. if ($diff < 0) {
  2384. $diff += $daysinweek;
  2385. }
  2386. // This is the first such weekday of the month equal to or after $startday.
  2387. $firstfromindex = $startday + $diff;
  2388. return $firstfromindex;
  2389. }
  2390. }
  2391. /**
  2392. * Calculate the number of days in a given month
  2393. *
  2394. * @package core
  2395. * @category time
  2396. * @param int $month The month whose day count is sought
  2397. * @param int $year The year of the month whose day count is sought
  2398. * @return int
  2399. */
  2400. function days_in_month($month, $year) {
  2401. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2402. return $calendartype->get_num_days_in_month($year, $month);
  2403. }
  2404. /**
  2405. * Calculate the position in the week of a specific calendar day
  2406. *
  2407. * @package core
  2408. * @category time
  2409. * @param int $day The day of the date whose position in the week is sought
  2410. * @param int $month The month of the date whose position in the week is sought
  2411. * @param int $year The year of the date whose position in the week is sought
  2412. * @return int
  2413. */
  2414. function dayofweek($day, $month, $year) {
  2415. $calendartype = \core_calendar\type_factory::get_calendar_instance();
  2416. return $calendartype->get_weekday($year, $month, $day);
  2417. }
  2418. // USER AUTHENTICATION AND LOGIN.
  2419. /**
  2420. * Returns full login url.
  2421. *
  2422. * @return string login url
  2423. */
  2424. function get_login_url() {
  2425. global $CFG;
  2426. $url = "$CFG->wwwroot/login/index.php";
  2427. if (!empty($CFG->loginhttps)) {
  2428. $url = str_replace('http:', 'https:', $url);
  2429. }
  2430. return $url;
  2431. }
  2432. /**
  2433. * This function checks that the current user is logged in and has the
  2434. * required privileges
  2435. *
  2436. * This function checks that the current user is logged in, and optionally
  2437. * whether they are allowed to be in a particular course and view a particular
  2438. * course module.
  2439. * If they are not logged in, then it redirects them to the site login unless
  2440. * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
  2441. * case they are automatically logged in as guests.
  2442. * If $courseid is given and the user is not enrolled in that course then the
  2443. * user is redirected to the course enrolment page.
  2444. * If $cm is given and the course module is hidden and the user is not a teacher
  2445. * in the course then the user is redirected to the course home page.
  2446. *
  2447. * When $cm parameter specified, this function sets page layout to 'module'.
  2448. * You need to change it manually later if some other layout needed.
  2449. *
  2450. * @package core_access
  2451. * @category access
  2452. *
  2453. * @param mixed $courseorid id of the course or course object
  2454. * @param bool $autologinguest default true
  2455. * @param object $cm course module object
  2456. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  2457. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  2458. * in order to keep redirects working properly. MDL-14495
  2459. * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
  2460. * @return mixed Void, exit, and die depending on path
  2461. * @throws coding_exception
  2462. * @throws require_login_exception
  2463. */
  2464. function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
  2465. global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
  2466. // Must not redirect when byteserving already started.
  2467. if (!empty($_SERVER['HTTP_RANGE'])) {
  2468. $preventredirect = true;
  2469. }
  2470. // Setup global $COURSE, themes, language and locale.
  2471. if (!empty($courseorid)) {
  2472. if (is_object($courseorid)) {
  2473. $course = $courseorid;
  2474. } else if ($courseorid == SITEID) {
  2475. $course = clone($SITE);
  2476. } else {
  2477. $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
  2478. }
  2479. if ($cm) {
  2480. if ($cm->course != $course->id) {
  2481. throw new coding_exception('course and cm parameters in require_login() call do not match!!');
  2482. }
  2483. // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
  2484. if (!($cm instanceof cm_info)) {
  2485. // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
  2486. // db queries so this is not really a performance concern, however it is obviously
  2487. // better if you use get_fast_modinfo to get the cm before calling this.
  2488. $modinfo = get_fast_modinfo($course);
  2489. $cm = $modinfo->get_cm($cm->id);
  2490. }
  2491. $PAGE->set_cm($cm, $course); // Set's up global $COURSE.
  2492. $PAGE->set_pagelayout('incourse');
  2493. } else {
  2494. $PAGE->set_course($course); // Set's up global $COURSE.
  2495. }
  2496. } else {
  2497. // Do not touch global $COURSE via $PAGE->set_course(),
  2498. // the reasons is we need to be able to call require_login() at any time!!
  2499. $course = $SITE;
  2500. if ($cm) {
  2501. throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
  2502. }
  2503. }
  2504. // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
  2505. // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
  2506. // risk leading the user back to the AJAX request URL.
  2507. if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
  2508. $setwantsurltome = false;
  2509. }
  2510. // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
  2511. if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !$preventredirect && !empty($CFG->dbsessions)) {
  2512. if ($setwantsurltome) {
  2513. $SESSION->wantsurl = qualified_me();
  2514. }
  2515. redirect(get_login_url());
  2516. }
  2517. // If the user is not even logged in yet then make sure they are.
  2518. if (!isloggedin()) {
  2519. if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
  2520. if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
  2521. // Misconfigured site guest, just redirect to login page.
  2522. redirect(get_login_url());
  2523. exit; // Never reached.
  2524. }
  2525. $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
  2526. complete_user_login($guest);
  2527. $USER->autologinguest = true;
  2528. $SESSION->lang = $lang;
  2529. } else {
  2530. // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
  2531. if ($preventredirect) {
  2532. throw new require_login_exception('You are not logged in');
  2533. }
  2534. if ($setwantsurltome) {
  2535. $SESSION->wantsurl = qualified_me();
  2536. }
  2537. if (!empty($_SERVER['HTTP_REFERER'])) {
  2538. $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
  2539. }
  2540. redirect(get_login_url());
  2541. exit; // Never reached.
  2542. }
  2543. }
  2544. // Loginas as redirection if needed.
  2545. if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
  2546. if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
  2547. if ($USER->loginascontext->instanceid != $course->id) {
  2548. print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
  2549. }
  2550. }
  2551. }
  2552. // Check whether the user should be changing password (but only if it is REALLY them).
  2553. if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
  2554. $userauth = get_auth_plugin($USER->auth);
  2555. if ($userauth->can_change_password() and !$preventredirect) {
  2556. if ($setwantsurltome) {
  2557. $SESSION->wantsurl = qualified_me();
  2558. }
  2559. if ($changeurl = $userauth->change_password_url()) {
  2560. // Use plugin custom url.
  2561. redirect($changeurl);
  2562. } else {
  2563. // Use moodle internal method.
  2564. if (empty($CFG->loginhttps)) {
  2565. redirect($CFG->wwwroot .'/login/change_password.php');
  2566. } else {
  2567. $wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
  2568. redirect($wwwroot .'/login/change_password.php');
  2569. }
  2570. }
  2571. } else {
  2572. print_error('nopasswordchangeforced', 'auth');
  2573. }
  2574. }
  2575. // Check that the user account is properly set up.
  2576. if (user_not_fully_set_up($USER)) {
  2577. if ($preventredirect) {
  2578. throw new require_login_exception('User not fully set-up');
  2579. }
  2580. if ($setwantsurltome) {
  2581. $SESSION->wantsurl = qualified_me();
  2582. }
  2583. redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
  2584. }
  2585. // Make sure the USER has a sesskey set up. Used for CSRF protection.
  2586. sesskey();
  2587. // Do not bother admins with any formalities.
  2588. if (is_siteadmin()) {
  2589. // Set accesstime or the user will appear offline which messes up messaging.
  2590. user_accesstime_log($course->id);
  2591. return;
  2592. }
  2593. // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
  2594. if (!$USER->policyagreed and !is_siteadmin()) {
  2595. if (!empty($CFG->sitepolicy) and !isguestuser()) {
  2596. if ($preventredirect) {
  2597. throw new require_login_exception('Policy not agreed');
  2598. }
  2599. if ($setwantsurltome) {
  2600. $SESSION->wantsurl = qualified_me();
  2601. }
  2602. redirect($CFG->wwwroot .'/user/policy.php');
  2603. } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
  2604. if ($preventredirect) {
  2605. throw new require_login_exception('Policy not agreed');
  2606. }
  2607. if ($setwantsurltome) {
  2608. $SESSION->wantsurl = qualified_me();
  2609. }
  2610. redirect($CFG->wwwroot .'/user/policy.php');
  2611. }
  2612. }
  2613. // Fetch the system context, the course context, and prefetch its child contexts.
  2614. $sysctx = context_system::instance();
  2615. $coursecontext = context_course::instance($course->id, MUST_EXIST);
  2616. if ($cm) {
  2617. $cmcontext = context_module::instance($cm->id, MUST_EXIST);
  2618. } else {
  2619. $cmcontext = null;
  2620. }
  2621. // If the site is currently under maintenance, then print a message.
  2622. if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
  2623. if ($preventredirect) {
  2624. throw new require_login_exception('Maintenance in progress');
  2625. }
  2626. print_maintenance_message();
  2627. }
  2628. // Make sure the course itself is not hidden.
  2629. if ($course->id == SITEID) {
  2630. // Frontpage can not be hidden.
  2631. } else {
  2632. if (is_role_switched($course->id)) {
  2633. // When switching roles ignore the hidden flag - user had to be in course to do the switch.
  2634. } else {
  2635. if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
  2636. // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
  2637. // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
  2638. if ($preventredirect) {
  2639. throw new require_login_exception('Course is hidden');
  2640. }
  2641. // We need to override the navigation URL as the course won't have been added to the navigation and thus
  2642. // the navigation will mess up when trying to find it.
  2643. navigation_node::override_active_url(new moodle_url('/'));
  2644. notice(get_string('coursehidden'), $CFG->wwwroot .'/');
  2645. }
  2646. }
  2647. }
  2648. // Is the user enrolled?
  2649. if ($course->id == SITEID) {
  2650. // Everybody is enrolled on the frontpage.
  2651. } else {
  2652. if (\core\session\manager::is_loggedinas()) {
  2653. // Make sure the REAL person can access this course first.
  2654. $realuser = \core\session\manager::get_realuser();
  2655. if (!is_enrolled($coursecontext, $realuser->id, '', true) and
  2656. !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
  2657. if ($preventredirect) {
  2658. throw new require_login_exception('Invalid course login-as access');
  2659. }
  2660. echo $OUTPUT->header();
  2661. notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
  2662. }
  2663. }
  2664. $access = false;
  2665. if (is_role_switched($course->id)) {
  2666. // Ok, user had to be inside this course before the switch.
  2667. $access = true;
  2668. } else if (is_viewing($coursecontext, $USER)) {
  2669. // Ok, no need to mess with enrol.
  2670. $access = true;
  2671. } else {
  2672. if (isset($USER->enrol['enrolled'][$course->id])) {
  2673. if ($USER->enrol['enrolled'][$course->id] > time()) {
  2674. $access = true;
  2675. if (isset($USER->enrol['tempguest'][$course->id])) {
  2676. unset($USER->enrol['tempguest'][$course->id]);
  2677. remove_temp_course_roles($coursecontext);
  2678. }
  2679. } else {
  2680. // Expired.
  2681. unset($USER->enrol['enrolled'][$course->id]);
  2682. }
  2683. }
  2684. if (isset($USER->enrol['tempguest'][$course->id])) {
  2685. if ($USER->enrol['tempguest'][$course->id] == 0) {
  2686. $access = true;
  2687. } else if ($USER->enrol['tempguest'][$course->id] > time()) {
  2688. $access = true;
  2689. } else {
  2690. // Expired.
  2691. unset($USER->enrol['tempguest'][$course->id]);
  2692. remove_temp_course_roles($coursecontext);
  2693. }
  2694. }
  2695. if (!$access) {
  2696. // Cache not ok.
  2697. $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
  2698. if ($until !== false) {
  2699. // Active participants may always access, a timestamp in the future, 0 (always) or false.
  2700. if ($until == 0) {
  2701. $until = ENROL_MAX_TIMESTAMP;
  2702. }
  2703. $USER->enrol['enrolled'][$course->id] = $until;
  2704. $access = true;
  2705. } else {
  2706. $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
  2707. $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
  2708. $enrols = enrol_get_plugins(true);
  2709. // First ask all enabled enrol instances in course if they want to auto enrol user.
  2710. foreach ($instances as $instance) {
  2711. if (!isset($enrols[$instance->enrol])) {
  2712. continue;
  2713. }
  2714. // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
  2715. $until = $enrols[$instance->enrol]->try_autoenrol($instance);
  2716. if ($until !== false) {
  2717. if ($until == 0) {
  2718. $until = ENROL_MAX_TIMESTAMP;
  2719. }
  2720. $USER->enrol['enrolled'][$course->id] = $until;
  2721. $access = true;
  2722. break;
  2723. }
  2724. }
  2725. // If not enrolled yet try to gain temporary guest access.
  2726. if (!$access) {
  2727. foreach ($instances as $instance) {
  2728. if (!isset($enrols[$instance->enrol])) {
  2729. continue;
  2730. }
  2731. // Get a duration for the guest access, a timestamp in the future or false.
  2732. $until = $enrols[$instance->enrol]->try_guestaccess($instance);
  2733. if ($until !== false and $until > time()) {
  2734. $USER->enrol['tempguest'][$course->id] = $until;
  2735. $access = true;
  2736. break;
  2737. }
  2738. }
  2739. }
  2740. }
  2741. }
  2742. }
  2743. if (!$access) {
  2744. if ($preventredirect) {
  2745. throw new require_login_exception('Not enrolled');
  2746. }
  2747. if ($setwantsurltome) {
  2748. $SESSION->wantsurl = qualified_me();
  2749. }
  2750. redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
  2751. }
  2752. }
  2753. // Check visibility of activity to current user; includes visible flag, groupmembersonly, conditional availability, etc.
  2754. if ($cm && !$cm->uservisible) {
  2755. if ($preventredirect) {
  2756. throw new require_login_exception('Activity is hidden');
  2757. }
  2758. if ($course->id != SITEID) {
  2759. $url = new moodle_url('/course/view.php', array('id' => $course->id));
  2760. } else {
  2761. $url = new moodle_url('/');
  2762. }
  2763. redirect($url, get_string('activityiscurrentlyhidden'));
  2764. }
  2765. // Finally access granted, update lastaccess times.
  2766. user_accesstime_log($course->id);
  2767. }
  2768. /**
  2769. * This function just makes sure a user is logged out.
  2770. *
  2771. * @package core_access
  2772. * @category access
  2773. */
  2774. function require_logout() {
  2775. global $USER, $DB;
  2776. if (!isloggedin()) {
  2777. // This should not happen often, no need for hooks or events here.
  2778. \core\session\manager::terminate_current();
  2779. return;
  2780. }
  2781. // Execute hooks before action.
  2782. $authsequence = get_enabled_auth_plugins();
  2783. foreach ($authsequence as $authname) {
  2784. $authplugin = get_auth_plugin($authname);
  2785. $authplugin->prelogout_hook();
  2786. }
  2787. // Store info that gets removed during logout.
  2788. $sid = session_id();
  2789. $event = \core\event\user_loggedout::create(
  2790. array(
  2791. 'userid' => $USER->id,
  2792. 'objectid' => $USER->id,
  2793. 'other' => array('sessionid' => $sid),
  2794. )
  2795. );
  2796. if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
  2797. $event->add_record_snapshot('sessions', $session);
  2798. }
  2799. // Delete session record and drop $_SESSION content.
  2800. \core\session\manager::terminate_current();
  2801. // Trigger event AFTER action.
  2802. $event->trigger();
  2803. }
  2804. /**
  2805. * Weaker version of require_login()
  2806. *
  2807. * This is a weaker version of {@link require_login()} which only requires login
  2808. * when called from within a course rather than the site page, unless
  2809. * the forcelogin option is turned on.
  2810. * @see require_login()
  2811. *
  2812. * @package core_access
  2813. * @category access
  2814. *
  2815. * @param mixed $courseorid The course object or id in question
  2816. * @param bool $autologinguest Allow autologin guests if that is wanted
  2817. * @param object $cm Course activity module if known
  2818. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  2819. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  2820. * in order to keep redirects working properly. MDL-14495
  2821. * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
  2822. * @return void
  2823. * @throws coding_exception
  2824. */
  2825. function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
  2826. global $CFG, $PAGE, $SITE;
  2827. $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
  2828. or (!is_object($courseorid) and $courseorid == SITEID));
  2829. if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
  2830. // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
  2831. // db queries so this is not really a performance concern, however it is obviously
  2832. // better if you use get_fast_modinfo to get the cm before calling this.
  2833. if (is_object($courseorid)) {
  2834. $course = $courseorid;
  2835. } else {
  2836. $course = clone($SITE);
  2837. }
  2838. $modinfo = get_fast_modinfo($course);
  2839. $cm = $modinfo->get_cm($cm->id);
  2840. }
  2841. if (!empty($CFG->forcelogin)) {
  2842. // Login required for both SITE and courses.
  2843. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2844. } else if ($issite && !empty($cm) and !$cm->uservisible) {
  2845. // Always login for hidden activities.
  2846. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2847. } else if ($issite) {
  2848. // Login for SITE not required.
  2849. if ($cm and empty($cm->visible)) {
  2850. // Hidden activities are not accessible without login.
  2851. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2852. } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
  2853. // Not-logged-in users do not have any group membership.
  2854. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2855. } else {
  2856. // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
  2857. if (!empty($courseorid)) {
  2858. if (is_object($courseorid)) {
  2859. $course = $courseorid;
  2860. } else {
  2861. $course = clone($SITE);
  2862. }
  2863. if ($cm) {
  2864. if ($cm->course != $course->id) {
  2865. throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
  2866. }
  2867. $PAGE->set_cm($cm, $course);
  2868. $PAGE->set_pagelayout('incourse');
  2869. } else {
  2870. $PAGE->set_course($course);
  2871. }
  2872. } else {
  2873. // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
  2874. $PAGE->set_course($PAGE->course);
  2875. }
  2876. // TODO: verify conditional activities here.
  2877. user_accesstime_log(SITEID);
  2878. return;
  2879. }
  2880. } else {
  2881. // Course login always required.
  2882. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2883. }
  2884. }
  2885. /**
  2886. * Require key login. Function terminates with error if key not found or incorrect.
  2887. *
  2888. * @uses NO_MOODLE_COOKIES
  2889. * @uses PARAM_ALPHANUM
  2890. * @param string $script unique script identifier
  2891. * @param int $instance optional instance id
  2892. * @return int Instance ID
  2893. */
  2894. function require_user_key_login($script, $instance=null) {
  2895. global $DB;
  2896. if (!NO_MOODLE_COOKIES) {
  2897. print_error('sessioncookiesdisable');
  2898. }
  2899. // Extra safety.
  2900. \core\session\manager::write_close();
  2901. $keyvalue = required_param('key', PARAM_ALPHANUM);
  2902. if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
  2903. print_error('invalidkey');
  2904. }
  2905. if (!empty($key->validuntil) and $key->validuntil < time()) {
  2906. print_error('expiredkey');
  2907. }
  2908. if ($key->iprestriction) {
  2909. $remoteaddr = getremoteaddr(null);
  2910. if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
  2911. print_error('ipmismatch');
  2912. }
  2913. }
  2914. if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
  2915. print_error('invaliduserid');
  2916. }
  2917. // Emulate normal session.
  2918. enrol_check_plugins($user);
  2919. \core\session\manager::set_user($user);
  2920. // Note we are not using normal login.
  2921. if (!defined('USER_KEY_LOGIN')) {
  2922. define('USER_KEY_LOGIN', true);
  2923. }
  2924. // Return instance id - it might be empty.
  2925. return $key->instance;
  2926. }
  2927. /**
  2928. * Creates a new private user access key.
  2929. *
  2930. * @param string $script unique target identifier
  2931. * @param int $userid
  2932. * @param int $instance optional instance id
  2933. * @param string $iprestriction optional ip restricted access
  2934. * @param timestamp $validuntil key valid only until given data
  2935. * @return string access key value
  2936. */
  2937. function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
  2938. global $DB;
  2939. $key = new stdClass();
  2940. $key->script = $script;
  2941. $key->userid = $userid;
  2942. $key->instance = $instance;
  2943. $key->iprestriction = $iprestriction;
  2944. $key->validuntil = $validuntil;
  2945. $key->timecreated = time();
  2946. // Something long and unique.
  2947. $key->value = md5($userid.'_'.time().random_string(40));
  2948. while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
  2949. // Must be unique.
  2950. $key->value = md5($userid.'_'.time().random_string(40));
  2951. }
  2952. $DB->insert_record('user_private_key', $key);
  2953. return $key->value;
  2954. }
  2955. /**
  2956. * Delete the user's new private user access keys for a particular script.
  2957. *
  2958. * @param string $script unique target identifier
  2959. * @param int $userid
  2960. * @return void
  2961. */
  2962. function delete_user_key($script, $userid) {
  2963. global $DB;
  2964. $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
  2965. }
  2966. /**
  2967. * Gets a private user access key (and creates one if one doesn't exist).
  2968. *
  2969. * @param string $script unique target identifier
  2970. * @param int $userid
  2971. * @param int $instance optional instance id
  2972. * @param string $iprestriction optional ip restricted access
  2973. * @param timestamp $validuntil key valid only until given data
  2974. * @return string access key value
  2975. */
  2976. function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
  2977. global $DB;
  2978. if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
  2979. 'instance' => $instance, 'iprestriction' => $iprestriction,
  2980. 'validuntil' => $validuntil))) {
  2981. return $key->value;
  2982. } else {
  2983. return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
  2984. }
  2985. }
  2986. /**
  2987. * Modify the user table by setting the currently logged in user's last login to now.
  2988. *
  2989. * @return bool Always returns true
  2990. */
  2991. function update_user_login_times() {
  2992. global $USER, $DB;
  2993. if (isguestuser()) {
  2994. // Do not update guest access times/ips for performance.
  2995. return true;
  2996. }
  2997. $now = time();
  2998. $user = new stdClass();
  2999. $user->id = $USER->id;
  3000. // Make sure all users that logged in have some firstaccess.
  3001. if ($USER->firstaccess == 0) {
  3002. $USER->firstaccess = $user->firstaccess = $now;
  3003. }
  3004. // Store the previous current as lastlogin.
  3005. $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
  3006. $USER->currentlogin = $user->currentlogin = $now;
  3007. // Function user_accesstime_log() may not update immediately, better do it here.
  3008. $USER->lastaccess = $user->lastaccess = $now;
  3009. $USER->lastip = $user->lastip = getremoteaddr();
  3010. // Note: do not call user_update_user() here because this is part of the login process,
  3011. // the login event means that these fields were updated.
  3012. $DB->update_record('user', $user);
  3013. return true;
  3014. }
  3015. /**
  3016. * Determines if a user has completed setting up their account.
  3017. *
  3018. * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
  3019. * @return bool
  3020. */
  3021. function user_not_fully_set_up($user) {
  3022. if (isguestuser($user)) {
  3023. return false;
  3024. }
  3025. return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
  3026. }
  3027. /**
  3028. * Check whether the user has exceeded the bounce threshold
  3029. *
  3030. * @param stdClass $user A {@link $USER} object
  3031. * @return bool true => User has exceeded bounce threshold
  3032. */
  3033. function over_bounce_threshold($user) {
  3034. global $CFG, $DB;
  3035. if (empty($CFG->handlebounces)) {
  3036. return false;
  3037. }
  3038. if (empty($user->id)) {
  3039. // No real (DB) user, nothing to do here.
  3040. return false;
  3041. }
  3042. // Set sensible defaults.
  3043. if (empty($CFG->minbounces)) {
  3044. $CFG->minbounces = 10;
  3045. }
  3046. if (empty($CFG->bounceratio)) {
  3047. $CFG->bounceratio = .20;
  3048. }
  3049. $bouncecount = 0;
  3050. $sendcount = 0;
  3051. if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
  3052. $bouncecount = $bounce->value;
  3053. }
  3054. if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
  3055. $sendcount = $send->value;
  3056. }
  3057. return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
  3058. }
  3059. /**
  3060. * Used to increment or reset email sent count
  3061. *
  3062. * @param stdClass $user object containing an id
  3063. * @param bool $reset will reset the count to 0
  3064. * @return void
  3065. */
  3066. function set_send_count($user, $reset=false) {
  3067. global $DB;
  3068. if (empty($user->id)) {
  3069. // No real (DB) user, nothing to do here.
  3070. return;
  3071. }
  3072. if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
  3073. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  3074. $DB->update_record('user_preferences', $pref);
  3075. } else if (!empty($reset)) {
  3076. // If it's not there and we're resetting, don't bother. Make a new one.
  3077. $pref = new stdClass();
  3078. $pref->name = 'email_send_count';
  3079. $pref->value = 1;
  3080. $pref->userid = $user->id;
  3081. $DB->insert_record('user_preferences', $pref, false);
  3082. }
  3083. }
  3084. /**
  3085. * Increment or reset user's email bounce count
  3086. *
  3087. * @param stdClass $user object containing an id
  3088. * @param bool $reset will reset the count to 0
  3089. */
  3090. function set_bounce_count($user, $reset=false) {
  3091. global $DB;
  3092. if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
  3093. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  3094. $DB->update_record('user_preferences', $pref);
  3095. } else if (!empty($reset)) {
  3096. // If it's not there and we're resetting, don't bother. Make a new one.
  3097. $pref = new stdClass();
  3098. $pref->name = 'email_bounce_count';
  3099. $pref->value = 1;
  3100. $pref->userid = $user->id;
  3101. $DB->insert_record('user_preferences', $pref, false);
  3102. }
  3103. }
  3104. /**
  3105. * Determines if the logged in user is currently moving an activity
  3106. *
  3107. * @param int $courseid The id of the course being tested
  3108. * @return bool
  3109. */
  3110. function ismoving($courseid) {
  3111. global $USER;
  3112. if (!empty($USER->activitycopy)) {
  3113. return ($USER->activitycopycourse == $courseid);
  3114. }
  3115. return false;
  3116. }
  3117. /**
  3118. * Returns a persons full name
  3119. *
  3120. * Given an object containing all of the users name values, this function returns a string with the full name of the person.
  3121. * The result may depend on system settings or language. 'override' will force both names to be used even if system settings
  3122. * specify one.
  3123. *
  3124. * @param stdClass $user A {@link $USER} object to get full name of.
  3125. * @param bool $override If true then the name will be firstname followed by lastname rather than adhering to fullnamedisplay.
  3126. * @return string
  3127. */
  3128. function fullname($user, $override=false) {
  3129. global $CFG, $SESSION;
  3130. if (!isset($user->firstname) and !isset($user->lastname)) {
  3131. return '';
  3132. }
  3133. // Get all of the name fields.
  3134. $allnames = get_all_user_name_fields();
  3135. if ($CFG->debugdeveloper) {
  3136. foreach ($allnames as $allname) {
  3137. if (!array_key_exists($allname, $user)) {
  3138. // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
  3139. debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
  3140. // Message has been sent, no point in sending the message multiple times.
  3141. break;
  3142. }
  3143. }
  3144. }
  3145. if (!$override) {
  3146. if (!empty($CFG->forcefirstname)) {
  3147. $user->firstname = $CFG->forcefirstname;
  3148. }
  3149. if (!empty($CFG->forcelastname)) {
  3150. $user->lastname = $CFG->forcelastname;
  3151. }
  3152. }
  3153. if (!empty($SESSION->fullnamedisplay)) {
  3154. $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
  3155. }
  3156. $template = null;
  3157. // If the fullnamedisplay setting is available, set the template to that.
  3158. if (isset($CFG->fullnamedisplay)) {
  3159. $template = $CFG->fullnamedisplay;
  3160. }
  3161. // If the template is empty, or set to language, or $override is set, return the language string.
  3162. if (empty($template) || $template == 'language' || $override) {
  3163. return get_string('fullnamedisplay', null, $user);
  3164. }
  3165. $requirednames = array();
  3166. // With each name, see if it is in the display name template, and add it to the required names array if it is.
  3167. foreach ($allnames as $allname) {
  3168. if (strpos($template, $allname) !== false) {
  3169. $requirednames[] = $allname;
  3170. }
  3171. }
  3172. $displayname = $template;
  3173. // Switch in the actual data into the template.
  3174. foreach ($requirednames as $altname) {
  3175. if (isset($user->$altname)) {
  3176. // Using empty() on the below if statement causes breakages.
  3177. if ((string)$user->$altname == '') {
  3178. $displayname = str_replace($altname, 'EMPTY', $displayname);
  3179. } else {
  3180. $displayname = str_replace($altname, $user->$altname, $displayname);
  3181. }
  3182. } else {
  3183. $displayname = str_replace($altname, 'EMPTY', $displayname);
  3184. }
  3185. }
  3186. // Tidy up any misc. characters (Not perfect, but gets most characters).
  3187. // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
  3188. // katakana and parenthesis.
  3189. $patterns = array();
  3190. // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
  3191. // filled in by a user.
  3192. // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
  3193. $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
  3194. // This regular expression is to remove any double spaces in the display name.
  3195. $patterns[] = '/\s{2,}/u';
  3196. foreach ($patterns as $pattern) {
  3197. $displayname = preg_replace($pattern, ' ', $displayname);
  3198. }
  3199. // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
  3200. $displayname = trim($displayname);
  3201. if (empty($displayname)) {
  3202. // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
  3203. // people in general feel is a good setting to fall back on.
  3204. $displayname = $user->firstname;
  3205. }
  3206. return $displayname;
  3207. }
  3208. /**
  3209. * A centralised location for the all name fields. Returns an array / sql string snippet.
  3210. *
  3211. * @param bool $returnsql True for an sql select field snippet.
  3212. * @param string $tableprefix table query prefix to use in front of each field.
  3213. * @param string $prefix prefix added to the name fields e.g. authorfirstname.
  3214. * @param string $fieldprefix sql field prefix e.g. id AS userid.
  3215. * @return array|string All name fields.
  3216. */
  3217. function get_all_user_name_fields($returnsql = false, $tableprefix = null, $prefix = null, $fieldprefix = null) {
  3218. $alternatenames = array('firstnamephonetic' => 'firstnamephonetic',
  3219. 'lastnamephonetic' => 'lastnamephonetic',
  3220. 'middlename' => 'middlename',
  3221. 'alternatename' => 'alternatename',
  3222. 'firstname' => 'firstname',
  3223. 'lastname' => 'lastname');
  3224. // Let's add a prefix to the array of user name fields if provided.
  3225. if ($prefix) {
  3226. foreach ($alternatenames as $key => $altname) {
  3227. $alternatenames[$key] = $prefix . $altname;
  3228. }
  3229. }
  3230. // Create an sql field snippet if requested.
  3231. if ($returnsql) {
  3232. if ($tableprefix) {
  3233. if ($fieldprefix) {
  3234. foreach ($alternatenames as $key => $altname) {
  3235. $alternatenames[$key] = $tableprefix . '.' . $altname . ' AS ' . $fieldprefix . $altname;
  3236. }
  3237. } else {
  3238. foreach ($alternatenames as $key => $altname) {
  3239. $alternatenames[$key] = $tableprefix . '.' . $altname;
  3240. }
  3241. }
  3242. }
  3243. $alternatenames = implode(',', $alternatenames);
  3244. }
  3245. return $alternatenames;
  3246. }
  3247. /**
  3248. * Reduces lines of duplicated code for getting user name fields.
  3249. *
  3250. * @param object $addtoobject Object to add user name fields to.
  3251. * @param object $secondobject Object that contains user name field information.
  3252. * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
  3253. * @param array $additionalfields Additional fields to be matched with data in the second object.
  3254. * The key can be set to the user table field name.
  3255. * @return object User name fields.
  3256. */
  3257. function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
  3258. $fields = get_all_user_name_fields(false, null, $prefix);
  3259. if ($additionalfields) {
  3260. // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
  3261. // the key is a number and then sets the key to the array value.
  3262. foreach ($additionalfields as $key => $value) {
  3263. if (is_numeric($key)) {
  3264. $additionalfields[$value] = $prefix . $value;
  3265. unset($additionalfields[$key]);
  3266. } else {
  3267. $additionalfields[$key] = $prefix . $value;
  3268. }
  3269. }
  3270. $fields = array_merge($fields, $additionalfields);
  3271. }
  3272. foreach ($fields as $key => $field) {
  3273. // Important that we have all of the user name fields present in the object that we are sending back.
  3274. $addtoobject->$key = '';
  3275. if (isset($secondobject->$field)) {
  3276. $addtoobject->$key = $secondobject->$field;
  3277. }
  3278. }
  3279. return $addtoobject;
  3280. }
  3281. /**
  3282. * Returns an array of values in order of occurance in a provided string.
  3283. * The key in the result is the character postion in the string.
  3284. *
  3285. * @param array $values Values to be found in the string format
  3286. * @param string $stringformat The string which may contain values being searched for.
  3287. * @return array An array of values in order according to placement in the string format.
  3288. */
  3289. function order_in_string($values, $stringformat) {
  3290. $valuearray = array();
  3291. foreach ($values as $value) {
  3292. $pattern = "/$value\b/";
  3293. // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
  3294. if (preg_match($pattern, $stringformat)) {
  3295. $replacement = "thing";
  3296. // Replace the value with something more unique to ensure we get the right position when using strpos().
  3297. $newformat = preg_replace($pattern, $replacement, $stringformat);
  3298. $position = strpos($newformat, $replacement);
  3299. $valuearray[$position] = $value;
  3300. }
  3301. }
  3302. ksort($valuearray);
  3303. return $valuearray;
  3304. }
  3305. /**
  3306. * Checks if current user is shown any extra fields when listing users.
  3307. *
  3308. * @param object $context Context
  3309. * @param array $already Array of fields that we're going to show anyway
  3310. * so don't bother listing them
  3311. * @return array Array of field names from user table, not including anything
  3312. * listed in $already
  3313. */
  3314. function get_extra_user_fields($context, $already = array()) {
  3315. global $CFG;
  3316. // Only users with permission get the extra fields.
  3317. if (!has_capability('moodle/site:viewuseridentity', $context)) {
  3318. return array();
  3319. }
  3320. // Split showuseridentity on comma.
  3321. if (empty($CFG->showuseridentity)) {
  3322. // Explode gives wrong result with empty string.
  3323. $extra = array();
  3324. } else {
  3325. $extra = explode(',', $CFG->showuseridentity);
  3326. }
  3327. $renumber = false;
  3328. foreach ($extra as $key => $field) {
  3329. if (in_array($field, $already)) {
  3330. unset($extra[$key]);
  3331. $renumber = true;
  3332. }
  3333. }
  3334. if ($renumber) {
  3335. // For consistency, if entries are removed from array, renumber it
  3336. // so they are numbered as you would expect.
  3337. $extra = array_merge($extra);
  3338. }
  3339. return $extra;
  3340. }
  3341. /**
  3342. * If the current user is to be shown extra user fields when listing or
  3343. * selecting users, returns a string suitable for including in an SQL select
  3344. * clause to retrieve those fields.
  3345. *
  3346. * @param context $context Context
  3347. * @param string $alias Alias of user table, e.g. 'u' (default none)
  3348. * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
  3349. * @param array $already Array of fields that we're going to include anyway so don't list them (default none)
  3350. * @return string Partial SQL select clause, beginning with comma, for example ',u.idnumber,u.department' unless it is blank
  3351. */
  3352. function get_extra_user_fields_sql($context, $alias='', $prefix='', $already = array()) {
  3353. $fields = get_extra_user_fields($context, $already);
  3354. $result = '';
  3355. // Add punctuation for alias.
  3356. if ($alias !== '') {
  3357. $alias .= '.';
  3358. }
  3359. foreach ($fields as $field) {
  3360. $result .= ', ' . $alias . $field;
  3361. if ($prefix) {
  3362. $result .= ' AS ' . $prefix . $field;
  3363. }
  3364. }
  3365. return $result;
  3366. }
  3367. /**
  3368. * Returns the display name of a field in the user table. Works for most fields that are commonly displayed to users.
  3369. * @param string $field Field name, e.g. 'phone1'
  3370. * @return string Text description taken from language file, e.g. 'Phone number'
  3371. */
  3372. function get_user_field_name($field) {
  3373. // Some fields have language strings which are not the same as field name.
  3374. switch ($field) {
  3375. case 'phone1' : {
  3376. return get_string('phone');
  3377. }
  3378. case 'url' : {
  3379. return get_string('webpage');
  3380. }
  3381. case 'icq' : {
  3382. return get_string('icqnumber');
  3383. }
  3384. case 'skype' : {
  3385. return get_string('skypeid');
  3386. }
  3387. case 'aim' : {
  3388. return get_string('aimid');
  3389. }
  3390. case 'yahoo' : {
  3391. return get_string('yahooid');
  3392. }
  3393. case 'msn' : {
  3394. return get_string('msnid');
  3395. }
  3396. }
  3397. // Otherwise just use the same lang string.
  3398. return get_string($field);
  3399. }
  3400. /**
  3401. * Returns whether a given authentication plugin exists.
  3402. *
  3403. * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
  3404. * @return boolean Whether the plugin is available.
  3405. */
  3406. function exists_auth_plugin($auth) {
  3407. global $CFG;
  3408. if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
  3409. return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
  3410. }
  3411. return false;
  3412. }
  3413. /**
  3414. * Checks if a given plugin is in the list of enabled authentication plugins.
  3415. *
  3416. * @param string $auth Authentication plugin.
  3417. * @return boolean Whether the plugin is enabled.
  3418. */
  3419. function is_enabled_auth($auth) {
  3420. if (empty($auth)) {
  3421. return false;
  3422. }
  3423. $enabled = get_enabled_auth_plugins();
  3424. return in_array($auth, $enabled);
  3425. }
  3426. /**
  3427. * Returns an authentication plugin instance.
  3428. *
  3429. * @param string $auth name of authentication plugin
  3430. * @return auth_plugin_base An instance of the required authentication plugin.
  3431. */
  3432. function get_auth_plugin($auth) {
  3433. global $CFG;
  3434. // Check the plugin exists first.
  3435. if (! exists_auth_plugin($auth)) {
  3436. print_error('authpluginnotfound', 'debug', '', $auth);
  3437. }
  3438. // Return auth plugin instance.
  3439. require_once("{$CFG->dirroot}/auth/$auth/auth.php");
  3440. $class = "auth_plugin_$auth";
  3441. return new $class;
  3442. }
  3443. /**
  3444. * Returns array of active auth plugins.
  3445. *
  3446. * @param bool $fix fix $CFG->auth if needed
  3447. * @return array
  3448. */
  3449. function get_enabled_auth_plugins($fix=false) {
  3450. global $CFG;
  3451. $default = array('manual', 'nologin');
  3452. if (empty($CFG->auth)) {
  3453. $auths = array();
  3454. } else {
  3455. $auths = explode(',', $CFG->auth);
  3456. }
  3457. if ($fix) {
  3458. $auths = array_unique($auths);
  3459. foreach ($auths as $k => $authname) {
  3460. if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
  3461. unset($auths[$k]);
  3462. }
  3463. }
  3464. $newconfig = implode(',', $auths);
  3465. if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
  3466. set_config('auth', $newconfig);
  3467. }
  3468. }
  3469. return (array_merge($default, $auths));
  3470. }
  3471. /**
  3472. * Returns true if an internal authentication method is being used.
  3473. * if method not specified then, global default is assumed
  3474. *
  3475. * @param string $auth Form of authentication required
  3476. * @return bool
  3477. */
  3478. function is_internal_auth($auth) {
  3479. // Throws error if bad $auth.
  3480. $authplugin = get_auth_plugin($auth);
  3481. return $authplugin->is_internal();
  3482. }
  3483. /**
  3484. * Returns true if the user is a 'restored' one.
  3485. *
  3486. * Used in the login process to inform the user and allow him/her to reset the password
  3487. *
  3488. * @param string $username username to be checked
  3489. * @return bool
  3490. */
  3491. function is_restored_user($username) {
  3492. global $CFG, $DB;
  3493. return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
  3494. }
  3495. /**
  3496. * Returns an array of user fields
  3497. *
  3498. * @return array User field/column names
  3499. */
  3500. function get_user_fieldnames() {
  3501. global $DB;
  3502. $fieldarray = $DB->get_columns('user');
  3503. unset($fieldarray['id']);
  3504. $fieldarray = array_keys($fieldarray);
  3505. return $fieldarray;
  3506. }
  3507. /**
  3508. * Creates a bare-bones user record
  3509. *
  3510. * @todo Outline auth types and provide code example
  3511. *
  3512. * @param string $username New user's username to add to record
  3513. * @param string $password New user's password to add to record
  3514. * @param string $auth Form of authentication required
  3515. * @return stdClass A complete user object
  3516. */
  3517. function create_user_record($username, $password, $auth = 'manual') {
  3518. global $CFG, $DB;
  3519. require_once($CFG->dirroot.'/user/profile/lib.php');
  3520. require_once($CFG->dirroot.'/user/lib.php');
  3521. // Just in case check text case.
  3522. $username = trim(core_text::strtolower($username));
  3523. $authplugin = get_auth_plugin($auth);
  3524. $customfields = $authplugin->get_custom_user_profile_fields();
  3525. $newuser = new stdClass();
  3526. if ($newinfo = $authplugin->get_userinfo($username)) {
  3527. $newinfo = truncate_userinfo($newinfo);
  3528. foreach ($newinfo as $key => $value) {
  3529. if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
  3530. $newuser->$key = $value;
  3531. }
  3532. }
  3533. }
  3534. if (!empty($newuser->email)) {
  3535. if (email_is_not_allowed($newuser->email)) {
  3536. unset($newuser->email);
  3537. }
  3538. }
  3539. if (!isset($newuser->city)) {
  3540. $newuser->city = '';
  3541. }
  3542. $newuser->auth = $auth;
  3543. $newuser->username = $username;
  3544. // Fix for MDL-8480
  3545. // user CFG lang for user if $newuser->lang is empty
  3546. // or $user->lang is not an installed language.
  3547. if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
  3548. $newuser->lang = $CFG->lang;
  3549. }
  3550. $newuser->confirmed = 1;
  3551. $newuser->lastip = getremoteaddr();
  3552. $newuser->timecreated = time();
  3553. $newuser->timemodified = $newuser->timecreated;
  3554. $newuser->mnethostid = $CFG->mnet_localhost_id;
  3555. $newuser->id = user_create_user($newuser, false, false);
  3556. // Save user profile data.
  3557. profile_save_data($newuser);
  3558. $user = get_complete_user_data('id', $newuser->id);
  3559. if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
  3560. set_user_preference('auth_forcepasswordchange', 1, $user);
  3561. }
  3562. // Set the password.
  3563. update_internal_user_password($user, $password);
  3564. // Trigger event.
  3565. \core\event\user_created::create_from_userid($newuser->id)->trigger();
  3566. return $user;
  3567. }
  3568. /**
  3569. * Will update a local user record from an external source (MNET users can not be updated using this method!).
  3570. *
  3571. * @param string $username user's username to update the record
  3572. * @return stdClass A complete user object
  3573. */
  3574. function update_user_record($username) {
  3575. global $DB, $CFG;
  3576. require_once($CFG->dirroot."/user/profile/lib.php");
  3577. require_once($CFG->dirroot.'/user/lib.php');
  3578. // Just in case check text case.
  3579. $username = trim(core_text::strtolower($username));
  3580. $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
  3581. $newuser = array();
  3582. $userauth = get_auth_plugin($oldinfo->auth);
  3583. if ($newinfo = $userauth->get_userinfo($username)) {
  3584. $newinfo = truncate_userinfo($newinfo);
  3585. $customfields = $userauth->get_custom_user_profile_fields();
  3586. foreach ($newinfo as $key => $value) {
  3587. $key = strtolower($key);
  3588. $iscustom = in_array($key, $customfields);
  3589. if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
  3590. or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
  3591. // Unknown or must not be changed.
  3592. continue;
  3593. }
  3594. $confval = $userauth->config->{'field_updatelocal_' . $key};
  3595. $lockval = $userauth->config->{'field_lock_' . $key};
  3596. if (empty($confval) || empty($lockval)) {
  3597. continue;
  3598. }
  3599. if ($confval === 'onlogin') {
  3600. // MDL-4207 Don't overwrite modified user profile values with
  3601. // empty LDAP values when 'unlocked if empty' is set. The purpose
  3602. // of the setting 'unlocked if empty' is to allow the user to fill
  3603. // in a value for the selected field _if LDAP is giving
  3604. // nothing_ for this field. Thus it makes sense to let this value
  3605. // stand in until LDAP is giving a value for this field.
  3606. if (!(empty($value) && $lockval === 'unlockedifempty')) {
  3607. if ($iscustom || (in_array($key, $userauth->userfields) &&
  3608. ((string)$oldinfo->$key !== (string)$value))) {
  3609. $newuser[$key] = (string)$value;
  3610. }
  3611. }
  3612. }
  3613. }
  3614. if ($newuser) {
  3615. $newuser['id'] = $oldinfo->id;
  3616. $newuser['timemodified'] = time();
  3617. user_update_user((object) $newuser, false, false);
  3618. // Save user profile data.
  3619. profile_save_data((object) $newuser);
  3620. // Trigger event.
  3621. \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
  3622. }
  3623. }
  3624. return get_complete_user_data('id', $oldinfo->id);
  3625. }
  3626. /**
  3627. * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
  3628. *
  3629. * @param array $info Array of user properties to truncate if needed
  3630. * @return array The now truncated information that was passed in
  3631. */
  3632. function truncate_userinfo(array $info) {
  3633. // Define the limits.
  3634. $limit = array(
  3635. 'username' => 100,
  3636. 'idnumber' => 255,
  3637. 'firstname' => 100,
  3638. 'lastname' => 100,
  3639. 'email' => 100,
  3640. 'icq' => 15,
  3641. 'phone1' => 20,
  3642. 'phone2' => 20,
  3643. 'institution' => 255,
  3644. 'department' => 255,
  3645. 'address' => 255,
  3646. 'city' => 120,
  3647. 'country' => 2,
  3648. 'url' => 255,
  3649. );
  3650. // Apply where needed.
  3651. foreach (array_keys($info) as $key) {
  3652. if (!empty($limit[$key])) {
  3653. $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
  3654. }
  3655. }
  3656. return $info;
  3657. }
  3658. /**
  3659. * Marks user deleted in internal user database and notifies the auth plugin.
  3660. * Also unenrols user from all roles and does other cleanup.
  3661. *
  3662. * Any plugin that needs to purge user data should register the 'user_deleted' event.
  3663. *
  3664. * @param stdClass $user full user object before delete
  3665. * @return boolean success
  3666. * @throws coding_exception if invalid $user parameter detected
  3667. */
  3668. function delete_user(stdClass $user) {
  3669. global $CFG, $DB;
  3670. require_once($CFG->libdir.'/grouplib.php');
  3671. require_once($CFG->libdir.'/gradelib.php');
  3672. require_once($CFG->dirroot.'/message/lib.php');
  3673. require_once($CFG->dirroot.'/tag/lib.php');
  3674. require_once($CFG->dirroot.'/user/lib.php');
  3675. // Make sure nobody sends bogus record type as parameter.
  3676. if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
  3677. throw new coding_exception('Invalid $user parameter in delete_user() detected');
  3678. }
  3679. // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
  3680. if (!$user = $DB->get_record('user', array('id' => $user->id))) {
  3681. debugging('Attempt to delete unknown user account.');
  3682. return false;
  3683. }
  3684. // There must be always exactly one guest record, originally the guest account was identified by username only,
  3685. // now we use $CFG->siteguest for performance reasons.
  3686. if ($user->username === 'guest' or isguestuser($user)) {
  3687. debugging('Guest user account can not be deleted.');
  3688. return false;
  3689. }
  3690. // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
  3691. // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
  3692. if ($user->auth === 'manual' and is_siteadmin($user)) {
  3693. debugging('Local administrator accounts can not be deleted.');
  3694. return false;
  3695. }
  3696. // Keep user record before updating it, as we have to pass this to user_deleted event.
  3697. $olduser = clone $user;
  3698. // Keep a copy of user context, we need it for event.
  3699. $usercontext = context_user::instance($user->id);
  3700. // Delete all grades - backup is kept in grade_grades_history table.
  3701. grade_user_delete($user->id);
  3702. // Move unread messages from this user to read.
  3703. message_move_userfrom_unread2read($user->id);
  3704. // TODO: remove from cohorts using standard API here.
  3705. // Remove user tags.
  3706. tag_set('user', $user->id, array());
  3707. // Unconditionally unenrol from all courses.
  3708. enrol_user_delete($user);
  3709. // Unenrol from all roles in all contexts.
  3710. // This might be slow but it is really needed - modules might do some extra cleanup!
  3711. role_unassign_all(array('userid' => $user->id));
  3712. // Now do a brute force cleanup.
  3713. // Remove from all cohorts.
  3714. $DB->delete_records('cohort_members', array('userid' => $user->id));
  3715. // Remove from all groups.
  3716. $DB->delete_records('groups_members', array('userid' => $user->id));
  3717. // Brute force unenrol from all courses.
  3718. $DB->delete_records('user_enrolments', array('userid' => $user->id));
  3719. // Purge user preferences.
  3720. $DB->delete_records('user_preferences', array('userid' => $user->id));
  3721. // Purge user extra profile info.
  3722. $DB->delete_records('user_info_data', array('userid' => $user->id));
  3723. // Last course access not necessary either.
  3724. $DB->delete_records('user_lastaccess', array('userid' => $user->id));
  3725. // Remove all user tokens.
  3726. $DB->delete_records('external_tokens', array('userid' => $user->id));
  3727. // Unauthorise the user for all services.
  3728. $DB->delete_records('external_services_users', array('userid' => $user->id));
  3729. // Remove users private keys.
  3730. $DB->delete_records('user_private_key', array('userid' => $user->id));
  3731. // Remove users customised pages.
  3732. $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
  3733. // Force logout - may fail if file based sessions used, sorry.
  3734. \core\session\manager::kill_user_sessions($user->id);
  3735. // Workaround for bulk deletes of users with the same email address.
  3736. $delname = clean_param($user->email . "." . time(), PARAM_USERNAME);
  3737. while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
  3738. $delname++;
  3739. }
  3740. // Mark internal user record as "deleted".
  3741. $updateuser = new stdClass();
  3742. $updateuser->id = $user->id;
  3743. $updateuser->deleted = 1;
  3744. $updateuser->username = $delname; // Remember it just in case.
  3745. $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users.
  3746. $updateuser->idnumber = ''; // Clear this field to free it up.
  3747. $updateuser->picture = 0;
  3748. $updateuser->timemodified = time();
  3749. // Don't trigger update event, as user is being deleted.
  3750. user_update_user($updateuser, false, false);
  3751. // Now do a final accesslib cleanup - removes all role assignments in user context and context itself.
  3752. context_helper::delete_instance(CONTEXT_USER, $user->id);
  3753. // Any plugin that needs to cleanup should register this event.
  3754. // Trigger event.
  3755. $event = \core\event\user_deleted::create(
  3756. array(
  3757. 'objectid' => $user->id,
  3758. 'context' => $usercontext,
  3759. 'other' => array(
  3760. 'username' => $user->username,
  3761. 'email' => $user->email,
  3762. 'idnumber' => $user->idnumber,
  3763. 'picture' => $user->picture,
  3764. 'mnethostid' => $user->mnethostid
  3765. )
  3766. )
  3767. );
  3768. $event->add_record_snapshot('user', $olduser);
  3769. $event->trigger();
  3770. // We will update the user's timemodified, as it will be passed to the user_deleted event, which
  3771. // should know about this updated property persisted to the user's table.
  3772. $user->timemodified = $updateuser->timemodified;
  3773. // Notify auth plugin - do not block the delete even when plugin fails.
  3774. $authplugin = get_auth_plugin($user->auth);
  3775. $authplugin->user_delete($user);
  3776. return true;
  3777. }
  3778. /**
  3779. * Retrieve the guest user object.
  3780. *
  3781. * @return stdClass A {@link $USER} object
  3782. */
  3783. function guest_user() {
  3784. global $CFG, $DB;
  3785. if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
  3786. $newuser->confirmed = 1;
  3787. $newuser->lang = $CFG->lang;
  3788. $newuser->lastip = getremoteaddr();
  3789. }
  3790. return $newuser;
  3791. }
  3792. /**
  3793. * Authenticates a user against the chosen authentication mechanism
  3794. *
  3795. * Given a username and password, this function looks them
  3796. * up using the currently selected authentication mechanism,
  3797. * and if the authentication is successful, it returns a
  3798. * valid $user object from the 'user' table.
  3799. *
  3800. * Uses auth_ functions from the currently active auth module
  3801. *
  3802. * After authenticate_user_login() returns success, you will need to
  3803. * log that the user has logged in, and call complete_user_login() to set
  3804. * the session up.
  3805. *
  3806. * Note: this function works only with non-mnet accounts!
  3807. *
  3808. * @param string $username User's username
  3809. * @param string $password User's password
  3810. * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
  3811. * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
  3812. * @return stdClass|false A {@link $USER} object or false if error
  3813. */
  3814. function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null) {
  3815. global $CFG, $DB;
  3816. require_once("$CFG->libdir/authlib.php");
  3817. $authsenabled = get_enabled_auth_plugins();
  3818. if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
  3819. // Use manual if auth not set.
  3820. $auth = empty($user->auth) ? 'manual' : $user->auth;
  3821. if (!empty($user->suspended)) {
  3822. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3823. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3824. $failurereason = AUTH_LOGIN_SUSPENDED;
  3825. return false;
  3826. }
  3827. if ($auth=='nologin' or !is_enabled_auth($auth)) {
  3828. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3829. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3830. // Legacy way to suspend user.
  3831. $failurereason = AUTH_LOGIN_SUSPENDED;
  3832. return false;
  3833. }
  3834. $auths = array($auth);
  3835. } else {
  3836. // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
  3837. if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'deleted' => 1))) {
  3838. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3839. $failurereason = AUTH_LOGIN_NOUSER;
  3840. return false;
  3841. }
  3842. // Do not try to authenticate non-existent accounts when user creation is not disabled.
  3843. if (!empty($CFG->authpreventaccountcreation)) {
  3844. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3845. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Unknown user, can not create new accounts: $username ".$_SERVER['HTTP_USER_AGENT']);
  3846. $failurereason = AUTH_LOGIN_NOUSER;
  3847. return false;
  3848. }
  3849. // User does not exist.
  3850. $auths = $authsenabled;
  3851. $user = new stdClass();
  3852. $user->id = 0;
  3853. }
  3854. if ($ignorelockout) {
  3855. // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
  3856. // or this function is called from a SSO script.
  3857. } else if ($user->id) {
  3858. // Verify login lockout after other ways that may prevent user login.
  3859. if (login_is_lockedout($user)) {
  3860. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3861. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Login lockout: $username ".$_SERVER['HTTP_USER_AGENT']);
  3862. $failurereason = AUTH_LOGIN_LOCKOUT;
  3863. return false;
  3864. }
  3865. } else {
  3866. // We can not lockout non-existing accounts.
  3867. }
  3868. foreach ($auths as $auth) {
  3869. $authplugin = get_auth_plugin($auth);
  3870. // On auth fail fall through to the next plugin.
  3871. if (!$authplugin->user_login($username, $password)) {
  3872. continue;
  3873. }
  3874. // Successful authentication.
  3875. if ($user->id) {
  3876. // User already exists in database.
  3877. if (empty($user->auth)) {
  3878. // For some reason auth isn't set yet.
  3879. $DB->set_field('user', 'auth', $auth, array('username' => $username));
  3880. $user->auth = $auth;
  3881. }
  3882. // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
  3883. // the current hash algorithm while we have access to the user's password.
  3884. update_internal_user_password($user, $password);
  3885. if ($authplugin->is_synchronised_with_external()) {
  3886. // Update user record from external DB.
  3887. $user = update_user_record($username);
  3888. }
  3889. } else {
  3890. // Create account, we verified above that user creation is allowed.
  3891. $user = create_user_record($username, $password, $auth);
  3892. }
  3893. $authplugin->sync_roles($user);
  3894. foreach ($authsenabled as $hau) {
  3895. $hauth = get_auth_plugin($hau);
  3896. $hauth->user_authenticated_hook($user, $username, $password);
  3897. }
  3898. if (empty($user->id)) {
  3899. $failurereason = AUTH_LOGIN_NOUSER;
  3900. return false;
  3901. }
  3902. if (!empty($user->suspended)) {
  3903. // Just in case some auth plugin suspended account.
  3904. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3905. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3906. $failurereason = AUTH_LOGIN_SUSPENDED;
  3907. return false;
  3908. }
  3909. login_attempt_valid($user);
  3910. $failurereason = AUTH_LOGIN_OK;
  3911. return $user;
  3912. }
  3913. // Failed if all the plugins have failed.
  3914. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3915. if (debugging('', DEBUG_ALL)) {
  3916. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3917. }
  3918. if ($user->id) {
  3919. login_attempt_failed($user);
  3920. $failurereason = AUTH_LOGIN_FAILED;
  3921. } else {
  3922. $failurereason = AUTH_LOGIN_NOUSER;
  3923. }
  3924. return false;
  3925. }
  3926. /**
  3927. * Call to complete the user login process after authenticate_user_login()
  3928. * has succeeded. It will setup the $USER variable and other required bits
  3929. * and pieces.
  3930. *
  3931. * NOTE:
  3932. * - It will NOT log anything -- up to the caller to decide what to log.
  3933. * - this function does not set any cookies any more!
  3934. *
  3935. * @param stdClass $user
  3936. * @return stdClass A {@link $USER} object - BC only, do not use
  3937. */
  3938. function complete_user_login($user) {
  3939. global $CFG, $USER;
  3940. \core\session\manager::login_user($user);
  3941. // Reload preferences from DB.
  3942. unset($USER->preference);
  3943. check_user_preferences_loaded($USER);
  3944. // Update login times.
  3945. update_user_login_times();
  3946. // Extra session prefs init.
  3947. set_login_session_preferences();
  3948. // Trigger login event.
  3949. $event = \core\event\user_loggedin::create(
  3950. array(
  3951. 'userid' => $USER->id,
  3952. 'objectid' => $USER->id,
  3953. 'other' => array('username' => $USER->username),
  3954. )
  3955. );
  3956. $event->trigger();
  3957. if (isguestuser()) {
  3958. // No need to continue when user is THE guest.
  3959. return $USER;
  3960. }
  3961. if (CLI_SCRIPT) {
  3962. // We can redirect to password change URL only in browser.
  3963. return $USER;
  3964. }
  3965. // Select password change url.
  3966. $userauth = get_auth_plugin($USER->auth);
  3967. // Check whether the user should be changing password.
  3968. if (get_user_preferences('auth_forcepasswordchange', false)) {
  3969. if ($userauth->can_change_password()) {
  3970. if ($changeurl = $userauth->change_password_url()) {
  3971. redirect($changeurl);
  3972. } else {
  3973. redirect($CFG->httpswwwroot.'/login/change_password.php');
  3974. }
  3975. } else {
  3976. print_error('nopasswordchangeforced', 'auth');
  3977. }
  3978. }
  3979. return $USER;
  3980. }
  3981. /**
  3982. * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
  3983. *
  3984. * @param string $password String to check.
  3985. * @return boolean True if the $password matches the format of an md5 sum.
  3986. */
  3987. function password_is_legacy_hash($password) {
  3988. return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
  3989. }
  3990. /**
  3991. * Checks whether the password compatibility library will work with the current
  3992. * version of PHP. This cannot be done using PHP version numbers since the fix
  3993. * has been backported to earlier versions in some distributions.
  3994. *
  3995. * See https://github.com/ircmaxell/password_compat/issues/10 for more details.
  3996. *
  3997. * @return bool True if the library is NOT supported.
  3998. */
  3999. function password_compat_not_supported() {
  4000. $hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
  4001. // Create a one off application cache to store bcrypt support status as
  4002. // the support status doesn't change and crypt() is slow.
  4003. $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'password_compat');
  4004. if (!$bcryptsupport = $cache->get('bcryptsupport')) {
  4005. $test = crypt('password', $hash);
  4006. // Cache string instead of boolean to avoid MDL-37472.
  4007. if ($test == $hash) {
  4008. $bcryptsupport = 'supported';
  4009. } else {
  4010. $bcryptsupport = 'not supported';
  4011. }
  4012. $cache->set('bcryptsupport', $bcryptsupport);
  4013. }
  4014. // Return true if bcrypt *not* supported.
  4015. return ($bcryptsupport !== 'supported');
  4016. }
  4017. /**
  4018. * Compare password against hash stored in user object to determine if it is valid.
  4019. *
  4020. * If necessary it also updates the stored hash to the current format.
  4021. *
  4022. * @param stdClass $user (Password property may be updated).
  4023. * @param string $password Plain text password.
  4024. * @return bool True if password is valid.
  4025. */
  4026. function validate_internal_user_password($user, $password) {
  4027. global $CFG;
  4028. require_once($CFG->libdir.'/password_compat/lib/password.php');
  4029. if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
  4030. // Internal password is not used at all, it can not validate.
  4031. return false;
  4032. }
  4033. // If hash isn't a legacy (md5) hash, validate using the library function.
  4034. if (!password_is_legacy_hash($user->password)) {
  4035. return password_verify($password, $user->password);
  4036. }
  4037. // Otherwise we need to check for a legacy (md5) hash instead. If the hash
  4038. // is valid we can then update it to the new algorithm.
  4039. $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
  4040. $validated = false;
  4041. if ($user->password === md5($password.$sitesalt)
  4042. or $user->password === md5($password)
  4043. or $user->password === md5(addslashes($password).$sitesalt)
  4044. or $user->password === md5(addslashes($password))) {
  4045. // Note: we are intentionally using the addslashes() here because we
  4046. // need to accept old password hashes of passwords with magic quotes.
  4047. $validated = true;
  4048. } else {
  4049. for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
  4050. $alt = 'passwordsaltalt'.$i;
  4051. if (!empty($CFG->$alt)) {
  4052. if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
  4053. $validated = true;
  4054. break;
  4055. }
  4056. }
  4057. }
  4058. }
  4059. if ($validated) {
  4060. // If the password matches the existing md5 hash, update to the
  4061. // current hash algorithm while we have access to the user's password.
  4062. update_internal_user_password($user, $password);
  4063. }
  4064. return $validated;
  4065. }
  4066. /**
  4067. * Calculate hash for a plain text password.
  4068. *
  4069. * @param string $password Plain text password to be hashed.
  4070. * @param bool $fasthash If true, use a low cost factor when generating the hash
  4071. * This is much faster to generate but makes the hash
  4072. * less secure. It is used when lots of hashes need to
  4073. * be generated quickly.
  4074. * @return string The hashed password.
  4075. *
  4076. * @throws moodle_exception If a problem occurs while generating the hash.
  4077. */
  4078. function hash_internal_user_password($password, $fasthash = false) {
  4079. global $CFG;
  4080. require_once($CFG->libdir.'/password_compat/lib/password.php');
  4081. // Use the legacy hashing algorithm (md5) if PHP is not new enough to support bcrypt properly.
  4082. if (password_compat_not_supported()) {
  4083. if (isset($CFG->passwordsaltmain)) {
  4084. return md5($password.$CFG->passwordsaltmain);
  4085. } else {
  4086. return md5($password);
  4087. }
  4088. }
  4089. // Set the cost factor to 4 for fast hashing, otherwise use default cost.
  4090. $options = ($fasthash) ? array('cost' => 4) : array();
  4091. $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
  4092. if ($generatedhash === false || $generatedhash === null) {
  4093. throw new moodle_exception('Failed to generate password hash.');
  4094. }
  4095. return $generatedhash;
  4096. }
  4097. /**
  4098. * Update password hash in user object (if necessary).
  4099. *
  4100. * The password is updated if:
  4101. * 1. The password has changed (the hash of $user->password is different
  4102. * to the hash of $password).
  4103. * 2. The existing hash is using an out-of-date algorithm (or the legacy
  4104. * md5 algorithm).
  4105. *
  4106. * Updating the password will modify the $user object and the database
  4107. * record to use the current hashing algorithm.
  4108. *
  4109. * @param stdClass $user User object (password property may be updated).
  4110. * @param string $password Plain text password.
  4111. * @return bool Always returns true.
  4112. */
  4113. function update_internal_user_password($user, $password) {
  4114. global $CFG, $DB;
  4115. require_once($CFG->libdir.'/password_compat/lib/password.php');
  4116. // Use the legacy hashing algorithm (md5) if PHP doesn't support bcrypt properly.
  4117. $legacyhash = password_compat_not_supported();
  4118. // Figure out what the hashed password should be.
  4119. $authplugin = get_auth_plugin($user->auth);
  4120. if ($authplugin->prevent_local_passwords()) {
  4121. $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
  4122. } else {
  4123. $hashedpassword = hash_internal_user_password($password);
  4124. }
  4125. if ($legacyhash) {
  4126. $passwordchanged = ($user->password !== $hashedpassword);
  4127. $algorithmchanged = false;
  4128. } else {
  4129. if (isset($user->password)) {
  4130. // If verification fails then it means the password has changed.
  4131. $passwordchanged = !password_verify($password, $user->password);
  4132. $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
  4133. } else {
  4134. $passwordchanged = true;
  4135. }
  4136. }
  4137. if ($passwordchanged || $algorithmchanged) {
  4138. $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
  4139. $user->password = $hashedpassword;
  4140. // Trigger event.
  4141. $event = \core\event\user_updated::create(array(
  4142. 'objectid' => $user->id,
  4143. 'context' => context_user::instance($user->id)
  4144. ));
  4145. $event->add_record_snapshot('user', $user);
  4146. $event->trigger();
  4147. }
  4148. return true;
  4149. }
  4150. /**
  4151. * Get a complete user record, which includes all the info in the user record.
  4152. *
  4153. * Intended for setting as $USER session variable
  4154. *
  4155. * @param string $field The user field to be checked for a given value.
  4156. * @param string $value The value to match for $field.
  4157. * @param int $mnethostid
  4158. * @return mixed False, or A {@link $USER} object.
  4159. */
  4160. function get_complete_user_data($field, $value, $mnethostid = null) {
  4161. global $CFG, $DB;
  4162. if (!$field || !$value) {
  4163. return false;
  4164. }
  4165. // Build the WHERE clause for an SQL query.
  4166. $params = array('fieldval' => $value);
  4167. $constraints = "$field = :fieldval AND deleted <> 1";
  4168. // If we are loading user data based on anything other than id,
  4169. // we must also restrict our search based on mnet host.
  4170. if ($field != 'id') {
  4171. if (empty($mnethostid)) {
  4172. // If empty, we restrict to local users.
  4173. $mnethostid = $CFG->mnet_localhost_id;
  4174. }
  4175. }
  4176. if (!empty($mnethostid)) {
  4177. $params['mnethostid'] = $mnethostid;
  4178. $constraints .= " AND mnethostid = :mnethostid";
  4179. }
  4180. // Get all the basic user data.
  4181. if (! $user = $DB->get_record_select('user', $constraints, $params)) {
  4182. return false;
  4183. }
  4184. // Get various settings and preferences.
  4185. // Preload preference cache.
  4186. check_user_preferences_loaded($user);
  4187. // Load course enrolment related stuff.
  4188. $user->lastcourseaccess = array(); // During last session.
  4189. $user->currentcourseaccess = array(); // During current session.
  4190. if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
  4191. foreach ($lastaccesses as $lastaccess) {
  4192. $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
  4193. }
  4194. }
  4195. $sql = "SELECT g.id, g.courseid
  4196. FROM {groups} g, {groups_members} gm
  4197. WHERE gm.groupid=g.id AND gm.userid=?";
  4198. // This is a special hack to speedup calendar display.
  4199. $user->groupmember = array();
  4200. if (!isguestuser($user)) {
  4201. if ($groups = $DB->get_records_sql($sql, array($user->id))) {
  4202. foreach ($groups as $group) {
  4203. if (!array_key_exists($group->courseid, $user->groupmember)) {
  4204. $user->groupmember[$group->courseid] = array();
  4205. }
  4206. $user->groupmember[$group->courseid][$group->id] = $group->id;
  4207. }
  4208. }
  4209. }
  4210. // Add the custom profile fields to the user record.
  4211. $user->profile = array();
  4212. if (!isguestuser($user)) {
  4213. require_once($CFG->dirroot.'/user/profile/lib.php');
  4214. profile_load_custom_fields($user);
  4215. }
  4216. // Rewrite some variables if necessary.
  4217. if (!empty($user->description)) {
  4218. // No need to cart all of it around.
  4219. $user->description = true;
  4220. }
  4221. if (isguestuser($user)) {
  4222. // Guest language always same as site.
  4223. $user->lang = $CFG->lang;
  4224. // Name always in current language.
  4225. $user->firstname = get_string('guestuser');
  4226. $user->lastname = ' ';
  4227. }
  4228. return $user;
  4229. }
  4230. /**
  4231. * Validate a password against the configured password policy
  4232. *
  4233. * @param string $password the password to be checked against the password policy
  4234. * @param string $errmsg the error message to display when the password doesn't comply with the policy.
  4235. * @return bool true if the password is valid according to the policy. false otherwise.
  4236. */
  4237. function check_password_policy($password, &$errmsg) {
  4238. global $CFG;
  4239. if (empty($CFG->passwordpolicy)) {
  4240. return true;
  4241. }
  4242. $errmsg = '';
  4243. if (core_text::strlen($password) < $CFG->minpasswordlength) {
  4244. $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
  4245. }
  4246. if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
  4247. $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
  4248. }
  4249. if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
  4250. $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
  4251. }
  4252. if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
  4253. $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
  4254. }
  4255. if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
  4256. $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
  4257. }
  4258. if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
  4259. $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
  4260. }
  4261. if ($errmsg == '') {
  4262. return true;
  4263. } else {
  4264. return false;
  4265. }
  4266. }
  4267. /**
  4268. * When logging in, this function is run to set certain preferences for the current SESSION.
  4269. */
  4270. function set_login_session_preferences() {
  4271. global $SESSION;
  4272. $SESSION->justloggedin = true;
  4273. unset($SESSION->lang);
  4274. unset($SESSION->load_navigation_admin);
  4275. }
  4276. /**
  4277. * Delete a course, including all related data from the database, and any associated files.
  4278. *
  4279. * @param mixed $courseorid The id of the course or course object to delete.
  4280. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  4281. * @return bool true if all the removals succeeded. false if there were any failures. If this
  4282. * method returns false, some of the removals will probably have succeeded, and others
  4283. * failed, but you have no way of knowing which.
  4284. */
  4285. function delete_course($courseorid, $showfeedback = true) {
  4286. global $DB;
  4287. if (is_object($courseorid)) {
  4288. $courseid = $courseorid->id;
  4289. $course = $courseorid;
  4290. } else {
  4291. $courseid = $courseorid;
  4292. if (!$course = $DB->get_record('course', array('id' => $courseid))) {
  4293. return false;
  4294. }
  4295. }
  4296. $context = context_course::instance($courseid);
  4297. // Frontpage course can not be deleted!!
  4298. if ($courseid == SITEID) {
  4299. return false;
  4300. }
  4301. // Make the course completely empty.
  4302. remove_course_contents($courseid, $showfeedback);
  4303. // Delete the course and related context instance.
  4304. context_helper::delete_instance(CONTEXT_COURSE, $courseid);
  4305. $DB->delete_records("course", array("id" => $courseid));
  4306. $DB->delete_records("course_format_options", array("courseid" => $courseid));
  4307. // Trigger a course deleted event.
  4308. $event = \core\event\course_deleted::create(array(
  4309. 'objectid' => $course->id,
  4310. 'context' => $context,
  4311. 'other' => array(
  4312. 'shortname' => $course->shortname,
  4313. 'fullname' => $course->fullname,
  4314. 'idnumber' => $course->idnumber
  4315. )
  4316. ));
  4317. $event->add_record_snapshot('course', $course);
  4318. $event->trigger();
  4319. return true;
  4320. }
  4321. /**
  4322. * Clear a course out completely, deleting all content but don't delete the course itself.
  4323. *
  4324. * This function does not verify any permissions.
  4325. *
  4326. * Please note this function also deletes all user enrolments,
  4327. * enrolment instances and role assignments by default.
  4328. *
  4329. * $options:
  4330. * - 'keep_roles_and_enrolments' - false by default
  4331. * - 'keep_groups_and_groupings' - false by default
  4332. *
  4333. * @param int $courseid The id of the course that is being deleted
  4334. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  4335. * @param array $options extra options
  4336. * @return bool true if all the removals succeeded. false if there were any failures. If this
  4337. * method returns false, some of the removals will probably have succeeded, and others
  4338. * failed, but you have no way of knowing which.
  4339. */
  4340. function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
  4341. global $CFG, $DB, $OUTPUT;
  4342. require_once($CFG->libdir.'/badgeslib.php');
  4343. require_once($CFG->libdir.'/completionlib.php');
  4344. require_once($CFG->libdir.'/questionlib.php');
  4345. require_once($CFG->libdir.'/gradelib.php');
  4346. require_once($CFG->dirroot.'/group/lib.php');
  4347. require_once($CFG->dirroot.'/tag/coursetagslib.php');
  4348. require_once($CFG->dirroot.'/comment/lib.php');
  4349. require_once($CFG->dirroot.'/rating/lib.php');
  4350. require_once($CFG->dirroot.'/notes/lib.php');
  4351. // Handle course badges.
  4352. badges_handle_course_deletion($courseid);
  4353. // NOTE: these concatenated strings are suboptimal, but it is just extra info...
  4354. $strdeleted = get_string('deleted').' - ';
  4355. // Some crazy wishlist of stuff we should skip during purging of course content.
  4356. $options = (array)$options;
  4357. $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
  4358. $coursecontext = context_course::instance($courseid);
  4359. $fs = get_file_storage();
  4360. // Delete course completion information, this has to be done before grades and enrols.
  4361. $cc = new completion_info($course);
  4362. $cc->clear_criteria();
  4363. if ($showfeedback) {
  4364. echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
  4365. }
  4366. // Remove all data from gradebook - this needs to be done before course modules
  4367. // because while deleting this information, the system may need to reference
  4368. // the course modules that own the grades.
  4369. remove_course_grades($courseid, $showfeedback);
  4370. remove_grade_letters($coursecontext, $showfeedback);
  4371. // Delete course blocks in any all child contexts,
  4372. // they may depend on modules so delete them first.
  4373. $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
  4374. foreach ($childcontexts as $childcontext) {
  4375. blocks_delete_all_for_context($childcontext->id);
  4376. }
  4377. unset($childcontexts);
  4378. blocks_delete_all_for_context($coursecontext->id);
  4379. if ($showfeedback) {
  4380. echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
  4381. }
  4382. // Delete every instance of every module,
  4383. // this has to be done before deleting of course level stuff.
  4384. $locations = core_component::get_plugin_list('mod');
  4385. foreach ($locations as $modname => $moddir) {
  4386. if ($modname === 'NEWMODULE') {
  4387. continue;
  4388. }
  4389. if ($module = $DB->get_record('modules', array('name' => $modname))) {
  4390. include_once("$moddir/lib.php"); // Shows php warning only if plugin defective.
  4391. $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance.
  4392. $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon).
  4393. if ($instances = $DB->get_records($modname, array('course' => $course->id))) {
  4394. foreach ($instances as $instance) {
  4395. if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
  4396. // Delete activity context questions and question categories.
  4397. question_delete_activity($cm, $showfeedback);
  4398. }
  4399. if (function_exists($moddelete)) {
  4400. // This purges all module data in related tables, extra user prefs, settings, etc.
  4401. $moddelete($instance->id);
  4402. } else {
  4403. // NOTE: we should not allow installation of modules with missing delete support!
  4404. debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
  4405. $DB->delete_records($modname, array('id' => $instance->id));
  4406. }
  4407. if ($cm) {
  4408. // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
  4409. context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
  4410. $DB->delete_records('course_modules', array('id' => $cm->id));
  4411. }
  4412. }
  4413. }
  4414. if (function_exists($moddeletecourse)) {
  4415. // Execute ptional course cleanup callback.
  4416. $moddeletecourse($course, $showfeedback);
  4417. }
  4418. if ($instances and $showfeedback) {
  4419. echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
  4420. }
  4421. } else {
  4422. // Ooops, this module is not properly installed, force-delete it in the next block.
  4423. }
  4424. }
  4425. // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
  4426. // Remove all data from availability and completion tables that is associated
  4427. // with course-modules belonging to this course. Note this is done even if the
  4428. // features are not enabled now, in case they were enabled previously.
  4429. $DB->delete_records_select('course_modules_completion',
  4430. 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
  4431. array($courseid));
  4432. $DB->delete_records_select('course_modules_availability',
  4433. 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
  4434. array($courseid));
  4435. $DB->delete_records_select('course_modules_avail_fields',
  4436. 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
  4437. array($courseid));
  4438. // Remove course-module data.
  4439. $cms = $DB->get_records('course_modules', array('course' => $course->id));
  4440. foreach ($cms as $cm) {
  4441. if ($module = $DB->get_record('modules', array('id' => $cm->module))) {
  4442. try {
  4443. $DB->delete_records($module->name, array('id' => $cm->instance));
  4444. } catch (Exception $e) {
  4445. // Ignore weird or missing table problems.
  4446. }
  4447. }
  4448. context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
  4449. $DB->delete_records('course_modules', array('id' => $cm->id));
  4450. }
  4451. if ($showfeedback) {
  4452. echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
  4453. }
  4454. // Cleanup the rest of plugins.
  4455. $cleanuplugintypes = array('report', 'coursereport', 'format');
  4456. foreach ($cleanuplugintypes as $type) {
  4457. $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
  4458. foreach ($plugins as $plugin => $pluginfunction) {
  4459. $pluginfunction($course->id, $showfeedback);
  4460. }
  4461. if ($showfeedback) {
  4462. echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
  4463. }
  4464. }
  4465. // Delete questions and question categories.
  4466. question_delete_course($course, $showfeedback);
  4467. if ($showfeedback) {
  4468. echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
  4469. }
  4470. // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
  4471. $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
  4472. foreach ($childcontexts as $childcontext) {
  4473. $childcontext->delete();
  4474. }
  4475. unset($childcontexts);
  4476. // Remove all roles and enrolments by default.
  4477. if (empty($options['keep_roles_and_enrolments'])) {
  4478. // This hack is used in restore when deleting contents of existing course.
  4479. role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
  4480. enrol_course_delete($course);
  4481. if ($showfeedback) {
  4482. echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
  4483. }
  4484. }
  4485. // Delete any groups, removing members and grouping/course links first.
  4486. if (empty($options['keep_groups_and_groupings'])) {
  4487. groups_delete_groupings($course->id, $showfeedback);
  4488. groups_delete_groups($course->id, $showfeedback);
  4489. }
  4490. // Filters be gone!
  4491. filter_delete_all_for_context($coursecontext->id);
  4492. // Notes, you shall not pass!
  4493. note_delete_all($course->id);
  4494. // Die comments!
  4495. comment::delete_comments($coursecontext->id);
  4496. // Ratings are history too.
  4497. $delopt = new stdclass();
  4498. $delopt->contextid = $coursecontext->id;
  4499. $rm = new rating_manager();
  4500. $rm->delete_ratings($delopt);
  4501. // Delete course tags.
  4502. coursetag_delete_course_tags($course->id, $showfeedback);
  4503. // Delete calendar events.
  4504. $DB->delete_records('event', array('courseid' => $course->id));
  4505. $fs->delete_area_files($coursecontext->id, 'calendar');
  4506. // Delete all related records in other core tables that may have a courseid
  4507. // This array stores the tables that need to be cleared, as
  4508. // table_name => column_name that contains the course id.
  4509. $tablestoclear = array(
  4510. 'log' => 'course', // Course logs (NOTE: this might be changed in the future).
  4511. 'backup_courses' => 'courseid', // Scheduled backup stuff.
  4512. 'user_lastaccess' => 'courseid', // User access info.
  4513. );
  4514. foreach ($tablestoclear as $table => $col) {
  4515. $DB->delete_records($table, array($col => $course->id));
  4516. }
  4517. // Delete all course backup files.
  4518. $fs->delete_area_files($coursecontext->id, 'backup');
  4519. // Cleanup course record - remove links to deleted stuff.
  4520. $oldcourse = new stdClass();
  4521. $oldcourse->id = $course->id;
  4522. $oldcourse->summary = '';
  4523. $oldcourse->cacherev = 0;
  4524. $oldcourse->legacyfiles = 0;
  4525. $oldcourse->enablecompletion = 0;
  4526. if (!empty($options['keep_groups_and_groupings'])) {
  4527. $oldcourse->defaultgroupingid = 0;
  4528. }
  4529. $DB->update_record('course', $oldcourse);
  4530. // Delete course sections and availability options.
  4531. $DB->delete_records_select('course_sections_availability',
  4532. 'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
  4533. array($course->id));
  4534. $DB->delete_records_select('course_sections_avail_fields',
  4535. 'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
  4536. array($course->id));
  4537. $DB->delete_records('course_sections', array('course' => $course->id));
  4538. // Delete legacy, section and any other course files.
  4539. $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
  4540. // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
  4541. if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
  4542. // Easy, do not delete the context itself...
  4543. $coursecontext->delete_content();
  4544. } else {
  4545. // Hack alert!!!!
  4546. // We can not drop all context stuff because it would bork enrolments and roles,
  4547. // there might be also files used by enrol plugins...
  4548. }
  4549. // Delete legacy files - just in case some files are still left there after conversion to new file api,
  4550. // also some non-standard unsupported plugins may try to store something there.
  4551. fulldelete($CFG->dataroot.'/'.$course->id);
  4552. // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
  4553. $cachemodinfo = cache::make('core', 'coursemodinfo');
  4554. $cachemodinfo->delete($courseid);
  4555. // Trigger a course content deleted event.
  4556. $event = \core\event\course_content_deleted::create(array(
  4557. 'objectid' => $course->id,
  4558. 'context' => $coursecontext,
  4559. 'other' => array('shortname' => $course->shortname,
  4560. 'fullname' => $course->fullname,
  4561. 'options' => $options) // Passing this for legacy reasons.
  4562. ));
  4563. $event->add_record_snapshot('course', $course);
  4564. $event->trigger();
  4565. return true;
  4566. }
  4567. /**
  4568. * Change dates in module - used from course reset.
  4569. *
  4570. * @param string $modname forum, assignment, etc
  4571. * @param array $fields array of date fields from mod table
  4572. * @param int $timeshift time difference
  4573. * @param int $courseid
  4574. * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
  4575. * @return bool success
  4576. */
  4577. function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
  4578. global $CFG, $DB;
  4579. include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
  4580. $return = true;
  4581. $params = array($timeshift, $courseid);
  4582. foreach ($fields as $field) {
  4583. $updatesql = "UPDATE {".$modname."}
  4584. SET $field = $field + ?
  4585. WHERE course=? AND $field<>0";
  4586. if ($modid) {
  4587. $updatesql .= ' AND id=?';
  4588. $params[] = $modid;
  4589. }
  4590. $return = $DB->execute($updatesql, $params) && $return;
  4591. }
  4592. $refreshfunction = $modname.'_refresh_events';
  4593. if (function_exists($refreshfunction)) {
  4594. $refreshfunction($courseid);
  4595. }
  4596. return $return;
  4597. }
  4598. /**
  4599. * This function will empty a course of user data.
  4600. * It will retain the activities and the structure of the course.
  4601. *
  4602. * @param object $data an object containing all the settings including courseid (without magic quotes)
  4603. * @return array status array of array component, item, error
  4604. */
  4605. function reset_course_userdata($data) {
  4606. global $CFG, $DB;
  4607. require_once($CFG->libdir.'/gradelib.php');
  4608. require_once($CFG->libdir.'/completionlib.php');
  4609. require_once($CFG->dirroot.'/group/lib.php');
  4610. $data->courseid = $data->id;
  4611. $context = context_course::instance($data->courseid);
  4612. $eventparams = array(
  4613. 'context' => $context,
  4614. 'courseid' => $data->id,
  4615. 'other' => array(
  4616. 'reset_options' => (array) $data
  4617. )
  4618. );
  4619. $event = \core\event\course_reset_started::create($eventparams);
  4620. $event->trigger();
  4621. // Calculate the time shift of dates.
  4622. if (!empty($data->reset_start_date)) {
  4623. // Time part of course startdate should be zero.
  4624. $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
  4625. } else {
  4626. $data->timeshift = 0;
  4627. }
  4628. // Result array: component, item, error.
  4629. $status = array();
  4630. // Start the resetting.
  4631. $componentstr = get_string('general');
  4632. // Move the course start time.
  4633. if (!empty($data->reset_start_date) and $data->timeshift) {
  4634. // Change course start data.
  4635. $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
  4636. // Update all course and group events - do not move activity events.
  4637. $updatesql = "UPDATE {event}
  4638. SET timestart = timestart + ?
  4639. WHERE courseid=? AND instance=0";
  4640. $DB->execute($updatesql, array($data->timeshift, $data->courseid));
  4641. $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
  4642. }
  4643. if (!empty($data->reset_logs)) {
  4644. $DB->delete_records('log', array('course' => $data->courseid));
  4645. $status[] = array('component' => $componentstr, 'item' => get_string('deletelogs'), 'error' => false);
  4646. }
  4647. if (!empty($data->reset_events)) {
  4648. $DB->delete_records('event', array('courseid' => $data->courseid));
  4649. $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
  4650. }
  4651. if (!empty($data->reset_notes)) {
  4652. require_once($CFG->dirroot.'/notes/lib.php');
  4653. note_delete_all($data->courseid);
  4654. $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
  4655. }
  4656. if (!empty($data->delete_blog_associations)) {
  4657. require_once($CFG->dirroot.'/blog/lib.php');
  4658. blog_remove_associations_for_course($data->courseid);
  4659. $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
  4660. }
  4661. if (!empty($data->reset_completion)) {
  4662. // Delete course and activity completion information.
  4663. $course = $DB->get_record('course', array('id' => $data->courseid));
  4664. $cc = new completion_info($course);
  4665. $cc->delete_all_completion_data();
  4666. $status[] = array('component' => $componentstr,
  4667. 'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
  4668. }
  4669. $componentstr = get_string('roles');
  4670. if (!empty($data->reset_roles_overrides)) {
  4671. $children = $context->get_child_contexts();
  4672. foreach ($children as $child) {
  4673. $DB->delete_records('role_capabilities', array('contextid' => $child->id));
  4674. }
  4675. $DB->delete_records('role_capabilities', array('contextid' => $context->id));
  4676. // Force refresh for logged in users.
  4677. $context->mark_dirty();
  4678. $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
  4679. }
  4680. if (!empty($data->reset_roles_local)) {
  4681. $children = $context->get_child_contexts();
  4682. foreach ($children as $child) {
  4683. role_unassign_all(array('contextid' => $child->id));
  4684. }
  4685. // Force refresh for logged in users.
  4686. $context->mark_dirty();
  4687. $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
  4688. }
  4689. // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
  4690. $data->unenrolled = array();
  4691. if (!empty($data->unenrol_users)) {
  4692. $plugins = enrol_get_plugins(true);
  4693. $instances = enrol_get_instances($data->courseid, true);
  4694. foreach ($instances as $key => $instance) {
  4695. if (!isset($plugins[$instance->enrol])) {
  4696. unset($instances[$key]);
  4697. continue;
  4698. }
  4699. }
  4700. foreach ($data->unenrol_users as $withroleid) {
  4701. if ($withroleid) {
  4702. $sql = "SELECT ue.*
  4703. FROM {user_enrolments} ue
  4704. JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
  4705. JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
  4706. JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
  4707. $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
  4708. } else {
  4709. // Without any role assigned at course context.
  4710. $sql = "SELECT ue.*
  4711. FROM {user_enrolments} ue
  4712. JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
  4713. JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
  4714. LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
  4715. WHERE ra.id IS null";
  4716. $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
  4717. }
  4718. $rs = $DB->get_recordset_sql($sql, $params);
  4719. foreach ($rs as $ue) {
  4720. if (!isset($instances[$ue->enrolid])) {
  4721. continue;
  4722. }
  4723. $instance = $instances[$ue->enrolid];
  4724. $plugin = $plugins[$instance->enrol];
  4725. if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
  4726. continue;
  4727. }
  4728. $plugin->unenrol_user($instance, $ue->userid);
  4729. $data->unenrolled[$ue->userid] = $ue->userid;
  4730. }
  4731. $rs->close();
  4732. }
  4733. }
  4734. if (!empty($data->unenrolled)) {
  4735. $status[] = array(
  4736. 'component' => $componentstr,
  4737. 'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
  4738. 'error' => false
  4739. );
  4740. }
  4741. $componentstr = get_string('groups');
  4742. // Remove all group members.
  4743. if (!empty($data->reset_groups_members)) {
  4744. groups_delete_group_members($data->courseid);
  4745. $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
  4746. }
  4747. // Remove all groups.
  4748. if (!empty($data->reset_groups_remove)) {
  4749. groups_delete_groups($data->courseid, false);
  4750. $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
  4751. }
  4752. // Remove all grouping members.
  4753. if (!empty($data->reset_groupings_members)) {
  4754. groups_delete_groupings_groups($data->courseid, false);
  4755. $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
  4756. }
  4757. // Remove all groupings.
  4758. if (!empty($data->reset_groupings_remove)) {
  4759. groups_delete_groupings($data->courseid, false);
  4760. $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
  4761. }
  4762. // Look in every instance of every module for data to delete.
  4763. $unsupportedmods = array();
  4764. if ($allmods = $DB->get_records('modules') ) {
  4765. foreach ($allmods as $mod) {
  4766. $modname = $mod->name;
  4767. $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
  4768. $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data.
  4769. if (file_exists($modfile)) {
  4770. if (!$DB->count_records($modname, array('course' => $data->courseid))) {
  4771. continue; // Skip mods with no instances.
  4772. }
  4773. include_once($modfile);
  4774. if (function_exists($moddeleteuserdata)) {
  4775. $modstatus = $moddeleteuserdata($data);
  4776. if (is_array($modstatus)) {
  4777. $status = array_merge($status, $modstatus);
  4778. } else {
  4779. debugging('Module '.$modname.' returned incorrect staus - must be an array!');
  4780. }
  4781. } else {
  4782. $unsupportedmods[] = $mod;
  4783. }
  4784. } else {
  4785. debugging('Missing lib.php in '.$modname.' module!');
  4786. }
  4787. }
  4788. }
  4789. // Mention unsupported mods.
  4790. if (!empty($unsupportedmods)) {
  4791. foreach ($unsupportedmods as $mod) {
  4792. $status[] = array(
  4793. 'component' => get_string('modulenameplural', $mod->name),
  4794. 'item' => '',
  4795. 'error' => get_string('resetnotimplemented')
  4796. );
  4797. }
  4798. }
  4799. $componentstr = get_string('gradebook', 'grades');
  4800. // Reset gradebook,.
  4801. if (!empty($data->reset_gradebook_items)) {
  4802. remove_course_grades($data->courseid, false);
  4803. grade_grab_course_grades($data->courseid);
  4804. grade_regrade_final_grades($data->courseid);
  4805. $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
  4806. } else if (!empty($data->reset_gradebook_grades)) {
  4807. grade_course_reset($data->courseid);
  4808. $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
  4809. }
  4810. // Reset comments.
  4811. if (!empty($data->reset_comments)) {
  4812. require_once($CFG->dirroot.'/comment/lib.php');
  4813. comment::reset_course_page_comments($context);
  4814. }
  4815. $event = \core\event\course_reset_ended::create($eventparams);
  4816. $event->trigger();
  4817. return $status;
  4818. }
  4819. /**
  4820. * Generate an email processing address.
  4821. *
  4822. * @param int $modid
  4823. * @param string $modargs
  4824. * @return string Returns email processing address
  4825. */
  4826. function generate_email_processing_address($modid, $modargs) {
  4827. global $CFG;
  4828. $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
  4829. return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
  4830. }
  4831. /**
  4832. * ?
  4833. *
  4834. * @todo Finish documenting this function
  4835. *
  4836. * @param string $modargs
  4837. * @param string $body Currently unused
  4838. */
  4839. function moodle_process_email($modargs, $body) {
  4840. global $DB;
  4841. // The first char should be an unencoded letter. We'll take this as an action.
  4842. switch ($modargs{0}) {
  4843. case 'B': { // Bounce.
  4844. list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
  4845. if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
  4846. // Check the half md5 of their email.
  4847. $md5check = substr(md5($user->email), 0, 16);
  4848. if ($md5check == substr($modargs, -16)) {
  4849. set_bounce_count($user);
  4850. }
  4851. // Else maybe they've already changed it?
  4852. }
  4853. }
  4854. break;
  4855. // Maybe more later?
  4856. }
  4857. }
  4858. // CORRESPONDENCE.
  4859. /**
  4860. * Get mailer instance, enable buffering, flush buffer or disable buffering.
  4861. *
  4862. * @param string $action 'get', 'buffer', 'close' or 'flush'
  4863. * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
  4864. */
  4865. function get_mailer($action='get') {
  4866. global $CFG;
  4867. /** @var moodle_phpmailer $mailer */
  4868. static $mailer = null;
  4869. static $counter = 0;
  4870. if (!isset($CFG->smtpmaxbulk)) {
  4871. $CFG->smtpmaxbulk = 1;
  4872. }
  4873. if ($action == 'get') {
  4874. $prevkeepalive = false;
  4875. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  4876. if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
  4877. $counter++;
  4878. // Reset the mailer.
  4879. $mailer->Priority = 3;
  4880. $mailer->CharSet = 'UTF-8'; // Our default.
  4881. $mailer->ContentType = "text/plain";
  4882. $mailer->Encoding = "8bit";
  4883. $mailer->From = "root@localhost";
  4884. $mailer->FromName = "Root User";
  4885. $mailer->Sender = "";
  4886. $mailer->Subject = "";
  4887. $mailer->Body = "";
  4888. $mailer->AltBody = "";
  4889. $mailer->ConfirmReadingTo = "";
  4890. $mailer->clearAllRecipients();
  4891. $mailer->clearReplyTos();
  4892. $mailer->clearAttachments();
  4893. $mailer->clearCustomHeaders();
  4894. return $mailer;
  4895. }
  4896. $prevkeepalive = $mailer->SMTPKeepAlive;
  4897. get_mailer('flush');
  4898. }
  4899. require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
  4900. $mailer = new moodle_phpmailer();
  4901. $counter = 1;
  4902. if ($CFG->smtphosts == 'qmail') {
  4903. // Use Qmail system.
  4904. $mailer->isQmail();
  4905. } else if (empty($CFG->smtphosts)) {
  4906. // Use PHP mail() = sendmail.
  4907. $mailer->isMail();
  4908. } else {
  4909. // Use SMTP directly.
  4910. $mailer->isSMTP();
  4911. if (!empty($CFG->debugsmtp)) {
  4912. $mailer->SMTPDebug = true;
  4913. }
  4914. // Specify main and backup servers.
  4915. $mailer->Host = $CFG->smtphosts;
  4916. // Specify secure connection protocol.
  4917. $mailer->SMTPSecure = $CFG->smtpsecure;
  4918. // Use previous keepalive.
  4919. $mailer->SMTPKeepAlive = $prevkeepalive;
  4920. if ($CFG->smtpuser) {
  4921. // Use SMTP authentication.
  4922. $mailer->SMTPAuth = true;
  4923. $mailer->Username = $CFG->smtpuser;
  4924. $mailer->Password = $CFG->smtppass;
  4925. }
  4926. }
  4927. return $mailer;
  4928. }
  4929. $nothing = null;
  4930. // Keep smtp session open after sending.
  4931. if ($action == 'buffer') {
  4932. if (!empty($CFG->smtpmaxbulk)) {
  4933. get_mailer('flush');
  4934. $m = get_mailer();
  4935. if ($m->Mailer == 'smtp') {
  4936. $m->SMTPKeepAlive = true;
  4937. }
  4938. }
  4939. return $nothing;
  4940. }
  4941. // Close smtp session, but continue buffering.
  4942. if ($action == 'flush') {
  4943. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  4944. if (!empty($mailer->SMTPDebug)) {
  4945. echo '<pre>'."\n";
  4946. }
  4947. $mailer->SmtpClose();
  4948. if (!empty($mailer->SMTPDebug)) {
  4949. echo '</pre>';
  4950. }
  4951. }
  4952. return $nothing;
  4953. }
  4954. // Close smtp session, do not buffer anymore.
  4955. if ($action == 'close') {
  4956. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  4957. get_mailer('flush');
  4958. $mailer->SMTPKeepAlive = false;
  4959. }
  4960. $mailer = null; // Better force new instance.
  4961. return $nothing;
  4962. }
  4963. }
  4964. /**
  4965. * Send an email to a specified user
  4966. *
  4967. * @param stdClass $user A {@link $USER} object
  4968. * @param stdClass $from A {@link $USER} object
  4969. * @param string $subject plain text subject line of the email
  4970. * @param string $messagetext plain text version of the message
  4971. * @param string $messagehtml complete html version of the message (optional)
  4972. * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
  4973. * @param string $attachname the name of the file (extension indicates MIME)
  4974. * @param bool $usetrueaddress determines whether $from email address should
  4975. * be sent out. Will be overruled by user profile setting for maildisplay
  4976. * @param string $replyto Email address to reply to
  4977. * @param string $replytoname Name of reply to recipient
  4978. * @param int $wordwrapwidth custom word wrap width, default 79
  4979. * @return bool Returns true if mail was sent OK and false if there was an error.
  4980. */
  4981. function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
  4982. $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
  4983. global $CFG;
  4984. if (empty($user) or empty($user->id)) {
  4985. debugging('Can not send email to null user', DEBUG_DEVELOPER);
  4986. return false;
  4987. }
  4988. if (empty($user->email)) {
  4989. debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
  4990. return false;
  4991. }
  4992. if (!empty($user->deleted)) {
  4993. debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
  4994. return false;
  4995. }
  4996. if (!empty($CFG->noemailever)) {
  4997. // Hidden setting for development sites, set in config.php if needed.
  4998. debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
  4999. return true;
  5000. }
  5001. if (!empty($CFG->divertallemailsto)) {
  5002. $subject = "[DIVERTED {$user->email}] $subject";
  5003. $user = clone($user);
  5004. $user->email = $CFG->divertallemailsto;
  5005. }
  5006. // Skip mail to suspended users.
  5007. if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
  5008. return true;
  5009. }
  5010. if (!validate_email($user->email)) {
  5011. // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
  5012. $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
  5013. error_log($invalidemail);
  5014. if (CLI_SCRIPT) {
  5015. mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
  5016. }
  5017. return false;
  5018. }
  5019. if (over_bounce_threshold($user)) {
  5020. $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
  5021. error_log($bouncemsg);
  5022. if (CLI_SCRIPT) {
  5023. mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
  5024. }
  5025. return false;
  5026. }
  5027. // If the user is a remote mnet user, parse the email text for URL to the
  5028. // wwwroot and modify the url to direct the user's browser to login at their
  5029. // home site (identity provider - idp) before hitting the link itself.
  5030. if (is_mnet_remote_user($user)) {
  5031. require_once($CFG->dirroot.'/mnet/lib.php');
  5032. $jumpurl = mnet_get_idp_jump_url($user);
  5033. $callback = partial('mnet_sso_apply_indirection', $jumpurl);
  5034. $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
  5035. $callback,
  5036. $messagetext);
  5037. $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
  5038. $callback,
  5039. $messagehtml);
  5040. }
  5041. $mail = get_mailer();
  5042. if (!empty($mail->SMTPDebug)) {
  5043. echo '<pre>' . "\n";
  5044. }
  5045. $temprecipients = array();
  5046. $tempreplyto = array();
  5047. $supportuser = core_user::get_support_user();
  5048. // Make up an email address for handling bounces.
  5049. if (!empty($CFG->handlebounces)) {
  5050. $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
  5051. $mail->Sender = generate_email_processing_address(0, $modargs);
  5052. } else {
  5053. $mail->Sender = $supportuser->email;
  5054. }
  5055. if (!empty($CFG->emailonlyfromnoreplyaddress)) {
  5056. $usetrueaddress = false;
  5057. if (empty($replyto) && $from->maildisplay) {
  5058. $replyto = $from->email;
  5059. $replytoname = fullname($from);
  5060. }
  5061. }
  5062. if (is_string($from)) { // So we can pass whatever we want if there is need.
  5063. $mail->From = $CFG->noreplyaddress;
  5064. $mail->FromName = $from;
  5065. } else if ($usetrueaddress and $from->maildisplay) {
  5066. $mail->From = $from->email;
  5067. $mail->FromName = fullname($from);
  5068. } else {
  5069. $mail->From = $CFG->noreplyaddress;
  5070. $mail->FromName = fullname($from);
  5071. if (empty($replyto)) {
  5072. $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
  5073. }
  5074. }
  5075. if (!empty($replyto)) {
  5076. $tempreplyto[] = array($replyto, $replytoname);
  5077. }
  5078. $mail->Subject = substr($subject, 0, 900);
  5079. $temprecipients[] = array($user->email, fullname($user));
  5080. // Set word wrap.
  5081. $mail->WordWrap = $wordwrapwidth;
  5082. if (!empty($from->customheaders)) {
  5083. // Add custom headers.
  5084. if (is_array($from->customheaders)) {
  5085. foreach ($from->customheaders as $customheader) {
  5086. $mail->addCustomHeader($customheader);
  5087. }
  5088. } else {
  5089. $mail->addCustomHeader($from->customheaders);
  5090. }
  5091. }
  5092. if (!empty($from->priority)) {
  5093. $mail->Priority = $from->priority;
  5094. }
  5095. if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
  5096. // Don't ever send HTML to users who don't want it.
  5097. $mail->isHTML(true);
  5098. $mail->Encoding = 'quoted-printable';
  5099. $mail->Body = $messagehtml;
  5100. $mail->AltBody = "\n$messagetext\n";
  5101. } else {
  5102. $mail->IsHTML(false);
  5103. $mail->Body = "\n$messagetext\n";
  5104. }
  5105. if ($attachment && $attachname) {
  5106. if (preg_match( "~\\.\\.~" , $attachment )) {
  5107. // Security check for ".." in dir path.
  5108. $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
  5109. $mail->addStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
  5110. } else {
  5111. require_once($CFG->libdir.'/filelib.php');
  5112. $mimetype = mimeinfo('type', $attachname);
  5113. $mail->addAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
  5114. }
  5115. }
  5116. // Check if the email should be sent in an other charset then the default UTF-8.
  5117. if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
  5118. // Use the defined site mail charset or eventually the one preferred by the recipient.
  5119. $charset = $CFG->sitemailcharset;
  5120. if (!empty($CFG->allowusermailcharset)) {
  5121. if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
  5122. $charset = $useremailcharset;
  5123. }
  5124. }
  5125. // Convert all the necessary strings if the charset is supported.
  5126. $charsets = get_list_of_charsets();
  5127. unset($charsets['UTF-8']);
  5128. if (in_array($charset, $charsets)) {
  5129. $mail->CharSet = $charset;
  5130. $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
  5131. $mail->Subject = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
  5132. $mail->Body = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
  5133. $mail->AltBody = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
  5134. foreach ($temprecipients as $key => $values) {
  5135. $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
  5136. }
  5137. foreach ($tempreplyto as $key => $values) {
  5138. $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
  5139. }
  5140. }
  5141. }
  5142. foreach ($temprecipients as $values) {
  5143. $mail->addAddress($values[0], $values[1]);
  5144. }
  5145. foreach ($tempreplyto as $values) {
  5146. $mail->addReplyTo($values[0], $values[1]);
  5147. }
  5148. if ($mail->send()) {
  5149. set_send_count($user);
  5150. if (!empty($mail->SMTPDebug)) {
  5151. echo '</pre>';
  5152. }
  5153. return true;
  5154. } else {
  5155. add_to_log(SITEID, 'library', 'mailer', qualified_me(), 'ERROR: '. $mail->ErrorInfo);
  5156. if (CLI_SCRIPT) {
  5157. mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
  5158. }
  5159. if (!empty($mail->SMTPDebug)) {
  5160. echo '</pre>';
  5161. }
  5162. return false;
  5163. }
  5164. }
  5165. /**
  5166. * Generate a signoff for emails based on support settings
  5167. *
  5168. * @return string
  5169. */
  5170. function generate_email_signoff() {
  5171. global $CFG;
  5172. $signoff = "\n";
  5173. if (!empty($CFG->supportname)) {
  5174. $signoff .= $CFG->supportname."\n";
  5175. }
  5176. if (!empty($CFG->supportemail)) {
  5177. $signoff .= $CFG->supportemail."\n";
  5178. }
  5179. if (!empty($CFG->supportpage)) {
  5180. $signoff .= $CFG->supportpage."\n";
  5181. }
  5182. return $signoff;
  5183. }
  5184. /**
  5185. * Sets specified user's password and send the new password to the user via email.
  5186. *
  5187. * @param stdClass $user A {@link $USER} object
  5188. * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
  5189. * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
  5190. */
  5191. function setnew_password_and_mail($user, $fasthash = false) {
  5192. global $CFG, $DB;
  5193. // We try to send the mail in language the user understands,
  5194. // unfortunately the filter_string() does not support alternative langs yet
  5195. // so multilang will not work properly for site->fullname.
  5196. $lang = empty($user->lang) ? $CFG->lang : $user->lang;
  5197. $site = get_site();
  5198. $supportuser = core_user::get_support_user();
  5199. $newpassword = generate_password();
  5200. $hashedpassword = hash_internal_user_password($newpassword, $fasthash);
  5201. $DB->set_field('user', 'password', $hashedpassword, array('id' => $user->id));
  5202. $user->password = $hashedpassword;
  5203. // Trigger event.
  5204. $event = \core\event\user_updated::create(array(
  5205. 'objectid' => $user->id,
  5206. 'context' => context_user::instance($user->id)
  5207. ));
  5208. $event->add_record_snapshot('user', $user);
  5209. $event->trigger();
  5210. $a = new stdClass();
  5211. $a->firstname = fullname($user, true);
  5212. $a->sitename = format_string($site->fullname);
  5213. $a->username = $user->username;
  5214. $a->newpassword = $newpassword;
  5215. $a->link = $CFG->wwwroot .'/login/';
  5216. $a->signoff = generate_email_signoff();
  5217. $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
  5218. $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
  5219. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5220. return email_to_user($user, $supportuser, $subject, $message);
  5221. }
  5222. /**
  5223. * Resets specified user's password and send the new password to the user via email.
  5224. *
  5225. * @param stdClass $user A {@link $USER} object
  5226. * @return bool Returns true if mail was sent OK and false if there was an error.
  5227. */
  5228. function reset_password_and_mail($user) {
  5229. global $CFG;
  5230. $site = get_site();
  5231. $supportuser = core_user::get_support_user();
  5232. $userauth = get_auth_plugin($user->auth);
  5233. if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
  5234. trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
  5235. return false;
  5236. }
  5237. $newpassword = generate_password();
  5238. if (!$userauth->user_update_password($user, $newpassword)) {
  5239. print_error("cannotsetpassword");
  5240. }
  5241. $a = new stdClass();
  5242. $a->firstname = $user->firstname;
  5243. $a->lastname = $user->lastname;
  5244. $a->sitename = format_string($site->fullname);
  5245. $a->username = $user->username;
  5246. $a->newpassword = $newpassword;
  5247. $a->link = $CFG->httpswwwroot .'/login/change_password.php';
  5248. $a->signoff = generate_email_signoff();
  5249. $message = get_string('newpasswordtext', '', $a);
  5250. $subject = format_string($site->fullname) .': '. get_string('changedpassword');
  5251. unset_user_preference('create_password', $user); // Prevent cron from generating the password.
  5252. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5253. return email_to_user($user, $supportuser, $subject, $message);
  5254. }
  5255. /**
  5256. * Send email to specified user with confirmation text and activation link.
  5257. *
  5258. * @param stdClass $user A {@link $USER} object
  5259. * @return bool Returns true if mail was sent OK and false if there was an error.
  5260. */
  5261. function send_confirmation_email($user) {
  5262. global $CFG;
  5263. $site = get_site();
  5264. $supportuser = core_user::get_support_user();
  5265. $data = new stdClass();
  5266. $data->firstname = fullname($user);
  5267. $data->sitename = format_string($site->fullname);
  5268. $data->admin = generate_email_signoff();
  5269. $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
  5270. $username = urlencode($user->username);
  5271. $username = str_replace('.', '%2E', $username); // Prevent problems with trailing dots.
  5272. $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
  5273. $message = get_string('emailconfirmation', '', $data);
  5274. $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
  5275. $user->mailformat = 1; // Always send HTML version as well.
  5276. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5277. return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
  5278. }
  5279. /**
  5280. * Sends a password change confirmation email.
  5281. *
  5282. * @param stdClass $user A {@link $USER} object
  5283. * @param stdClass $resetrecord An object tracking metadata regarding password reset request
  5284. * @return bool Returns true if mail was sent OK and false if there was an error.
  5285. */
  5286. function send_password_change_confirmation_email($user, $resetrecord) {
  5287. global $CFG;
  5288. $site = get_site();
  5289. $supportuser = core_user::get_support_user();
  5290. $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
  5291. $data = new stdClass();
  5292. $data->firstname = $user->firstname;
  5293. $data->lastname = $user->lastname;
  5294. $data->username = $user->username;
  5295. $data->sitename = format_string($site->fullname);
  5296. $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
  5297. $data->admin = generate_email_signoff();
  5298. $data->resetminutes = $pwresetmins;
  5299. $message = get_string('emailresetconfirmation', '', $data);
  5300. $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
  5301. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5302. return email_to_user($user, $supportuser, $subject, $message);
  5303. }
  5304. /**
  5305. * Sends an email containinginformation on how to change your password.
  5306. *
  5307. * @param stdClass $user A {@link $USER} object
  5308. * @return bool Returns true if mail was sent OK and false if there was an error.
  5309. */
  5310. function send_password_change_info($user) {
  5311. global $CFG;
  5312. $site = get_site();
  5313. $supportuser = core_user::get_support_user();
  5314. $systemcontext = context_system::instance();
  5315. $data = new stdClass();
  5316. $data->firstname = $user->firstname;
  5317. $data->lastname = $user->lastname;
  5318. $data->sitename = format_string($site->fullname);
  5319. $data->admin = generate_email_signoff();
  5320. $userauth = get_auth_plugin($user->auth);
  5321. if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
  5322. $message = get_string('emailpasswordchangeinfodisabled', '', $data);
  5323. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  5324. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5325. return email_to_user($user, $supportuser, $subject, $message);
  5326. }
  5327. if ($userauth->can_change_password() and $userauth->change_password_url()) {
  5328. // We have some external url for password changing.
  5329. $data->link .= $userauth->change_password_url();
  5330. } else {
  5331. // No way to change password, sorry.
  5332. $data->link = '';
  5333. }
  5334. if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
  5335. $message = get_string('emailpasswordchangeinfo', '', $data);
  5336. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  5337. } else {
  5338. $message = get_string('emailpasswordchangeinfofail', '', $data);
  5339. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  5340. }
  5341. // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
  5342. return email_to_user($user, $supportuser, $subject, $message);
  5343. }
  5344. /**
  5345. * Check that an email is allowed. It returns an error message if there was a problem.
  5346. *
  5347. * @param string $email Content of email
  5348. * @return string|false
  5349. */
  5350. function email_is_not_allowed($email) {
  5351. global $CFG;
  5352. if (!empty($CFG->allowemailaddresses)) {
  5353. $allowed = explode(' ', $CFG->allowemailaddresses);
  5354. foreach ($allowed as $allowedpattern) {
  5355. $allowedpattern = trim($allowedpattern);
  5356. if (!$allowedpattern) {
  5357. continue;
  5358. }
  5359. if (strpos($allowedpattern, '.') === 0) {
  5360. if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
  5361. // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
  5362. return false;
  5363. }
  5364. } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
  5365. return false;
  5366. }
  5367. }
  5368. return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
  5369. } else if (!empty($CFG->denyemailaddresses)) {
  5370. $denied = explode(' ', $CFG->denyemailaddresses);
  5371. foreach ($denied as $deniedpattern) {
  5372. $deniedpattern = trim($deniedpattern);
  5373. if (!$deniedpattern) {
  5374. continue;
  5375. }
  5376. if (strpos($deniedpattern, '.') === 0) {
  5377. if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
  5378. // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
  5379. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  5380. }
  5381. } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
  5382. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  5383. }
  5384. }
  5385. }
  5386. return false;
  5387. }
  5388. // FILE HANDLING.
  5389. /**
  5390. * Returns local file storage instance
  5391. *
  5392. * @return file_storage
  5393. */
  5394. function get_file_storage() {
  5395. global $CFG;
  5396. static $fs = null;
  5397. if ($fs) {
  5398. return $fs;
  5399. }
  5400. require_once("$CFG->libdir/filelib.php");
  5401. if (isset($CFG->filedir)) {
  5402. $filedir = $CFG->filedir;
  5403. } else {
  5404. $filedir = $CFG->dataroot.'/filedir';
  5405. }
  5406. if (isset($CFG->trashdir)) {
  5407. $trashdirdir = $CFG->trashdir;
  5408. } else {
  5409. $trashdirdir = $CFG->dataroot.'/trashdir';
  5410. }
  5411. $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
  5412. return $fs;
  5413. }
  5414. /**
  5415. * Returns local file storage instance
  5416. *
  5417. * @return file_browser
  5418. */
  5419. function get_file_browser() {
  5420. global $CFG;
  5421. static $fb = null;
  5422. if ($fb) {
  5423. return $fb;
  5424. }
  5425. require_once("$CFG->libdir/filelib.php");
  5426. $fb = new file_browser();
  5427. return $fb;
  5428. }
  5429. /**
  5430. * Returns file packer
  5431. *
  5432. * @param string $mimetype default application/zip
  5433. * @return file_packer
  5434. */
  5435. function get_file_packer($mimetype='application/zip') {
  5436. global $CFG;
  5437. static $fp = array();
  5438. if (isset($fp[$mimetype])) {
  5439. return $fp[$mimetype];
  5440. }
  5441. switch ($mimetype) {
  5442. case 'application/zip':
  5443. case 'application/vnd.moodle.profiling':
  5444. $classname = 'zip_packer';
  5445. break;
  5446. case 'application/x-gzip' :
  5447. $classname = 'tgz_packer';
  5448. break;
  5449. case 'application/vnd.moodle.backup':
  5450. $classname = 'mbz_packer';
  5451. break;
  5452. default:
  5453. return false;
  5454. }
  5455. require_once("$CFG->libdir/filestorage/$classname.php");
  5456. $fp[$mimetype] = new $classname();
  5457. return $fp[$mimetype];
  5458. }
  5459. /**
  5460. * Returns current name of file on disk if it exists.
  5461. *
  5462. * @param string $newfile File to be verified
  5463. * @return string Current name of file on disk if true
  5464. */
  5465. function valid_uploaded_file($newfile) {
  5466. if (empty($newfile)) {
  5467. return '';
  5468. }
  5469. if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
  5470. return $newfile['tmp_name'];
  5471. } else {
  5472. return '';
  5473. }
  5474. }
  5475. /**
  5476. * Returns the maximum size for uploading files.
  5477. *
  5478. * There are seven possible upload limits:
  5479. * 1. in Apache using LimitRequestBody (no way of checking or changing this)
  5480. * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
  5481. * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
  5482. * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
  5483. * 5. by the Moodle admin in $CFG->maxbytes
  5484. * 6. by the teacher in the current course $course->maxbytes
  5485. * 7. by the teacher for the current module, eg $assignment->maxbytes
  5486. *
  5487. * These last two are passed to this function as arguments (in bytes).
  5488. * Anything defined as 0 is ignored.
  5489. * The smallest of all the non-zero numbers is returned.
  5490. *
  5491. * @todo Finish documenting this function
  5492. *
  5493. * @param int $sitebytes Set maximum size
  5494. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5495. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5496. * @return int The maximum size for uploading files.
  5497. */
  5498. function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
  5499. if (! $filesize = ini_get('upload_max_filesize')) {
  5500. $filesize = '5M';
  5501. }
  5502. $minimumsize = get_real_size($filesize);
  5503. if ($postsize = ini_get('post_max_size')) {
  5504. $postsize = get_real_size($postsize);
  5505. if ($postsize < $minimumsize) {
  5506. $minimumsize = $postsize;
  5507. }
  5508. }
  5509. if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
  5510. $minimumsize = $sitebytes;
  5511. }
  5512. if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
  5513. $minimumsize = $coursebytes;
  5514. }
  5515. if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
  5516. $minimumsize = $modulebytes;
  5517. }
  5518. return $minimumsize;
  5519. }
  5520. /**
  5521. * Returns the maximum size for uploading files for the current user
  5522. *
  5523. * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
  5524. *
  5525. * @param context $context The context in which to check user capabilities
  5526. * @param int $sitebytes Set maximum size
  5527. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5528. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5529. * @param stdClass $user The user
  5530. * @return int The maximum size for uploading files.
  5531. */
  5532. function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null) {
  5533. global $USER;
  5534. if (empty($user)) {
  5535. $user = $USER;
  5536. }
  5537. if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
  5538. return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
  5539. }
  5540. return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
  5541. }
  5542. /**
  5543. * Returns an array of possible sizes in local language
  5544. *
  5545. * Related to {@link get_max_upload_file_size()} - this function returns an
  5546. * array of possible sizes in an array, translated to the
  5547. * local language.
  5548. *
  5549. * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
  5550. *
  5551. * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
  5552. * with the value set to 0. This option will be the first in the list.
  5553. *
  5554. * @uses SORT_NUMERIC
  5555. * @param int $sitebytes Set maximum size
  5556. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5557. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5558. * @param int|array $custombytes custom upload size/s which will be added to list,
  5559. * Only value/s smaller then maxsize will be added to list.
  5560. * @return array
  5561. */
  5562. function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
  5563. global $CFG;
  5564. if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
  5565. return array();
  5566. }
  5567. if ($sitebytes == 0) {
  5568. // Will get the minimum of upload_max_filesize or post_max_size.
  5569. $sitebytes = get_max_upload_file_size();
  5570. }
  5571. $filesize = array();
  5572. $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
  5573. 5242880, 10485760, 20971520, 52428800, 104857600);
  5574. // If custombytes is given and is valid then add it to the list.
  5575. if (is_number($custombytes) and $custombytes > 0) {
  5576. $custombytes = (int)$custombytes;
  5577. if (!in_array($custombytes, $sizelist)) {
  5578. $sizelist[] = $custombytes;
  5579. }
  5580. } else if (is_array($custombytes)) {
  5581. $sizelist = array_unique(array_merge($sizelist, $custombytes));
  5582. }
  5583. // Allow maxbytes to be selected if it falls outside the above boundaries.
  5584. if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
  5585. // Note: get_real_size() is used in order to prevent problems with invalid values.
  5586. $sizelist[] = get_real_size($CFG->maxbytes);
  5587. }
  5588. foreach ($sizelist as $sizebytes) {
  5589. if ($sizebytes < $maxsize && $sizebytes > 0) {
  5590. $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
  5591. }
  5592. }
  5593. $limitlevel = '';
  5594. $displaysize = '';
  5595. if ($modulebytes &&
  5596. (($modulebytes < $coursebytes || $coursebytes == 0) &&
  5597. ($modulebytes < $sitebytes || $sitebytes == 0))) {
  5598. $limitlevel = get_string('activity', 'core');
  5599. $displaysize = display_size($modulebytes);
  5600. $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
  5601. } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
  5602. $limitlevel = get_string('course', 'core');
  5603. $displaysize = display_size($coursebytes);
  5604. $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
  5605. } else if ($sitebytes) {
  5606. $limitlevel = get_string('site', 'core');
  5607. $displaysize = display_size($sitebytes);
  5608. $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
  5609. }
  5610. krsort($filesize, SORT_NUMERIC);
  5611. if ($limitlevel) {
  5612. $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
  5613. $filesize = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
  5614. }
  5615. return $filesize;
  5616. }
  5617. /**
  5618. * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
  5619. *
  5620. * If excludefiles is defined, then that file/directory is ignored
  5621. * If getdirs is true, then (sub)directories are included in the output
  5622. * If getfiles is true, then files are included in the output
  5623. * (at least one of these must be true!)
  5624. *
  5625. * @todo Finish documenting this function. Add examples of $excludefile usage.
  5626. *
  5627. * @param string $rootdir A given root directory to start from
  5628. * @param string|array $excludefiles If defined then the specified file/directory is ignored
  5629. * @param bool $descend If true then subdirectories are recursed as well
  5630. * @param bool $getdirs If true then (sub)directories are included in the output
  5631. * @param bool $getfiles If true then files are included in the output
  5632. * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
  5633. */
  5634. function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
  5635. $dirs = array();
  5636. if (!$getdirs and !$getfiles) { // Nothing to show.
  5637. return $dirs;
  5638. }
  5639. if (!is_dir($rootdir)) { // Must be a directory.
  5640. return $dirs;
  5641. }
  5642. if (!$dir = opendir($rootdir)) { // Can't open it for some reason.
  5643. return $dirs;
  5644. }
  5645. if (!is_array($excludefiles)) {
  5646. $excludefiles = array($excludefiles);
  5647. }
  5648. while (false !== ($file = readdir($dir))) {
  5649. $firstchar = substr($file, 0, 1);
  5650. if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
  5651. continue;
  5652. }
  5653. $fullfile = $rootdir .'/'. $file;
  5654. if (filetype($fullfile) == 'dir') {
  5655. if ($getdirs) {
  5656. $dirs[] = $file;
  5657. }
  5658. if ($descend) {
  5659. $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
  5660. foreach ($subdirs as $subdir) {
  5661. $dirs[] = $file .'/'. $subdir;
  5662. }
  5663. }
  5664. } else if ($getfiles) {
  5665. $dirs[] = $file;
  5666. }
  5667. }
  5668. closedir($dir);
  5669. asort($dirs);
  5670. return $dirs;
  5671. }
  5672. /**
  5673. * Adds up all the files in a directory and works out the size.
  5674. *
  5675. * @param string $rootdir The directory to start from
  5676. * @param string $excludefile A file to exclude when summing directory size
  5677. * @return int The summed size of all files and subfiles within the root directory
  5678. */
  5679. function get_directory_size($rootdir, $excludefile='') {
  5680. global $CFG;
  5681. // Do it this way if we can, it's much faster.
  5682. if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
  5683. $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
  5684. $output = null;
  5685. $return = null;
  5686. exec($command, $output, $return);
  5687. if (is_array($output)) {
  5688. // We told it to return k.
  5689. return get_real_size(intval($output[0]).'k');
  5690. }
  5691. }
  5692. if (!is_dir($rootdir)) {
  5693. // Must be a directory.
  5694. return 0;
  5695. }
  5696. if (!$dir = @opendir($rootdir)) {
  5697. // Can't open it for some reason.
  5698. return 0;
  5699. }
  5700. $size = 0;
  5701. while (false !== ($file = readdir($dir))) {
  5702. $firstchar = substr($file, 0, 1);
  5703. if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
  5704. continue;
  5705. }
  5706. $fullfile = $rootdir .'/'. $file;
  5707. if (filetype($fullfile) == 'dir') {
  5708. $size += get_directory_size($fullfile, $excludefile);
  5709. } else {
  5710. $size += filesize($fullfile);
  5711. }
  5712. }
  5713. closedir($dir);
  5714. return $size;
  5715. }
  5716. /**
  5717. * Converts bytes into display form
  5718. *
  5719. * @static string $gb Localized string for size in gigabytes
  5720. * @static string $mb Localized string for size in megabytes
  5721. * @static string $kb Localized string for size in kilobytes
  5722. * @static string $b Localized string for size in bytes
  5723. * @param int $size The size to convert to human readable form
  5724. * @return string
  5725. */
  5726. function display_size($size) {
  5727. static $gb, $mb, $kb, $b;
  5728. if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
  5729. return get_string('unlimited');
  5730. }
  5731. if (empty($gb)) {
  5732. $gb = get_string('sizegb');
  5733. $mb = get_string('sizemb');
  5734. $kb = get_string('sizekb');
  5735. $b = get_string('sizeb');
  5736. }
  5737. if ($size >= 1073741824) {
  5738. $size = round($size / 1073741824 * 10) / 10 . $gb;
  5739. } else if ($size >= 1048576) {
  5740. $size = round($size / 1048576 * 10) / 10 . $mb;
  5741. } else if ($size >= 1024) {
  5742. $size = round($size / 1024 * 10) / 10 . $kb;
  5743. } else {
  5744. $size = intval($size) .' '. $b; // File sizes over 2GB can not work in 32bit PHP anyway.
  5745. }
  5746. return $size;
  5747. }
  5748. /**
  5749. * Cleans a given filename by removing suspicious or troublesome characters
  5750. *
  5751. * @see clean_param()
  5752. * @param string $string file name
  5753. * @return string cleaned file name
  5754. */
  5755. function clean_filename($string) {
  5756. return clean_param($string, PARAM_FILE);
  5757. }
  5758. // STRING TRANSLATION.
  5759. /**
  5760. * Returns the code for the current language
  5761. *
  5762. * @category string
  5763. * @return string
  5764. */
  5765. function current_language() {
  5766. global $CFG, $USER, $SESSION, $COURSE;
  5767. if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
  5768. // Course language can override all other settings for this page.
  5769. $return = $COURSE->lang;
  5770. } else if (!empty($SESSION->lang)) {
  5771. // Session language can override other settings.
  5772. $return = $SESSION->lang;
  5773. } else if (!empty($USER->lang)) {
  5774. $return = $USER->lang;
  5775. } else if (isset($CFG->lang)) {
  5776. $return = $CFG->lang;
  5777. } else {
  5778. $return = 'en';
  5779. }
  5780. // Just in case this slipped in from somewhere by accident.
  5781. $return = str_replace('_utf8', '', $return);
  5782. return $return;
  5783. }
  5784. /**
  5785. * Returns parent language of current active language if defined
  5786. *
  5787. * @category string
  5788. * @param string $lang null means current language
  5789. * @return string
  5790. */
  5791. function get_parent_language($lang=null) {
  5792. global $COURSE, $SESSION;
  5793. // Let's hack around the current language.
  5794. if (!empty($lang)) {
  5795. $oldcourselang = empty($COURSE->lang) ? '' : $COURSE->lang;
  5796. $oldsessionlang = empty($SESSION->lang) ? '' : $SESSION->lang;
  5797. $COURSE->lang = '';
  5798. $SESSION->lang = $lang;
  5799. }
  5800. $parentlang = get_string('parentlanguage', 'langconfig');
  5801. if ($parentlang === 'en') {
  5802. $parentlang = '';
  5803. }
  5804. // Let's hack around the current language.
  5805. if (!empty($lang)) {
  5806. $COURSE->lang = $oldcourselang;
  5807. $SESSION->lang = $oldsessionlang;
  5808. }
  5809. return $parentlang;
  5810. }
  5811. /**
  5812. * Returns current string_manager instance.
  5813. *
  5814. * The param $forcereload is needed for CLI installer only where the string_manager instance
  5815. * must be replaced during the install.php script life time.
  5816. *
  5817. * @category string
  5818. * @param bool $forcereload shall the singleton be released and new instance created instead?
  5819. * @return core_string_manager
  5820. */
  5821. function get_string_manager($forcereload=false) {
  5822. global $CFG;
  5823. static $singleton = null;
  5824. if ($forcereload) {
  5825. $singleton = null;
  5826. }
  5827. if ($singleton === null) {
  5828. if (empty($CFG->early_install_lang)) {
  5829. if (empty($CFG->langlist)) {
  5830. $translist = array();
  5831. } else {
  5832. $translist = explode(',', $CFG->langlist);
  5833. }
  5834. $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist);
  5835. } else {
  5836. $singleton = new core_string_manager_install();
  5837. }
  5838. }
  5839. return $singleton;
  5840. }
  5841. /**
  5842. * Returns a localized string.
  5843. *
  5844. * Returns the translated string specified by $identifier as
  5845. * for $module. Uses the same format files as STphp.
  5846. * $a is an object, string or number that can be used
  5847. * within translation strings
  5848. *
  5849. * eg 'hello {$a->firstname} {$a->lastname}'
  5850. * or 'hello {$a}'
  5851. *
  5852. * If you would like to directly echo the localized string use
  5853. * the function {@link print_string()}
  5854. *
  5855. * Example usage of this function involves finding the string you would
  5856. * like a local equivalent of and using its identifier and module information
  5857. * to retrieve it.<br/>
  5858. * If you open moodle/lang/en/moodle.php and look near line 278
  5859. * you will find a string to prompt a user for their word for 'course'
  5860. * <code>
  5861. * $string['course'] = 'Course';
  5862. * </code>
  5863. * So if you want to display the string 'Course'
  5864. * in any language that supports it on your site
  5865. * you just need to use the identifier 'course'
  5866. * <code>
  5867. * $mystring = '<strong>'. get_string('course') .'</strong>';
  5868. * or
  5869. * </code>
  5870. * If the string you want is in another file you'd take a slightly
  5871. * different approach. Looking in moodle/lang/en/calendar.php you find
  5872. * around line 75:
  5873. * <code>
  5874. * $string['typecourse'] = 'Course event';
  5875. * </code>
  5876. * If you want to display the string "Course event" in any language
  5877. * supported you would use the identifier 'typecourse' and the module 'calendar'
  5878. * (because it is in the file calendar.php):
  5879. * <code>
  5880. * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
  5881. * </code>
  5882. *
  5883. * As a last resort, should the identifier fail to map to a string
  5884. * the returned string will be [[ $identifier ]]
  5885. *
  5886. * In Moodle 2.3 there is a new argument to this function $lazyload.
  5887. * Setting $lazyload to true causes get_string to return a lang_string object
  5888. * rather than the string itself. The fetching of the string is then put off until
  5889. * the string object is first used. The object can be used by calling it's out
  5890. * method or by casting the object to a string, either directly e.g.
  5891. * (string)$stringobject
  5892. * or indirectly by using the string within another string or echoing it out e.g.
  5893. * echo $stringobject
  5894. * return "<p>{$stringobject}</p>";
  5895. * It is worth noting that using $lazyload and attempting to use the string as an
  5896. * array key will cause a fatal error as objects cannot be used as array keys.
  5897. * But you should never do that anyway!
  5898. * For more information {@link lang_string}
  5899. *
  5900. * @category string
  5901. * @param string $identifier The key identifier for the localized string
  5902. * @param string $component The module where the key identifier is stored,
  5903. * usually expressed as the filename in the language pack without the
  5904. * .php on the end but can also be written as mod/forum or grade/export/xls.
  5905. * If none is specified then moodle.php is used.
  5906. * @param string|object|array $a An object, string or number that can be used
  5907. * within translation strings
  5908. * @param bool $lazyload If set to true a string object is returned instead of
  5909. * the string itself. The string then isn't calculated until it is first used.
  5910. * @return string The localized string.
  5911. * @throws coding_exception
  5912. */
  5913. function get_string($identifier, $component = '', $a = null, $lazyload = false) {
  5914. global $CFG;
  5915. // If the lazy load argument has been supplied return a lang_string object
  5916. // instead.
  5917. // We need to make sure it is true (and a bool) as you will see below there
  5918. // used to be a forth argument at one point.
  5919. if ($lazyload === true) {
  5920. return new lang_string($identifier, $component, $a);
  5921. }
  5922. if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
  5923. throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
  5924. }
  5925. // There is now a forth argument again, this time it is a boolean however so
  5926. // we can still check for the old extralocations parameter.
  5927. if (!is_bool($lazyload) && !empty($lazyload)) {
  5928. debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
  5929. }
  5930. if (strpos($component, '/') !== false) {
  5931. debugging('The module name you passed to get_string is the deprecated format ' .
  5932. 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
  5933. $componentpath = explode('/', $component);
  5934. switch ($componentpath[0]) {
  5935. case 'mod':
  5936. $component = $componentpath[1];
  5937. break;
  5938. case 'blocks':
  5939. case 'block':
  5940. $component = 'block_'.$componentpath[1];
  5941. break;
  5942. case 'enrol':
  5943. $component = 'enrol_'.$componentpath[1];
  5944. break;
  5945. case 'format':
  5946. $component = 'format_'.$componentpath[1];
  5947. break;
  5948. case 'grade':
  5949. $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
  5950. break;
  5951. }
  5952. }
  5953. $result = get_string_manager()->get_string($identifier, $component, $a);
  5954. // Debugging feature lets you display string identifier and component.
  5955. if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
  5956. $result .= ' {' . $identifier . '/' . $component . '}';
  5957. }
  5958. return $result;
  5959. }
  5960. /**
  5961. * Converts an array of strings to their localized value.
  5962. *
  5963. * @param array $array An array of strings
  5964. * @param string $component The language module that these strings can be found in.
  5965. * @return stdClass translated strings.
  5966. */
  5967. function get_strings($array, $component = '') {
  5968. $string = new stdClass;
  5969. foreach ($array as $item) {
  5970. $string->$item = get_string($item, $component);
  5971. }
  5972. return $string;
  5973. }
  5974. /**
  5975. * Prints out a translated string.
  5976. *
  5977. * Prints out a translated string using the return value from the {@link get_string()} function.
  5978. *
  5979. * Example usage of this function when the string is in the moodle.php file:<br/>
  5980. * <code>
  5981. * echo '<strong>';
  5982. * print_string('course');
  5983. * echo '</strong>';
  5984. * </code>
  5985. *
  5986. * Example usage of this function when the string is not in the moodle.php file:<br/>
  5987. * <code>
  5988. * echo '<h1>';
  5989. * print_string('typecourse', 'calendar');
  5990. * echo '</h1>';
  5991. * </code>
  5992. *
  5993. * @category string
  5994. * @param string $identifier The key identifier for the localized string
  5995. * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
  5996. * @param string|object|array $a An object, string or number that can be used within translation strings
  5997. */
  5998. function print_string($identifier, $component = '', $a = null) {
  5999. echo get_string($identifier, $component, $a);
  6000. }
  6001. /**
  6002. * Returns a list of charset codes
  6003. *
  6004. * Returns a list of charset codes. It's hardcoded, so they should be added manually
  6005. * (checking that such charset is supported by the texlib library!)
  6006. *
  6007. * @return array And associative array with contents in the form of charset => charset
  6008. */
  6009. function get_list_of_charsets() {
  6010. $charsets = array(
  6011. 'EUC-JP' => 'EUC-JP',
  6012. 'ISO-2022-JP'=> 'ISO-2022-JP',
  6013. 'ISO-8859-1' => 'ISO-8859-1',
  6014. 'SHIFT-JIS' => 'SHIFT-JIS',
  6015. 'GB2312' => 'GB2312',
  6016. 'GB18030' => 'GB18030', // GB18030 not supported by typo and mbstring.
  6017. 'UTF-8' => 'UTF-8');
  6018. asort($charsets);
  6019. return $charsets;
  6020. }
  6021. /**
  6022. * Returns a list of valid and compatible themes
  6023. *
  6024. * @return array
  6025. */
  6026. function get_list_of_themes() {
  6027. global $CFG;
  6028. $themes = array();
  6029. if (!empty($CFG->themelist)) { // Use admin's list of themes.
  6030. $themelist = explode(',', $CFG->themelist);
  6031. } else {
  6032. $themelist = array_keys(core_component::get_plugin_list("theme"));
  6033. }
  6034. foreach ($themelist as $key => $themename) {
  6035. $theme = theme_config::load($themename);
  6036. $themes[$themename] = $theme;
  6037. }
  6038. core_collator::asort_objects_by_method($themes, 'get_theme_name');
  6039. return $themes;
  6040. }
  6041. /**
  6042. * Returns a list of timezones in the current language
  6043. *
  6044. * @return array
  6045. */
  6046. function get_list_of_timezones() {
  6047. global $DB;
  6048. static $timezones;
  6049. if (!empty($timezones)) { // This function has been called recently.
  6050. return $timezones;
  6051. }
  6052. $timezones = array();
  6053. if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
  6054. foreach ($rawtimezones as $timezone) {
  6055. if (!empty($timezone->name)) {
  6056. if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
  6057. $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
  6058. } else {
  6059. $timezones[$timezone->name] = $timezone->name;
  6060. }
  6061. if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found.
  6062. $timezones[$timezone->name] = $timezone->name;
  6063. }
  6064. }
  6065. }
  6066. }
  6067. asort($timezones);
  6068. for ($i = -13; $i <= 13; $i += .5) {
  6069. $tzstring = 'UTC';
  6070. if ($i < 0) {
  6071. $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
  6072. } else if ($i > 0) {
  6073. $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
  6074. } else {
  6075. $timezones[sprintf("%.1f", $i)] = $tzstring;
  6076. }
  6077. }
  6078. return $timezones;
  6079. }
  6080. /**
  6081. * Factory function for emoticon_manager
  6082. *
  6083. * @return emoticon_manager singleton
  6084. */
  6085. function get_emoticon_manager() {
  6086. static $singleton = null;
  6087. if (is_null($singleton)) {
  6088. $singleton = new emoticon_manager();
  6089. }
  6090. return $singleton;
  6091. }
  6092. /**
  6093. * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
  6094. *
  6095. * Whenever this manager mentiones 'emoticon object', the following data
  6096. * structure is expected: stdClass with properties text, imagename, imagecomponent,
  6097. * altidentifier and altcomponent
  6098. *
  6099. * @see admin_setting_emoticons
  6100. *
  6101. * @copyright 2010 David Mudrak
  6102. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  6103. */
  6104. class emoticon_manager {
  6105. /**
  6106. * Returns the currently enabled emoticons
  6107. *
  6108. * @return array of emoticon objects
  6109. */
  6110. public function get_emoticons() {
  6111. global $CFG;
  6112. if (empty($CFG->emoticons)) {
  6113. return array();
  6114. }
  6115. $emoticons = $this->decode_stored_config($CFG->emoticons);
  6116. if (!is_array($emoticons)) {
  6117. // Something is wrong with the format of stored setting.
  6118. debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
  6119. return array();
  6120. }
  6121. return $emoticons;
  6122. }
  6123. /**
  6124. * Converts emoticon object into renderable pix_emoticon object
  6125. *
  6126. * @param stdClass $emoticon emoticon object
  6127. * @param array $attributes explicit HTML attributes to set
  6128. * @return pix_emoticon
  6129. */
  6130. public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
  6131. $stringmanager = get_string_manager();
  6132. if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
  6133. $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
  6134. } else {
  6135. $alt = s($emoticon->text);
  6136. }
  6137. return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
  6138. }
  6139. /**
  6140. * Encodes the array of emoticon objects into a string storable in config table
  6141. *
  6142. * @see self::decode_stored_config()
  6143. * @param array $emoticons array of emtocion objects
  6144. * @return string
  6145. */
  6146. public function encode_stored_config(array $emoticons) {
  6147. return json_encode($emoticons);
  6148. }
  6149. /**
  6150. * Decodes the string into an array of emoticon objects
  6151. *
  6152. * @see self::encode_stored_config()
  6153. * @param string $encoded
  6154. * @return string|null
  6155. */
  6156. public function decode_stored_config($encoded) {
  6157. $decoded = json_decode($encoded);
  6158. if (!is_array($decoded)) {
  6159. return null;
  6160. }
  6161. return $decoded;
  6162. }
  6163. /**
  6164. * Returns default set of emoticons supported by Moodle
  6165. *
  6166. * @return array of sdtClasses
  6167. */
  6168. public function default_emoticons() {
  6169. return array(
  6170. $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
  6171. $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
  6172. $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
  6173. $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
  6174. $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
  6175. $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
  6176. $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
  6177. $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
  6178. $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
  6179. $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
  6180. $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
  6181. $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
  6182. $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
  6183. $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
  6184. $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
  6185. $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
  6186. $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
  6187. $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
  6188. $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
  6189. $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
  6190. $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
  6191. $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
  6192. $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
  6193. $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
  6194. $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
  6195. $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
  6196. $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
  6197. $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
  6198. $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
  6199. $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
  6200. );
  6201. }
  6202. /**
  6203. * Helper method preparing the stdClass with the emoticon properties
  6204. *
  6205. * @param string|array $text or array of strings
  6206. * @param string $imagename to be used by {@link pix_emoticon}
  6207. * @param string $altidentifier alternative string identifier, null for no alt
  6208. * @param string $altcomponent where the alternative string is defined
  6209. * @param string $imagecomponent to be used by {@link pix_emoticon}
  6210. * @return stdClass
  6211. */
  6212. protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
  6213. $altcomponent = 'core_pix', $imagecomponent = 'core') {
  6214. return (object)array(
  6215. 'text' => $text,
  6216. 'imagename' => $imagename,
  6217. 'imagecomponent' => $imagecomponent,
  6218. 'altidentifier' => $altidentifier,
  6219. 'altcomponent' => $altcomponent,
  6220. );
  6221. }
  6222. }
  6223. // ENCRYPTION.
  6224. /**
  6225. * rc4encrypt
  6226. *
  6227. * @param string $data Data to encrypt.
  6228. * @return string The now encrypted data.
  6229. */
  6230. function rc4encrypt($data) {
  6231. return endecrypt(get_site_identifier(), $data, '');
  6232. }
  6233. /**
  6234. * rc4decrypt
  6235. *
  6236. * @param string $data Data to decrypt.
  6237. * @return string The now decrypted data.
  6238. */
  6239. function rc4decrypt($data) {
  6240. return endecrypt(get_site_identifier(), $data, 'de');
  6241. }
  6242. /**
  6243. * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
  6244. *
  6245. * @todo Finish documenting this function
  6246. *
  6247. * @param string $pwd The password to use when encrypting or decrypting
  6248. * @param string $data The data to be decrypted/encrypted
  6249. * @param string $case Either 'de' for decrypt or '' for encrypt
  6250. * @return string
  6251. */
  6252. function endecrypt ($pwd, $data, $case) {
  6253. if ($case == 'de') {
  6254. $data = urldecode($data);
  6255. }
  6256. $key[] = '';
  6257. $box[] = '';
  6258. $pwdlength = strlen($pwd);
  6259. for ($i = 0; $i <= 255; $i++) {
  6260. $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
  6261. $box[$i] = $i;
  6262. }
  6263. $x = 0;
  6264. for ($i = 0; $i <= 255; $i++) {
  6265. $x = ($x + $box[$i] + $key[$i]) % 256;
  6266. $tempswap = $box[$i];
  6267. $box[$i] = $box[$x];
  6268. $box[$x] = $tempswap;
  6269. }
  6270. $cipher = '';
  6271. $a = 0;
  6272. $j = 0;
  6273. for ($i = 0; $i < strlen($data); $i++) {
  6274. $a = ($a + 1) % 256;
  6275. $j = ($j + $box[$a]) % 256;
  6276. $temp = $box[$a];
  6277. $box[$a] = $box[$j];
  6278. $box[$j] = $temp;
  6279. $k = $box[(($box[$a] + $box[$j]) % 256)];
  6280. $cipherby = ord(substr($data, $i, 1)) ^ $k;
  6281. $cipher .= chr($cipherby);
  6282. }
  6283. if ($case == 'de') {
  6284. $cipher = urldecode(urlencode($cipher));
  6285. } else {
  6286. $cipher = urlencode($cipher);
  6287. }
  6288. return $cipher;
  6289. }
  6290. // ENVIRONMENT CHECKING.
  6291. /**
  6292. * This method validates a plug name. It is much faster than calling clean_param.
  6293. *
  6294. * @param string $name a string that might be a plugin name.
  6295. * @return bool if this string is a valid plugin name.
  6296. */
  6297. function is_valid_plugin_name($name) {
  6298. // This does not work for 'mod', bad luck, use any other type.
  6299. return core_component::is_valid_plugin_name('tool', $name);
  6300. }
  6301. /**
  6302. * Get a list of all the plugins of a given type that define a certain API function
  6303. * in a certain file. The plugin component names and function names are returned.
  6304. *
  6305. * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
  6306. * @param string $function the part of the name of the function after the
  6307. * frankenstyle prefix. e.g 'hook' if you are looking for functions with
  6308. * names like report_courselist_hook.
  6309. * @param string $file the name of file within the plugin that defines the
  6310. * function. Defaults to lib.php.
  6311. * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
  6312. * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
  6313. */
  6314. function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
  6315. $pluginfunctions = array();
  6316. $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, $file, true);
  6317. foreach ($pluginswithfile as $plugin => $notused) {
  6318. $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
  6319. if (function_exists($fullfunction)) {
  6320. // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
  6321. $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
  6322. } else if ($plugintype === 'mod') {
  6323. // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
  6324. $shortfunction = $plugin . '_' . $function;
  6325. if (function_exists($shortfunction)) {
  6326. $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
  6327. }
  6328. }
  6329. }
  6330. return $pluginfunctions;
  6331. }
  6332. /**
  6333. * Lists plugin-like directories within specified directory
  6334. *
  6335. * This function was originally used for standard Moodle plugins, please use
  6336. * new core_component::get_plugin_list() now.
  6337. *
  6338. * This function is used for general directory listing and backwards compatility.
  6339. *
  6340. * @param string $directory relative directory from root
  6341. * @param string $exclude dir name to exclude from the list (defaults to none)
  6342. * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
  6343. * @return array Sorted array of directory names found under the requested parameters
  6344. */
  6345. function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
  6346. global $CFG;
  6347. $plugins = array();
  6348. if (empty($basedir)) {
  6349. $basedir = $CFG->dirroot .'/'. $directory;
  6350. } else {
  6351. $basedir = $basedir .'/'. $directory;
  6352. }
  6353. if ($CFG->debugdeveloper and empty($exclude)) {
  6354. // Make sure devs do not use this to list normal plugins,
  6355. // this is intended for general directories that are not plugins!
  6356. $subtypes = core_component::get_plugin_types();
  6357. if (in_array($basedir, $subtypes)) {
  6358. debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
  6359. }
  6360. unset($subtypes);
  6361. }
  6362. if (file_exists($basedir) && filetype($basedir) == 'dir') {
  6363. if (!$dirhandle = opendir($basedir)) {
  6364. debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
  6365. return array();
  6366. }
  6367. while (false !== ($dir = readdir($dirhandle))) {
  6368. // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
  6369. if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
  6370. $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
  6371. continue;
  6372. }
  6373. if (filetype($basedir .'/'. $dir) != 'dir') {
  6374. continue;
  6375. }
  6376. $plugins[] = $dir;
  6377. }
  6378. closedir($dirhandle);
  6379. }
  6380. if ($plugins) {
  6381. asort($plugins);
  6382. }
  6383. return $plugins;
  6384. }
  6385. /**
  6386. * Invoke plugin's callback functions
  6387. *
  6388. * @param string $type plugin type e.g. 'mod'
  6389. * @param string $name plugin name
  6390. * @param string $feature feature name
  6391. * @param string $action feature's action
  6392. * @param array $params parameters of callback function, should be an array
  6393. * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
  6394. * @return mixed
  6395. *
  6396. * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
  6397. */
  6398. function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
  6399. return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
  6400. }
  6401. /**
  6402. * Invoke component's callback functions
  6403. *
  6404. * @param string $component frankenstyle component name, e.g. 'mod_quiz'
  6405. * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
  6406. * @param array $params parameters of callback function
  6407. * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
  6408. * @return mixed
  6409. */
  6410. function component_callback($component, $function, array $params = array(), $default = null) {
  6411. $functionname = component_callback_exists($component, $function);
  6412. if ($functionname) {
  6413. // Function exists, so just return function result.
  6414. $ret = call_user_func_array($functionname, $params);
  6415. if (is_null($ret)) {
  6416. return $default;
  6417. } else {
  6418. return $ret;
  6419. }
  6420. }
  6421. return $default;
  6422. }
  6423. /**
  6424. * Determine if a component callback exists and return the function name to call. Note that this
  6425. * function will include the required library files so that the functioname returned can be
  6426. * called directly.
  6427. *
  6428. * @param string $component frankenstyle component name, e.g. 'mod_quiz'
  6429. * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
  6430. * @return mixed Complete function name to call if the callback exists or false if it doesn't.
  6431. * @throws coding_exception if invalid component specfied
  6432. */
  6433. function component_callback_exists($component, $function) {
  6434. global $CFG; // This is needed for the inclusions.
  6435. $cleancomponent = clean_param($component, PARAM_COMPONENT);
  6436. if (empty($cleancomponent)) {
  6437. throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
  6438. }
  6439. $component = $cleancomponent;
  6440. list($type, $name) = core_component::normalize_component($component);
  6441. $component = $type . '_' . $name;
  6442. $oldfunction = $name.'_'.$function;
  6443. $function = $component.'_'.$function;
  6444. $dir = core_component::get_component_directory($component);
  6445. if (empty($dir)) {
  6446. throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
  6447. }
  6448. // Load library and look for function.
  6449. if (file_exists($dir.'/lib.php')) {
  6450. require_once($dir.'/lib.php');
  6451. }
  6452. if (!function_exists($function) and function_exists($oldfunction)) {
  6453. if ($type !== 'mod' and $type !== 'core') {
  6454. debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
  6455. }
  6456. $function = $oldfunction;
  6457. }
  6458. if (function_exists($function)) {
  6459. return $function;
  6460. }
  6461. return false;
  6462. }
  6463. /**
  6464. * Checks whether a plugin supports a specified feature.
  6465. *
  6466. * @param string $type Plugin type e.g. 'mod'
  6467. * @param string $name Plugin name e.g. 'forum'
  6468. * @param string $feature Feature code (FEATURE_xx constant)
  6469. * @param mixed $default default value if feature support unknown
  6470. * @return mixed Feature result (false if not supported, null if feature is unknown,
  6471. * otherwise usually true but may have other feature-specific value such as array)
  6472. * @throws coding_exception
  6473. */
  6474. function plugin_supports($type, $name, $feature, $default = null) {
  6475. global $CFG;
  6476. if ($type === 'mod' and $name === 'NEWMODULE') {
  6477. // Somebody forgot to rename the module template.
  6478. return false;
  6479. }
  6480. $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
  6481. if (empty($component)) {
  6482. throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
  6483. }
  6484. $function = null;
  6485. if ($type === 'mod') {
  6486. // We need this special case because we support subplugins in modules,
  6487. // otherwise it would end up in infinite loop.
  6488. if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
  6489. include_once("$CFG->dirroot/mod/$name/lib.php");
  6490. $function = $component.'_supports';
  6491. if (!function_exists($function)) {
  6492. // Legacy non-frankenstyle function name.
  6493. $function = $name.'_supports';
  6494. }
  6495. }
  6496. } else {
  6497. if (!$path = core_component::get_plugin_directory($type, $name)) {
  6498. // Non existent plugin type.
  6499. return false;
  6500. }
  6501. if (file_exists("$path/lib.php")) {
  6502. include_once("$path/lib.php");
  6503. $function = $component.'_supports';
  6504. }
  6505. }
  6506. if ($function and function_exists($function)) {
  6507. $supports = $function($feature);
  6508. if (is_null($supports)) {
  6509. // Plugin does not know - use default.
  6510. return $default;
  6511. } else {
  6512. return $supports;
  6513. }
  6514. }
  6515. // Plugin does not care, so use default.
  6516. return $default;
  6517. }
  6518. /**
  6519. * Returns true if the current version of PHP is greater that the specified one.
  6520. *
  6521. * @todo Check PHP version being required here is it too low?
  6522. *
  6523. * @param string $version The version of php being tested.
  6524. * @return bool
  6525. */
  6526. function check_php_version($version='5.2.4') {
  6527. return (version_compare(phpversion(), $version) >= 0);
  6528. }
  6529. /**
  6530. * Determine if moodle installation requires update.
  6531. *
  6532. * Checks version numbers of main code and all plugins to see
  6533. * if there are any mismatches.
  6534. *
  6535. * @return bool
  6536. */
  6537. function moodle_needs_upgrading() {
  6538. global $CFG;
  6539. if (empty($CFG->version)) {
  6540. return true;
  6541. }
  6542. // There is no need to purge plugininfo caches here because
  6543. // these caches are not used during upgrade and they are purged after
  6544. // every upgrade.
  6545. if (empty($CFG->allversionshash)) {
  6546. return true;
  6547. }
  6548. $hash = core_component::get_all_versions_hash();
  6549. return ($hash !== $CFG->allversionshash);
  6550. }
  6551. /**
  6552. * Returns the major version of this site
  6553. *
  6554. * Moodle version numbers consist of three numbers separated by a dot, for
  6555. * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
  6556. * called major version. This function extracts the major version from either
  6557. * $CFG->release (default) or eventually from the $release variable defined in
  6558. * the main version.php.
  6559. *
  6560. * @param bool $fromdisk should the version if source code files be used
  6561. * @return string|false the major version like '2.3', false if could not be determined
  6562. */
  6563. function moodle_major_version($fromdisk = false) {
  6564. global $CFG;
  6565. if ($fromdisk) {
  6566. $release = null;
  6567. require($CFG->dirroot.'/version.php');
  6568. if (empty($release)) {
  6569. return false;
  6570. }
  6571. } else {
  6572. if (empty($CFG->release)) {
  6573. return false;
  6574. }
  6575. $release = $CFG->release;
  6576. }
  6577. if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
  6578. return $matches[0];
  6579. } else {
  6580. return false;
  6581. }
  6582. }
  6583. // MISCELLANEOUS.
  6584. /**
  6585. * Sets the system locale
  6586. *
  6587. * @category string
  6588. * @param string $locale Can be used to force a locale
  6589. */
  6590. function moodle_setlocale($locale='') {
  6591. global $CFG;
  6592. static $currentlocale = ''; // Last locale caching.
  6593. $oldlocale = $currentlocale;
  6594. // Fetch the correct locale based on ostype.
  6595. if ($CFG->ostype == 'WINDOWS') {
  6596. $stringtofetch = 'localewin';
  6597. } else {
  6598. $stringtofetch = 'locale';
  6599. }
  6600. // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
  6601. if (!empty($locale)) {
  6602. $currentlocale = $locale;
  6603. } else if (!empty($CFG->locale)) { // Override locale for all language packs.
  6604. $currentlocale = $CFG->locale;
  6605. } else {
  6606. $currentlocale = get_string($stringtofetch, 'langconfig');
  6607. }
  6608. // Do nothing if locale already set up.
  6609. if ($oldlocale == $currentlocale) {
  6610. return;
  6611. }
  6612. // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
  6613. // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
  6614. // Some day, numeric, monetary and other categories should be set too, I think. :-/.
  6615. // Get current values.
  6616. $monetary= setlocale (LC_MONETARY, 0);
  6617. $numeric = setlocale (LC_NUMERIC, 0);
  6618. $ctype = setlocale (LC_CTYPE, 0);
  6619. if ($CFG->ostype != 'WINDOWS') {
  6620. $messages= setlocale (LC_MESSAGES, 0);
  6621. }
  6622. // Set locale to all.
  6623. $result = setlocale (LC_ALL, $currentlocale);
  6624. // If setting of locale fails try the other utf8 or utf-8 variant,
  6625. // some operating systems support both (Debian), others just one (OSX).
  6626. if ($result === false) {
  6627. if (stripos($currentlocale, '.UTF-8') !== false) {
  6628. $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
  6629. setlocale (LC_ALL, $newlocale);
  6630. } else if (stripos($currentlocale, '.UTF8') !== false) {
  6631. $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
  6632. setlocale (LC_ALL, $newlocale);
  6633. }
  6634. }
  6635. // Set old values.
  6636. setlocale (LC_MONETARY, $monetary);
  6637. setlocale (LC_NUMERIC, $numeric);
  6638. if ($CFG->ostype != 'WINDOWS') {
  6639. setlocale (LC_MESSAGES, $messages);
  6640. }
  6641. if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
  6642. // To workaround a well-known PHP problem with Turkish letter Ii.
  6643. setlocale (LC_CTYPE, $ctype);
  6644. }
  6645. }
  6646. /**
  6647. * Count words in a string.
  6648. *
  6649. * Words are defined as things between whitespace.
  6650. *
  6651. * @category string
  6652. * @param string $string The text to be searched for words.
  6653. * @return int The count of words in the specified string
  6654. */
  6655. function count_words($string) {
  6656. $string = strip_tags($string);
  6657. return count(preg_split("/\w\b/", $string)) - 1;
  6658. }
  6659. /**
  6660. * Count letters in a string.
  6661. *
  6662. * Letters are defined as chars not in tags and different from whitespace.
  6663. *
  6664. * @category string
  6665. * @param string $string The text to be searched for letters.
  6666. * @return int The count of letters in the specified text.
  6667. */
  6668. function count_letters($string) {
  6669. $string = strip_tags($string); // Tags are out now.
  6670. $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
  6671. return core_text::strlen($string);
  6672. }
  6673. /**
  6674. * Generate and return a random string of the specified length.
  6675. *
  6676. * @param int $length The length of the string to be created.
  6677. * @return string
  6678. */
  6679. function random_string ($length=15) {
  6680. $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  6681. $pool .= 'abcdefghijklmnopqrstuvwxyz';
  6682. $pool .= '0123456789';
  6683. $poollen = strlen($pool);
  6684. $string = '';
  6685. for ($i = 0; $i < $length; $i++) {
  6686. $string .= substr($pool, (mt_rand()%($poollen)), 1);
  6687. }
  6688. return $string;
  6689. }
  6690. /**
  6691. * Generate a complex random string (useful for md5 salts)
  6692. *
  6693. * This function is based on the above {@link random_string()} however it uses a
  6694. * larger pool of characters and generates a string between 24 and 32 characters
  6695. *
  6696. * @param int $length Optional if set generates a string to exactly this length
  6697. * @return string
  6698. */
  6699. function complex_random_string($length=null) {
  6700. $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  6701. $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
  6702. $poollen = strlen($pool);
  6703. if ($length===null) {
  6704. $length = floor(rand(24, 32));
  6705. }
  6706. $string = '';
  6707. for ($i = 0; $i < $length; $i++) {
  6708. $string .= $pool[(mt_rand()%$poollen)];
  6709. }
  6710. return $string;
  6711. }
  6712. /**
  6713. * Given some text (which may contain HTML) and an ideal length,
  6714. * this function truncates the text neatly on a word boundary if possible
  6715. *
  6716. * @category string
  6717. * @param string $text text to be shortened
  6718. * @param int $ideal ideal string length
  6719. * @param boolean $exact if false, $text will not be cut mid-word
  6720. * @param string $ending The string to append if the passed string is truncated
  6721. * @return string $truncate shortened string
  6722. */
  6723. function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
  6724. // If the plain text is shorter than the maximum length, return the whole text.
  6725. if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
  6726. return $text;
  6727. }
  6728. // Splits on HTML tags. Each open/close/empty tag will be the first thing
  6729. // and only tag in its 'line'.
  6730. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  6731. $totallength = core_text::strlen($ending);
  6732. $truncate = '';
  6733. // This array stores information about open and close tags and their position
  6734. // in the truncated string. Each item in the array is an object with fields
  6735. // ->open (true if open), ->tag (tag name in lower case), and ->pos
  6736. // (byte position in truncated text).
  6737. $tagdetails = array();
  6738. foreach ($lines as $linematchings) {
  6739. // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
  6740. if (!empty($linematchings[1])) {
  6741. // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
  6742. if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
  6743. if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
  6744. // Record closing tag.
  6745. $tagdetails[] = (object) array(
  6746. 'open' => false,
  6747. 'tag' => core_text::strtolower($tagmatchings[1]),
  6748. 'pos' => core_text::strlen($truncate),
  6749. );
  6750. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
  6751. // Record opening tag.
  6752. $tagdetails[] = (object) array(
  6753. 'open' => true,
  6754. 'tag' => core_text::strtolower($tagmatchings[1]),
  6755. 'pos' => core_text::strlen($truncate),
  6756. );
  6757. }
  6758. }
  6759. // Add html-tag to $truncate'd text.
  6760. $truncate .= $linematchings[1];
  6761. }
  6762. // Calculate the length of the plain text part of the line; handle entities as one character.
  6763. $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
  6764. if ($totallength + $contentlength > $ideal) {
  6765. // The number of characters which are left.
  6766. $left = $ideal - $totallength;
  6767. $entitieslength = 0;
  6768. // Search for html entities.
  6769. 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)) {
  6770. // Calculate the real length of all entities in the legal range.
  6771. foreach ($entities[0] as $entity) {
  6772. if ($entity[1]+1-$entitieslength <= $left) {
  6773. $left--;
  6774. $entitieslength += core_text::strlen($entity[0]);
  6775. } else {
  6776. // No more characters left.
  6777. break;
  6778. }
  6779. }
  6780. }
  6781. $breakpos = $left + $entitieslength;
  6782. // If the words shouldn't be cut in the middle...
  6783. if (!$exact) {
  6784. // Search the last occurence of a space.
  6785. for (; $breakpos > 0; $breakpos--) {
  6786. if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
  6787. if ($char === '.' or $char === ' ') {
  6788. $breakpos += 1;
  6789. break;
  6790. } else if (strlen($char) > 2) {
  6791. // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
  6792. $breakpos += 1;
  6793. break;
  6794. }
  6795. }
  6796. }
  6797. }
  6798. if ($breakpos == 0) {
  6799. // This deals with the test_shorten_text_no_spaces case.
  6800. $breakpos = $left + $entitieslength;
  6801. } else if ($breakpos > $left + $entitieslength) {
  6802. // This deals with the previous for loop breaking on the first char.
  6803. $breakpos = $left + $entitieslength;
  6804. }
  6805. $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
  6806. // Maximum length is reached, so get off the loop.
  6807. break;
  6808. } else {
  6809. $truncate .= $linematchings[2];
  6810. $totallength += $contentlength;
  6811. }
  6812. // If the maximum length is reached, get off the loop.
  6813. if ($totallength >= $ideal) {
  6814. break;
  6815. }
  6816. }
  6817. // Add the defined ending to the text.
  6818. $truncate .= $ending;
  6819. // Now calculate the list of open html tags based on the truncate position.
  6820. $opentags = array();
  6821. foreach ($tagdetails as $taginfo) {
  6822. if ($taginfo->open) {
  6823. // Add tag to the beginning of $opentags list.
  6824. array_unshift($opentags, $taginfo->tag);
  6825. } else {
  6826. // Can have multiple exact same open tags, close the last one.
  6827. $pos = array_search($taginfo->tag, array_reverse($opentags, true));
  6828. if ($pos !== false) {
  6829. unset($opentags[$pos]);
  6830. }
  6831. }
  6832. }
  6833. // Close all unclosed html-tags.
  6834. foreach ($opentags as $tag) {
  6835. $truncate .= '</' . $tag . '>';
  6836. }
  6837. return $truncate;
  6838. }
  6839. /**
  6840. * Given dates in seconds, how many weeks is the date from startdate
  6841. * The first week is 1, the second 2 etc ...
  6842. *
  6843. * @param int $startdate Timestamp for the start date
  6844. * @param int $thedate Timestamp for the end date
  6845. * @return string
  6846. */
  6847. function getweek ($startdate, $thedate) {
  6848. if ($thedate < $startdate) {
  6849. return 0;
  6850. }
  6851. return floor(($thedate - $startdate) / WEEKSECS) + 1;
  6852. }
  6853. /**
  6854. * Returns a randomly generated password of length $maxlen. inspired by
  6855. *
  6856. * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
  6857. * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
  6858. *
  6859. * @param int $maxlen The maximum size of the password being generated.
  6860. * @return string
  6861. */
  6862. function generate_password($maxlen=10) {
  6863. global $CFG;
  6864. if (empty($CFG->passwordpolicy)) {
  6865. $fillers = PASSWORD_DIGITS;
  6866. $wordlist = file($CFG->wordlist);
  6867. $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  6868. $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  6869. $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
  6870. $password = $word1 . $filler1 . $word2;
  6871. } else {
  6872. $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
  6873. $digits = $CFG->minpassworddigits;
  6874. $lower = $CFG->minpasswordlower;
  6875. $upper = $CFG->minpasswordupper;
  6876. $nonalphanum = $CFG->minpasswordnonalphanum;
  6877. $total = $lower + $upper + $digits + $nonalphanum;
  6878. // Var minlength should be the greater one of the two ( $minlen and $total ).
  6879. $minlen = $minlen < $total ? $total : $minlen;
  6880. // Var maxlen can never be smaller than minlen.
  6881. $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
  6882. $additional = $maxlen - $total;
  6883. // Make sure we have enough characters to fulfill
  6884. // complexity requirements.
  6885. $passworddigits = PASSWORD_DIGITS;
  6886. while ($digits > strlen($passworddigits)) {
  6887. $passworddigits .= PASSWORD_DIGITS;
  6888. }
  6889. $passwordlower = PASSWORD_LOWER;
  6890. while ($lower > strlen($passwordlower)) {
  6891. $passwordlower .= PASSWORD_LOWER;
  6892. }
  6893. $passwordupper = PASSWORD_UPPER;
  6894. while ($upper > strlen($passwordupper)) {
  6895. $passwordupper .= PASSWORD_UPPER;
  6896. }
  6897. $passwordnonalphanum = PASSWORD_NONALPHANUM;
  6898. while ($nonalphanum > strlen($passwordnonalphanum)) {
  6899. $passwordnonalphanum .= PASSWORD_NONALPHANUM;
  6900. }
  6901. // Now mix and shuffle it all.
  6902. $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
  6903. substr(str_shuffle ($passwordupper), 0, $upper) .
  6904. substr(str_shuffle ($passworddigits), 0, $digits) .
  6905. substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
  6906. substr(str_shuffle ($passwordlower .
  6907. $passwordupper .
  6908. $passworddigits .
  6909. $passwordnonalphanum), 0 , $additional));
  6910. }
  6911. return substr ($password, 0, $maxlen);
  6912. }
  6913. /**
  6914. * Given a float, prints it nicely.
  6915. * Localized floats must not be used in calculations!
  6916. *
  6917. * The stripzeros feature is intended for making numbers look nicer in small
  6918. * areas where it is not necessary to indicate the degree of accuracy by showing
  6919. * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
  6920. * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
  6921. *
  6922. * @param float $float The float to print
  6923. * @param int $decimalpoints The number of decimal places to print.
  6924. * @param bool $localized use localized decimal separator
  6925. * @param bool $stripzeros If true, removes final zeros after decimal point
  6926. * @return string locale float
  6927. */
  6928. function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
  6929. if (is_null($float)) {
  6930. return '';
  6931. }
  6932. if ($localized) {
  6933. $separator = get_string('decsep', 'langconfig');
  6934. } else {
  6935. $separator = '.';
  6936. }
  6937. $result = number_format($float, $decimalpoints, $separator, '');
  6938. if ($stripzeros) {
  6939. // Remove zeros and final dot if not needed.
  6940. $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
  6941. }
  6942. return $result;
  6943. }
  6944. /**
  6945. * Converts locale specific floating point/comma number back to standard PHP float value
  6946. * Do NOT try to do any math operations before this conversion on any user submitted floats!
  6947. *
  6948. * @param string $localefloat locale aware float representation
  6949. * @param bool $strict If true, then check the input and return false if it is not a valid number.
  6950. * @return mixed float|bool - false or the parsed float.
  6951. */
  6952. function unformat_float($localefloat, $strict = false) {
  6953. $localefloat = trim($localefloat);
  6954. if ($localefloat == '') {
  6955. return null;
  6956. }
  6957. $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
  6958. $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
  6959. if ($strict && !is_numeric($localefloat)) {
  6960. return false;
  6961. }
  6962. return (float)$localefloat;
  6963. }
  6964. /**
  6965. * Given a simple array, this shuffles it up just like shuffle()
  6966. * Unlike PHP's shuffle() this function works on any machine.
  6967. *
  6968. * @param array $array The array to be rearranged
  6969. * @return array
  6970. */
  6971. function swapshuffle($array) {
  6972. $last = count($array) - 1;
  6973. for ($i = 0; $i <= $last; $i++) {
  6974. $from = rand(0, $last);
  6975. $curr = $array[$i];
  6976. $array[$i] = $array[$from];
  6977. $array[$from] = $curr;
  6978. }
  6979. return $array;
  6980. }
  6981. /**
  6982. * Like {@link swapshuffle()}, but works on associative arrays
  6983. *
  6984. * @param array $array The associative array to be rearranged
  6985. * @return array
  6986. */
  6987. function swapshuffle_assoc($array) {
  6988. $newarray = array();
  6989. $newkeys = swapshuffle(array_keys($array));
  6990. foreach ($newkeys as $newkey) {
  6991. $newarray[$newkey] = $array[$newkey];
  6992. }
  6993. return $newarray;
  6994. }
  6995. /**
  6996. * Given an arbitrary array, and a number of draws,
  6997. * this function returns an array with that amount
  6998. * of items. The indexes are retained.
  6999. *
  7000. * @todo Finish documenting this function
  7001. *
  7002. * @param array $array
  7003. * @param int $draws
  7004. * @return array
  7005. */
  7006. function draw_rand_array($array, $draws) {
  7007. $return = array();
  7008. $last = count($array);
  7009. if ($draws > $last) {
  7010. $draws = $last;
  7011. }
  7012. while ($draws > 0) {
  7013. $last--;
  7014. $keys = array_keys($array);
  7015. $rand = rand(0, $last);
  7016. $return[$keys[$rand]] = $array[$keys[$rand]];
  7017. unset($array[$keys[$rand]]);
  7018. $draws--;
  7019. }
  7020. return $return;
  7021. }
  7022. /**
  7023. * Calculate the difference between two microtimes
  7024. *
  7025. * @param string $a The first Microtime
  7026. * @param string $b The second Microtime
  7027. * @return string
  7028. */
  7029. function microtime_diff($a, $b) {
  7030. list($adec, $asec) = explode(' ', $a);
  7031. list($bdec, $bsec) = explode(' ', $b);
  7032. return $bsec - $asec + $bdec - $adec;
  7033. }
  7034. /**
  7035. * Given a list (eg a,b,c,d,e) this function returns
  7036. * an array of 1->a, 2->b, 3->c etc
  7037. *
  7038. * @param string $list The string to explode into array bits
  7039. * @param string $separator The separator used within the list string
  7040. * @return array The now assembled array
  7041. */
  7042. function make_menu_from_list($list, $separator=',') {
  7043. $array = array_reverse(explode($separator, $list), true);
  7044. foreach ($array as $key => $item) {
  7045. $outarray[$key+1] = trim($item);
  7046. }
  7047. return $outarray;
  7048. }
  7049. /**
  7050. * Creates an array that represents all the current grades that
  7051. * can be chosen using the given grading type.
  7052. *
  7053. * Negative numbers
  7054. * are scales, zero is no grade, and positive numbers are maximum
  7055. * grades.
  7056. *
  7057. * @todo Finish documenting this function or better deprecated this completely!
  7058. *
  7059. * @param int $gradingtype
  7060. * @return array
  7061. */
  7062. function make_grades_menu($gradingtype) {
  7063. global $DB;
  7064. $grades = array();
  7065. if ($gradingtype < 0) {
  7066. if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
  7067. return make_menu_from_list($scale->scale);
  7068. }
  7069. } else if ($gradingtype > 0) {
  7070. for ($i=$gradingtype; $i>=0; $i--) {
  7071. $grades[$i] = $i .' / '. $gradingtype;
  7072. }
  7073. return $grades;
  7074. }
  7075. return $grades;
  7076. }
  7077. /**
  7078. * This function returns the number of activities using the given scale in the given course.
  7079. *
  7080. * @param int $courseid The course ID to check.
  7081. * @param int $scaleid The scale ID to check
  7082. * @return int
  7083. */
  7084. function course_scale_used($courseid, $scaleid) {
  7085. global $CFG, $DB;
  7086. $return = 0;
  7087. if (!empty($scaleid)) {
  7088. if ($cms = get_course_mods($courseid)) {
  7089. foreach ($cms as $cm) {
  7090. // Check cm->name/lib.php exists.
  7091. if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
  7092. include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
  7093. $functionname = $cm->modname.'_scale_used';
  7094. if (function_exists($functionname)) {
  7095. if ($functionname($cm->instance, $scaleid)) {
  7096. $return++;
  7097. }
  7098. }
  7099. }
  7100. }
  7101. }
  7102. // Check if any course grade item makes use of the scale.
  7103. $return += $DB->count_records('grade_items', array('courseid' => $courseid, 'scaleid' => $scaleid));
  7104. // Check if any outcome in the course makes use of the scale.
  7105. $return += $DB->count_records_sql("SELECT COUNT('x')
  7106. FROM {grade_outcomes_courses} goc,
  7107. {grade_outcomes} go
  7108. WHERE go.id = goc.outcomeid
  7109. AND go.scaleid = ? AND goc.courseid = ?",
  7110. array($scaleid, $courseid));
  7111. }
  7112. return $return;
  7113. }
  7114. /**
  7115. * This function returns the number of activities using scaleid in the entire site
  7116. *
  7117. * @param int $scaleid
  7118. * @param array $courses
  7119. * @return int
  7120. */
  7121. function site_scale_used($scaleid, &$courses) {
  7122. $return = 0;
  7123. if (!is_array($courses) || count($courses) == 0) {
  7124. $courses = get_courses("all", false, "c.id, c.shortname");
  7125. }
  7126. if (!empty($scaleid)) {
  7127. if (is_array($courses) && count($courses) > 0) {
  7128. foreach ($courses as $course) {
  7129. $return += course_scale_used($course->id, $scaleid);
  7130. }
  7131. }
  7132. }
  7133. return $return;
  7134. }
  7135. /**
  7136. * make_unique_id_code
  7137. *
  7138. * @todo Finish documenting this function
  7139. *
  7140. * @uses $_SERVER
  7141. * @param string $extra Extra string to append to the end of the code
  7142. * @return string
  7143. */
  7144. function make_unique_id_code($extra = '') {
  7145. $hostname = 'unknownhost';
  7146. if (!empty($_SERVER['HTTP_HOST'])) {
  7147. $hostname = $_SERVER['HTTP_HOST'];
  7148. } else if (!empty($_ENV['HTTP_HOST'])) {
  7149. $hostname = $_ENV['HTTP_HOST'];
  7150. } else if (!empty($_SERVER['SERVER_NAME'])) {
  7151. $hostname = $_SERVER['SERVER_NAME'];
  7152. } else if (!empty($_ENV['SERVER_NAME'])) {
  7153. $hostname = $_ENV['SERVER_NAME'];
  7154. }
  7155. $date = gmdate("ymdHis");
  7156. $random = random_string(6);
  7157. if ($extra) {
  7158. return $hostname .'+'. $date .'+'. $random .'+'. $extra;
  7159. } else {
  7160. return $hostname .'+'. $date .'+'. $random;
  7161. }
  7162. }
  7163. /**
  7164. * Function to check the passed address is within the passed subnet
  7165. *
  7166. * The parameter is a comma separated string of subnet definitions.
  7167. * Subnet strings can be in one of three formats:
  7168. * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
  7169. * 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)
  7170. * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
  7171. * Code for type 1 modified from user posted comments by mediator at
  7172. * {@link http://au.php.net/manual/en/function.ip2long.php}
  7173. *
  7174. * @param string $addr The address you are checking
  7175. * @param string $subnetstr The string of subnet addresses
  7176. * @return bool
  7177. */
  7178. function address_in_subnet($addr, $subnetstr) {
  7179. if ($addr == '0.0.0.0') {
  7180. return false;
  7181. }
  7182. $subnets = explode(',', $subnetstr);
  7183. $found = false;
  7184. $addr = trim($addr);
  7185. $addr = cleanremoteaddr($addr, false); // Normalise.
  7186. if ($addr === null) {
  7187. return false;
  7188. }
  7189. $addrparts = explode(':', $addr);
  7190. $ipv6 = strpos($addr, ':');
  7191. foreach ($subnets as $subnet) {
  7192. $subnet = trim($subnet);
  7193. if ($subnet === '') {
  7194. continue;
  7195. }
  7196. if (strpos($subnet, '/') !== false) {
  7197. // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
  7198. list($ip, $mask) = explode('/', $subnet);
  7199. $mask = trim($mask);
  7200. if (!is_number($mask)) {
  7201. continue; // Incorect mask number, eh?
  7202. }
  7203. $ip = cleanremoteaddr($ip, false); // Normalise.
  7204. if ($ip === null) {
  7205. continue;
  7206. }
  7207. if (strpos($ip, ':') !== false) {
  7208. // IPv6.
  7209. if (!$ipv6) {
  7210. continue;
  7211. }
  7212. if ($mask > 128 or $mask < 0) {
  7213. continue; // Nonsense.
  7214. }
  7215. if ($mask == 0) {
  7216. return true; // Any address.
  7217. }
  7218. if ($mask == 128) {
  7219. if ($ip === $addr) {
  7220. return true;
  7221. }
  7222. continue;
  7223. }
  7224. $ipparts = explode(':', $ip);
  7225. $modulo = $mask % 16;
  7226. $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
  7227. $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
  7228. if (implode(':', $ipnet) === implode(':', $addrnet)) {
  7229. if ($modulo == 0) {
  7230. return true;
  7231. }
  7232. $pos = ($mask-$modulo)/16;
  7233. $ipnet = hexdec($ipparts[$pos]);
  7234. $addrnet = hexdec($addrparts[$pos]);
  7235. $mask = 0xffff << (16 - $modulo);
  7236. if (($addrnet & $mask) == ($ipnet & $mask)) {
  7237. return true;
  7238. }
  7239. }
  7240. } else {
  7241. // IPv4.
  7242. if ($ipv6) {
  7243. continue;
  7244. }
  7245. if ($mask > 32 or $mask < 0) {
  7246. continue; // Nonsense.
  7247. }
  7248. if ($mask == 0) {
  7249. return true;
  7250. }
  7251. if ($mask == 32) {
  7252. if ($ip === $addr) {
  7253. return true;
  7254. }
  7255. continue;
  7256. }
  7257. $mask = 0xffffffff << (32 - $mask);
  7258. if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
  7259. return true;
  7260. }
  7261. }
  7262. } else if (strpos($subnet, '-') !== false) {
  7263. // 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.
  7264. $parts = explode('-', $subnet);
  7265. if (count($parts) != 2) {
  7266. continue;
  7267. }
  7268. if (strpos($subnet, ':') !== false) {
  7269. // IPv6.
  7270. if (!$ipv6) {
  7271. continue;
  7272. }
  7273. $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
  7274. if ($ipstart === null) {
  7275. continue;
  7276. }
  7277. $ipparts = explode(':', $ipstart);
  7278. $start = hexdec(array_pop($ipparts));
  7279. $ipparts[] = trim($parts[1]);
  7280. $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
  7281. if ($ipend === null) {
  7282. continue;
  7283. }
  7284. $ipparts[7] = '';
  7285. $ipnet = implode(':', $ipparts);
  7286. if (strpos($addr, $ipnet) !== 0) {
  7287. continue;
  7288. }
  7289. $ipparts = explode(':', $ipend);
  7290. $end = hexdec($ipparts[7]);
  7291. $addrend = hexdec($addrparts[7]);
  7292. if (($addrend >= $start) and ($addrend <= $end)) {
  7293. return true;
  7294. }
  7295. } else {
  7296. // IPv4.
  7297. if ($ipv6) {
  7298. continue;
  7299. }
  7300. $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
  7301. if ($ipstart === null) {
  7302. continue;
  7303. }
  7304. $ipparts = explode('.', $ipstart);
  7305. $ipparts[3] = trim($parts[1]);
  7306. $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
  7307. if ($ipend === null) {
  7308. continue;
  7309. }
  7310. if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
  7311. return true;
  7312. }
  7313. }
  7314. } else {
  7315. // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
  7316. if (strpos($subnet, ':') !== false) {
  7317. // IPv6.
  7318. if (!$ipv6) {
  7319. continue;
  7320. }
  7321. $parts = explode(':', $subnet);
  7322. $count = count($parts);
  7323. if ($parts[$count-1] === '') {
  7324. unset($parts[$count-1]); // Trim trailing :'s.
  7325. $count--;
  7326. $subnet = implode('.', $parts);
  7327. }
  7328. $isip = cleanremoteaddr($subnet, false); // Normalise.
  7329. if ($isip !== null) {
  7330. if ($isip === $addr) {
  7331. return true;
  7332. }
  7333. continue;
  7334. } else if ($count > 8) {
  7335. continue;
  7336. }
  7337. $zeros = array_fill(0, 8-$count, '0');
  7338. $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
  7339. if (address_in_subnet($addr, $subnet)) {
  7340. return true;
  7341. }
  7342. } else {
  7343. // IPv4.
  7344. if ($ipv6) {
  7345. continue;
  7346. }
  7347. $parts = explode('.', $subnet);
  7348. $count = count($parts);
  7349. if ($parts[$count-1] === '') {
  7350. unset($parts[$count-1]); // Trim trailing .
  7351. $count--;
  7352. $subnet = implode('.', $parts);
  7353. }
  7354. if ($count == 4) {
  7355. $subnet = cleanremoteaddr($subnet, false); // Normalise.
  7356. if ($subnet === $addr) {
  7357. return true;
  7358. }
  7359. continue;
  7360. } else if ($count > 4) {
  7361. continue;
  7362. }
  7363. $zeros = array_fill(0, 4-$count, '0');
  7364. $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
  7365. if (address_in_subnet($addr, $subnet)) {
  7366. return true;
  7367. }
  7368. }
  7369. }
  7370. }
  7371. return false;
  7372. }
  7373. /**
  7374. * For outputting debugging info
  7375. *
  7376. * @param string $string The string to write
  7377. * @param string $eol The end of line char(s) to use
  7378. * @param string $sleep Period to make the application sleep
  7379. * This ensures any messages have time to display before redirect
  7380. */
  7381. function mtrace($string, $eol="\n", $sleep=0) {
  7382. if (defined('STDOUT') and !PHPUNIT_TEST) {
  7383. fwrite(STDOUT, $string.$eol);
  7384. } else {
  7385. echo $string . $eol;
  7386. }
  7387. flush();
  7388. // Delay to keep message on user's screen in case of subsequent redirect.
  7389. if ($sleep) {
  7390. sleep($sleep);
  7391. }
  7392. }
  7393. /**
  7394. * Replace 1 or more slashes or backslashes to 1 slash
  7395. *
  7396. * @param string $path The path to strip
  7397. * @return string the path with double slashes removed
  7398. */
  7399. function cleardoubleslashes ($path) {
  7400. return preg_replace('/(\/|\\\){1,}/', '/', $path);
  7401. }
  7402. /**
  7403. * Is current ip in give list?
  7404. *
  7405. * @param string $list
  7406. * @return bool
  7407. */
  7408. function remoteip_in_list($list) {
  7409. $inlist = false;
  7410. $clientip = getremoteaddr(null);
  7411. if (!$clientip) {
  7412. // Ensure access on cli.
  7413. return true;
  7414. }
  7415. $list = explode("\n", $list);
  7416. foreach ($list as $subnet) {
  7417. $subnet = trim($subnet);
  7418. if (address_in_subnet($clientip, $subnet)) {
  7419. $inlist = true;
  7420. break;
  7421. }
  7422. }
  7423. return $inlist;
  7424. }
  7425. /**
  7426. * Returns most reliable client address
  7427. *
  7428. * @param string $default If an address can't be determined, then return this
  7429. * @return string The remote IP address
  7430. */
  7431. function getremoteaddr($default='0.0.0.0') {
  7432. global $CFG;
  7433. if (empty($CFG->getremoteaddrconf)) {
  7434. // This will happen, for example, before just after the upgrade, as the
  7435. // user is redirected to the admin screen.
  7436. $variablestoskip = 0;
  7437. } else {
  7438. $variablestoskip = $CFG->getremoteaddrconf;
  7439. }
  7440. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
  7441. if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  7442. $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
  7443. return $address ? $address : $default;
  7444. }
  7445. }
  7446. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
  7447. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  7448. $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
  7449. return $address ? $address : $default;
  7450. }
  7451. }
  7452. if (!empty($_SERVER['REMOTE_ADDR'])) {
  7453. $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
  7454. return $address ? $address : $default;
  7455. } else {
  7456. return $default;
  7457. }
  7458. }
  7459. /**
  7460. * Cleans an ip address. Internal addresses are now allowed.
  7461. * (Originally local addresses were not allowed.)
  7462. *
  7463. * @param string $addr IPv4 or IPv6 address
  7464. * @param bool $compress use IPv6 address compression
  7465. * @return string normalised ip address string, null if error
  7466. */
  7467. function cleanremoteaddr($addr, $compress=false) {
  7468. $addr = trim($addr);
  7469. // TODO: maybe add a separate function is_addr_public() or something like this.
  7470. if (strpos($addr, ':') !== false) {
  7471. // Can be only IPv6.
  7472. $parts = explode(':', $addr);
  7473. $count = count($parts);
  7474. if (strpos($parts[$count-1], '.') !== false) {
  7475. // Legacy ipv4 notation.
  7476. $last = array_pop($parts);
  7477. $ipv4 = cleanremoteaddr($last, true);
  7478. if ($ipv4 === null) {
  7479. return null;
  7480. }
  7481. $bits = explode('.', $ipv4);
  7482. $parts[] = dechex($bits[0]).dechex($bits[1]);
  7483. $parts[] = dechex($bits[2]).dechex($bits[3]);
  7484. $count = count($parts);
  7485. $addr = implode(':', $parts);
  7486. }
  7487. if ($count < 3 or $count > 8) {
  7488. return null; // Severly malformed.
  7489. }
  7490. if ($count != 8) {
  7491. if (strpos($addr, '::') === false) {
  7492. return null; // Malformed.
  7493. }
  7494. // Uncompress.
  7495. $insertat = array_search('', $parts, true);
  7496. $missing = array_fill(0, 1 + 8 - $count, '0');
  7497. array_splice($parts, $insertat, 1, $missing);
  7498. foreach ($parts as $key => $part) {
  7499. if ($part === '') {
  7500. $parts[$key] = '0';
  7501. }
  7502. }
  7503. }
  7504. $adr = implode(':', $parts);
  7505. if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
  7506. return null; // Incorrect format - sorry.
  7507. }
  7508. // Normalise 0s and case.
  7509. $parts = array_map('hexdec', $parts);
  7510. $parts = array_map('dechex', $parts);
  7511. $result = implode(':', $parts);
  7512. if (!$compress) {
  7513. return $result;
  7514. }
  7515. if ($result === '0:0:0:0:0:0:0:0') {
  7516. return '::'; // All addresses.
  7517. }
  7518. $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
  7519. if ($compressed !== $result) {
  7520. return $compressed;
  7521. }
  7522. $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
  7523. if ($compressed !== $result) {
  7524. return $compressed;
  7525. }
  7526. $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
  7527. if ($compressed !== $result) {
  7528. return $compressed;
  7529. }
  7530. return $result;
  7531. }
  7532. // First get all things that look like IPv4 addresses.
  7533. $parts = array();
  7534. if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
  7535. return null;
  7536. }
  7537. unset($parts[0]);
  7538. foreach ($parts as $key => $match) {
  7539. if ($match > 255) {
  7540. return null;
  7541. }
  7542. $parts[$key] = (int)$match; // Normalise 0s.
  7543. }
  7544. return implode('.', $parts);
  7545. }
  7546. /**
  7547. * This function will make a complete copy of anything it's given,
  7548. * regardless of whether it's an object or not.
  7549. *
  7550. * @param mixed $thing Something you want cloned
  7551. * @return mixed What ever it is you passed it
  7552. */
  7553. function fullclone($thing) {
  7554. return unserialize(serialize($thing));
  7555. }
  7556. /**
  7557. * If new messages are waiting for the current user, then insert
  7558. * JavaScript to pop up the messaging window into the page
  7559. *
  7560. * @return void
  7561. */
  7562. function message_popup_window() {
  7563. global $USER, $DB, $PAGE, $CFG;
  7564. if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
  7565. return;
  7566. }
  7567. if (!isloggedin() || isguestuser()) {
  7568. return;
  7569. }
  7570. if (!isset($USER->message_lastpopup)) {
  7571. $USER->message_lastpopup = 0;
  7572. } else if ($USER->message_lastpopup > (time()-120)) {
  7573. // Don't run the query to check whether to display a popup if its been run in the last 2 minutes.
  7574. return;
  7575. }
  7576. // A quick query to check whether the user has new messages.
  7577. $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
  7578. if ($messagecount < 1) {
  7579. return;
  7580. }
  7581. // There are unread messages so now do a more complex but slower query.
  7582. $messagesql = "SELECT m.id, c.blocked
  7583. FROM {message} m
  7584. JOIN {message_working} mw ON m.id=mw.unreadmessageid
  7585. JOIN {message_processors} p ON mw.processorid=p.id
  7586. JOIN {user} u ON m.useridfrom=u.id
  7587. LEFT JOIN {message_contacts} c ON c.contactid = m.useridfrom
  7588. AND c.userid = m.useridto
  7589. WHERE m.useridto = :userid
  7590. AND p.name='popup'";
  7591. // If the user was last notified over an hour ago we can re-notify them of old messages
  7592. // so don't worry about when the new message was sent.
  7593. $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
  7594. if (!$lastnotifiedlongago) {
  7595. $messagesql .= 'AND m.timecreated > :lastpopuptime';
  7596. }
  7597. $waitingmessages = $DB->get_records_sql($messagesql, array('userid' => $USER->id, 'lastpopuptime' => $USER->message_lastpopup));
  7598. $validmessages = 0;
  7599. foreach ($waitingmessages as $messageinfo) {
  7600. if ($messageinfo->blocked) {
  7601. // Message is from a user who has since been blocked so just mark it read.
  7602. // Get the full message to mark as read.
  7603. $messageobject = $DB->get_record('message', array('id' => $messageinfo->id));
  7604. message_mark_message_read($messageobject, time());
  7605. } else {
  7606. $validmessages++;
  7607. }
  7608. }
  7609. if ($validmessages > 0) {
  7610. $strmessages = get_string('unreadnewmessages', 'message', $validmessages);
  7611. $strgomessage = get_string('gotomessages', 'message');
  7612. $strstaymessage = get_string('ignore', 'admin');
  7613. $notificationsound = null;
  7614. $beep = get_user_preferences('message_beepnewmessage', '');
  7615. if (!empty($beep)) {
  7616. // Browsers will work down this list until they find something they support.
  7617. $sourcetags = html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.wav', 'type' => 'audio/wav'));
  7618. $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.ogg', 'type' => 'audio/ogg'));
  7619. $sourcetags .= html_writer::empty_tag('source', array('src' => $CFG->wwwroot.'/message/bell.mp3', 'type' => 'audio/mpeg'));
  7620. $sourcetags .= html_writer::empty_tag('embed', array('src' => $CFG->wwwroot.'/message/bell.wav', 'autostart' => 'true', 'hidden' => 'true'));
  7621. $notificationsound = html_writer::tag('audio', $sourcetags, array('preload' => 'auto', 'autoplay' => 'autoplay'));
  7622. }
  7623. $url = $CFG->wwwroot.'/message/index.php';
  7624. $content = html_writer::start_tag('div', array('id' => 'newmessageoverlay', 'class' => 'mdl-align')).
  7625. html_writer::start_tag('div', array('id' => 'newmessagetext')).
  7626. $strmessages.
  7627. html_writer::end_tag('div').
  7628. $notificationsound.
  7629. html_writer::start_tag('div', array('id' => 'newmessagelinks')).
  7630. html_writer::link($url, $strgomessage, array('id' => 'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
  7631. html_writer::link('', $strstaymessage, array('id' => 'notificationno')).
  7632. html_writer::end_tag('div');
  7633. html_writer::end_tag('div');
  7634. $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
  7635. $USER->message_lastpopup = time();
  7636. }
  7637. }
  7638. /**
  7639. * Used to make sure that $min <= $value <= $max
  7640. *
  7641. * Make sure that value is between min, and max
  7642. *
  7643. * @param int $min The minimum value
  7644. * @param int $value The value to check
  7645. * @param int $max The maximum value
  7646. * @return int
  7647. */
  7648. function bounded_number($min, $value, $max) {
  7649. if ($value < $min) {
  7650. return $min;
  7651. }
  7652. if ($value > $max) {
  7653. return $max;
  7654. }
  7655. return $value;
  7656. }
  7657. /**
  7658. * Check if there is a nested array within the passed array
  7659. *
  7660. * @param array $array
  7661. * @return bool true if there is a nested array false otherwise
  7662. */
  7663. function array_is_nested($array) {
  7664. foreach ($array as $value) {
  7665. if (is_array($value)) {
  7666. return true;
  7667. }
  7668. }
  7669. return false;
  7670. }
  7671. /**
  7672. * get_performance_info() pairs up with init_performance_info()
  7673. * loaded in setup.php. Returns an array with 'html' and 'txt'
  7674. * values ready for use, and each of the individual stats provided
  7675. * separately as well.
  7676. *
  7677. * @return array
  7678. */
  7679. function get_performance_info() {
  7680. global $CFG, $PERF, $DB, $PAGE;
  7681. $info = array();
  7682. $info['html'] = ''; // Holds userfriendly HTML representation.
  7683. $info['txt'] = me() . ' '; // Holds log-friendly representation.
  7684. $info['realtime'] = microtime_diff($PERF->starttime, microtime());
  7685. $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
  7686. $info['txt'] .= 'time: '.$info['realtime'].'s ';
  7687. if (function_exists('memory_get_usage')) {
  7688. $info['memory_total'] = memory_get_usage();
  7689. $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
  7690. $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
  7691. $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
  7692. $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
  7693. }
  7694. if (function_exists('memory_get_peak_usage')) {
  7695. $info['memory_peak'] = memory_get_peak_usage();
  7696. $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
  7697. $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
  7698. }
  7699. $inc = get_included_files();
  7700. $info['includecount'] = count($inc);
  7701. $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
  7702. $info['txt'] .= 'includecount: '.$info['includecount'].' ';
  7703. if (!empty($CFG->early_install_lang) or empty($PAGE)) {
  7704. // We can not track more performance before installation or before PAGE init, sorry.
  7705. return $info;
  7706. }
  7707. $filtermanager = filter_manager::instance();
  7708. if (method_exists($filtermanager, 'get_performance_summary')) {
  7709. list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
  7710. $info = array_merge($filterinfo, $info);
  7711. foreach ($filterinfo as $key => $value) {
  7712. $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
  7713. $info['txt'] .= "$key: $value ";
  7714. }
  7715. }
  7716. $stringmanager = get_string_manager();
  7717. if (method_exists($stringmanager, 'get_performance_summary')) {
  7718. list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
  7719. $info = array_merge($filterinfo, $info);
  7720. foreach ($filterinfo as $key => $value) {
  7721. $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
  7722. $info['txt'] .= "$key: $value ";
  7723. }
  7724. }
  7725. $jsmodules = $PAGE->requires->get_loaded_modules();
  7726. if ($jsmodules) {
  7727. $yuicount = 0;
  7728. $othercount = 0;
  7729. $details = '';
  7730. foreach ($jsmodules as $module => $backtraces) {
  7731. if (strpos($module, 'yui') === 0) {
  7732. $yuicount += 1;
  7733. } else {
  7734. $othercount += 1;
  7735. }
  7736. if (!empty($CFG->yuimoduledebug)) {
  7737. // Hidden feature for developers working on YUI module infrastructure.
  7738. $details .= "<div class='yui-module'><p>$module</p>";
  7739. foreach ($backtraces as $backtrace) {
  7740. $details .= "<div class='backtrace'>$backtrace</div>";
  7741. }
  7742. $details .= '</div>';
  7743. }
  7744. }
  7745. $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> ";
  7746. $info['txt'] .= "includedyuimodules: $yuicount ";
  7747. $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> ";
  7748. $info['txt'] .= "includedjsmodules: $othercount ";
  7749. if ($details) {
  7750. $info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>';
  7751. }
  7752. }
  7753. if (!empty($PERF->logwrites)) {
  7754. $info['logwrites'] = $PERF->logwrites;
  7755. $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
  7756. $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
  7757. }
  7758. $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
  7759. $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
  7760. $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
  7761. $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
  7762. $info['html'] .= '<span class="dbtime">DB queries time: '.$info['dbtime'].' secs</span> ';
  7763. $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
  7764. if (function_exists('posix_times')) {
  7765. $ptimes = posix_times();
  7766. if (is_array($ptimes)) {
  7767. foreach ($ptimes as $key => $val) {
  7768. $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
  7769. }
  7770. $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
  7771. $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
  7772. }
  7773. }
  7774. // Grab the load average for the last minute.
  7775. // /proc will only work under some linux configurations
  7776. // while uptime is there under MacOSX/Darwin and other unices.
  7777. if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
  7778. list($serverload) = explode(' ', $loadavg[0]);
  7779. unset($loadavg);
  7780. } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
  7781. if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
  7782. $serverload = $matches[1];
  7783. } else {
  7784. trigger_error('Could not parse uptime output!');
  7785. }
  7786. }
  7787. if (!empty($serverload)) {
  7788. $info['serverload'] = $serverload;
  7789. $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
  7790. $info['txt'] .= "serverload: {$info['serverload']} ";
  7791. }
  7792. // Display size of session if session started.
  7793. if ($si = \core\session\manager::get_performance_info()) {
  7794. $info['sessionsize'] = $si['size'];
  7795. $info['html'] .= $si['html'];
  7796. $info['txt'] .= $si['txt'];
  7797. }
  7798. if ($stats = cache_helper::get_stats()) {
  7799. $html = '<span class="cachesused">';
  7800. $html .= '<span class="cache-stats-heading">Caches used (hits/misses/sets)</span>';
  7801. $text = 'Caches used (hits/misses/sets): ';
  7802. $hits = 0;
  7803. $misses = 0;
  7804. $sets = 0;
  7805. foreach ($stats as $definition => $stores) {
  7806. $html .= '<span class="cache-definition-stats">';
  7807. $html .= '<span class="cache-definition-stats-heading">'.$definition.'</span>';
  7808. $text .= "$definition {";
  7809. foreach ($stores as $store => $data) {
  7810. $hits += $data['hits'];
  7811. $misses += $data['misses'];
  7812. $sets += $data['sets'];
  7813. if ($data['hits'] == 0 and $data['misses'] > 0) {
  7814. $cachestoreclass = 'nohits';
  7815. } else if ($data['hits'] < $data['misses']) {
  7816. $cachestoreclass = 'lowhits';
  7817. } else {
  7818. $cachestoreclass = 'hihits';
  7819. }
  7820. $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
  7821. $html .= "<span class=\"cache-store-stats $cachestoreclass\">$store: $data[hits] / $data[misses] / $data[sets]</span>";
  7822. }
  7823. $html .= '</span>';
  7824. $text .= '} ';
  7825. }
  7826. $html .= "<span class='cache-total-stats'>Total: $hits / $misses / $sets</span>";
  7827. $html .= '</span> ';
  7828. $info['cachesused'] = "$hits / $misses / $sets";
  7829. $info['html'] .= $html;
  7830. $info['txt'] .= $text.'. ';
  7831. } else {
  7832. $info['cachesused'] = '0 / 0 / 0';
  7833. $info['html'] .= '<span class="cachesused">Caches used (hits/misses/sets): 0/0/0</span>';
  7834. $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
  7835. }
  7836. $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
  7837. return $info;
  7838. }
  7839. /**
  7840. * Legacy function.
  7841. *
  7842. * @todo Document this function linux people
  7843. */
  7844. function apd_get_profiling() {
  7845. return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
  7846. }
  7847. /**
  7848. * Delete directory or only its content
  7849. *
  7850. * @param string $dir directory path
  7851. * @param bool $contentonly
  7852. * @return bool success, true also if dir does not exist
  7853. */
  7854. function remove_dir($dir, $contentonly=false) {
  7855. if (!file_exists($dir)) {
  7856. // Nothing to do.
  7857. return true;
  7858. }
  7859. if (!$handle = opendir($dir)) {
  7860. return false;
  7861. }
  7862. $result = true;
  7863. while (false!==($item = readdir($handle))) {
  7864. if ($item != '.' && $item != '..') {
  7865. if (is_dir($dir.'/'.$item)) {
  7866. $result = remove_dir($dir.'/'.$item) && $result;
  7867. } else {
  7868. $result = unlink($dir.'/'.$item) && $result;
  7869. }
  7870. }
  7871. }
  7872. closedir($handle);
  7873. if ($contentonly) {
  7874. clearstatcache(); // Make sure file stat cache is properly invalidated.
  7875. return $result;
  7876. }
  7877. $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
  7878. clearstatcache(); // Make sure file stat cache is properly invalidated.
  7879. return $result;
  7880. }
  7881. /**
  7882. * Detect if an object or a class contains a given property
  7883. * will take an actual object or the name of a class
  7884. *
  7885. * @param mix $obj Name of class or real object to test
  7886. * @param string $property name of property to find
  7887. * @return bool true if property exists
  7888. */
  7889. function object_property_exists( $obj, $property ) {
  7890. if (is_string( $obj )) {
  7891. $properties = get_class_vars( $obj );
  7892. } else {
  7893. $properties = get_object_vars( $obj );
  7894. }
  7895. return array_key_exists( $property, $properties );
  7896. }
  7897. /**
  7898. * Converts an object into an associative array
  7899. *
  7900. * This function converts an object into an associative array by iterating
  7901. * over its public properties. Because this function uses the foreach
  7902. * construct, Iterators are respected. It works recursively on arrays of objects.
  7903. * Arrays and simple values are returned as is.
  7904. *
  7905. * If class has magic properties, it can implement IteratorAggregate
  7906. * and return all available properties in getIterator()
  7907. *
  7908. * @param mixed $var
  7909. * @return array
  7910. */
  7911. function convert_to_array($var) {
  7912. $result = array();
  7913. // Loop over elements/properties.
  7914. foreach ($var as $key => $value) {
  7915. // Recursively convert objects.
  7916. if (is_object($value) || is_array($value)) {
  7917. $result[$key] = convert_to_array($value);
  7918. } else {
  7919. // Simple values are untouched.
  7920. $result[$key] = $value;
  7921. }
  7922. }
  7923. return $result;
  7924. }
  7925. /**
  7926. * Detect a custom script replacement in the data directory that will
  7927. * replace an existing moodle script
  7928. *
  7929. * @return string|bool full path name if a custom script exists, false if no custom script exists
  7930. */
  7931. function custom_script_path() {
  7932. global $CFG, $SCRIPT;
  7933. if ($SCRIPT === null) {
  7934. // Probably some weird external script.
  7935. return false;
  7936. }
  7937. $scriptpath = $CFG->customscripts . $SCRIPT;
  7938. // Check the custom script exists.
  7939. if (file_exists($scriptpath) and is_file($scriptpath)) {
  7940. return $scriptpath;
  7941. } else {
  7942. return false;
  7943. }
  7944. }
  7945. /**
  7946. * Returns whether or not the user object is a remote MNET user. This function
  7947. * is in moodlelib because it does not rely on loading any of the MNET code.
  7948. *
  7949. * @param object $user A valid user object
  7950. * @return bool True if the user is from a remote Moodle.
  7951. */
  7952. function is_mnet_remote_user($user) {
  7953. global $CFG;
  7954. if (!isset($CFG->mnet_localhost_id)) {
  7955. include_once($CFG->dirroot . '/mnet/lib.php');
  7956. $env = new mnet_environment();
  7957. $env->init();
  7958. unset($env);
  7959. }
  7960. return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
  7961. }
  7962. /**
  7963. * This function will search for browser prefereed languages, setting Moodle
  7964. * to use the best one available if $SESSION->lang is undefined
  7965. */
  7966. function setup_lang_from_browser() {
  7967. global $CFG, $SESSION, $USER;
  7968. if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
  7969. // Lang is defined in session or user profile, nothing to do.
  7970. return;
  7971. }
  7972. if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
  7973. return;
  7974. }
  7975. // Extract and clean langs from headers.
  7976. $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  7977. $rawlangs = str_replace('-', '_', $rawlangs); // We are using underscores.
  7978. $rawlangs = explode(',', $rawlangs); // Convert to array.
  7979. $langs = array();
  7980. $order = 1.0;
  7981. foreach ($rawlangs as $lang) {
  7982. if (strpos($lang, ';') === false) {
  7983. $langs[(string)$order] = $lang;
  7984. $order = $order-0.01;
  7985. } else {
  7986. $parts = explode(';', $lang);
  7987. $pos = strpos($parts[1], '=');
  7988. $langs[substr($parts[1], $pos+1)] = $parts[0];
  7989. }
  7990. }
  7991. krsort($langs, SORT_NUMERIC);
  7992. // Look for such langs under standard locations.
  7993. foreach ($langs as $lang) {
  7994. // Clean it properly for include.
  7995. $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
  7996. if (get_string_manager()->translation_exists($lang, false)) {
  7997. // Lang exists, set it in session.
  7998. $SESSION->lang = $lang;
  7999. // We have finished. Go out.
  8000. break;
  8001. }
  8002. }
  8003. return;
  8004. }
  8005. /**
  8006. * Check if $url matches anything in proxybypass list
  8007. *
  8008. * Any errors just result in the proxy being used (least bad)
  8009. *
  8010. * @param string $url url to check
  8011. * @return boolean true if we should bypass the proxy
  8012. */
  8013. function is_proxybypass( $url ) {
  8014. global $CFG;
  8015. // Sanity check.
  8016. if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
  8017. return false;
  8018. }
  8019. // Get the host part out of the url.
  8020. if (!$host = parse_url( $url, PHP_URL_HOST )) {
  8021. return false;
  8022. }
  8023. // Get the possible bypass hosts into an array.
  8024. $matches = explode( ',', $CFG->proxybypass );
  8025. // Check for a match.
  8026. // (IPs need to match the left hand side and hosts the right of the url,
  8027. // but we can recklessly check both as there can't be a false +ve).
  8028. foreach ($matches as $match) {
  8029. $match = trim($match);
  8030. // Try for IP match (Left side).
  8031. $lhs = substr($host, 0, strlen($match));
  8032. if (strcasecmp($match, $lhs)==0) {
  8033. return true;
  8034. }
  8035. // Try for host match (Right side).
  8036. $rhs = substr($host, -strlen($match));
  8037. if (strcasecmp($match, $rhs)==0) {
  8038. return true;
  8039. }
  8040. }
  8041. // Nothing matched.
  8042. return false;
  8043. }
  8044. /**
  8045. * Check if the passed navigation is of the new style
  8046. *
  8047. * @param mixed $navigation
  8048. * @return bool true for yes false for no
  8049. */
  8050. function is_newnav($navigation) {
  8051. if (is_array($navigation) && !empty($navigation['newnav'])) {
  8052. return true;
  8053. } else {
  8054. return false;
  8055. }
  8056. }
  8057. /**
  8058. * Checks whether the given variable name is defined as a variable within the given object.
  8059. *
  8060. * This will NOT work with stdClass objects, which have no class variables.
  8061. *
  8062. * @param string $var The variable name
  8063. * @param object $object The object to check
  8064. * @return boolean
  8065. */
  8066. function in_object_vars($var, $object) {
  8067. $classvars = get_class_vars(get_class($object));
  8068. $classvars = array_keys($classvars);
  8069. return in_array($var, $classvars);
  8070. }
  8071. /**
  8072. * Returns an array without repeated objects.
  8073. * This function is similar to array_unique, but for arrays that have objects as values
  8074. *
  8075. * @param array $array
  8076. * @param bool $keepkeyassoc
  8077. * @return array
  8078. */
  8079. function object_array_unique($array, $keepkeyassoc = true) {
  8080. $duplicatekeys = array();
  8081. $tmp = array();
  8082. foreach ($array as $key => $val) {
  8083. // Convert objects to arrays, in_array() does not support objects.
  8084. if (is_object($val)) {
  8085. $val = (array)$val;
  8086. }
  8087. if (!in_array($val, $tmp)) {
  8088. $tmp[] = $val;
  8089. } else {
  8090. $duplicatekeys[] = $key;
  8091. }
  8092. }
  8093. foreach ($duplicatekeys as $key) {
  8094. unset($array[$key]);
  8095. }
  8096. return $keepkeyassoc ? $array : array_values($array);
  8097. }
  8098. /**
  8099. * Is a userid the primary administrator?
  8100. *
  8101. * @param int $userid int id of user to check
  8102. * @return boolean
  8103. */
  8104. function is_primary_admin($userid) {
  8105. $primaryadmin = get_admin();
  8106. if ($userid == $primaryadmin->id) {
  8107. return true;
  8108. } else {
  8109. return false;
  8110. }
  8111. }
  8112. /**
  8113. * Returns the site identifier
  8114. *
  8115. * @return string $CFG->siteidentifier, first making sure it is properly initialised.
  8116. */
  8117. function get_site_identifier() {
  8118. global $CFG;
  8119. // Check to see if it is missing. If so, initialise it.
  8120. if (empty($CFG->siteidentifier)) {
  8121. set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
  8122. }
  8123. // Return it.
  8124. return $CFG->siteidentifier;
  8125. }
  8126. /**
  8127. * Check whether the given password has no more than the specified
  8128. * number of consecutive identical characters.
  8129. *
  8130. * @param string $password password to be checked against the password policy
  8131. * @param integer $maxchars maximum number of consecutive identical characters
  8132. * @return bool
  8133. */
  8134. function check_consecutive_identical_characters($password, $maxchars) {
  8135. if ($maxchars < 1) {
  8136. return true; // Zero 0 is to disable this check.
  8137. }
  8138. if (strlen($password) <= $maxchars) {
  8139. return true; // Too short to fail this test.
  8140. }
  8141. $previouschar = '';
  8142. $consecutivecount = 1;
  8143. foreach (str_split($password) as $char) {
  8144. if ($char != $previouschar) {
  8145. $consecutivecount = 1;
  8146. } else {
  8147. $consecutivecount++;
  8148. if ($consecutivecount > $maxchars) {
  8149. return false; // Check failed already.
  8150. }
  8151. }
  8152. $previouschar = $char;
  8153. }
  8154. return true;
  8155. }
  8156. /**
  8157. * Helper function to do partial function binding.
  8158. * so we can use it for preg_replace_callback, for example
  8159. * this works with php functions, user functions, static methods and class methods
  8160. * it returns you a callback that you can pass on like so:
  8161. *
  8162. * $callback = partial('somefunction', $arg1, $arg2);
  8163. * or
  8164. * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
  8165. * or even
  8166. * $obj = new someclass();
  8167. * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
  8168. *
  8169. * and then the arguments that are passed through at calltime are appended to the argument list.
  8170. *
  8171. * @param mixed $function a php callback
  8172. * @param mixed $arg1,... $argv arguments to partially bind with
  8173. * @return array Array callback
  8174. */
  8175. function partial() {
  8176. if (!class_exists('partial')) {
  8177. /**
  8178. * Used to manage function binding.
  8179. * @copyright 2009 Penny Leach
  8180. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  8181. */
  8182. class partial{
  8183. /** @var array */
  8184. public $values = array();
  8185. /** @var string The function to call as a callback. */
  8186. public $func;
  8187. /**
  8188. * Constructor
  8189. * @param string $func
  8190. * @param array $args
  8191. */
  8192. public function __construct($func, $args) {
  8193. $this->values = $args;
  8194. $this->func = $func;
  8195. }
  8196. /**
  8197. * Calls the callback function.
  8198. * @return mixed
  8199. */
  8200. public function method() {
  8201. $args = func_get_args();
  8202. return call_user_func_array($this->func, array_merge($this->values, $args));
  8203. }
  8204. }
  8205. }
  8206. $args = func_get_args();
  8207. $func = array_shift($args);
  8208. $p = new partial($func, $args);
  8209. return array($p, 'method');
  8210. }
  8211. /**
  8212. * helper function to load up and initialise the mnet environment
  8213. * this must be called before you use mnet functions.
  8214. *
  8215. * @return mnet_environment the equivalent of old $MNET global
  8216. */
  8217. function get_mnet_environment() {
  8218. global $CFG;
  8219. require_once($CFG->dirroot . '/mnet/lib.php');
  8220. static $instance = null;
  8221. if (empty($instance)) {
  8222. $instance = new mnet_environment();
  8223. $instance->init();
  8224. }
  8225. return $instance;
  8226. }
  8227. /**
  8228. * during xmlrpc server code execution, any code wishing to access
  8229. * information about the remote peer must use this to get it.
  8230. *
  8231. * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
  8232. */
  8233. function get_mnet_remote_client() {
  8234. if (!defined('MNET_SERVER')) {
  8235. debugging(get_string('notinxmlrpcserver', 'mnet'));
  8236. return false;
  8237. }
  8238. global $MNET_REMOTE_CLIENT;
  8239. if (isset($MNET_REMOTE_CLIENT)) {
  8240. return $MNET_REMOTE_CLIENT;
  8241. }
  8242. return false;
  8243. }
  8244. /**
  8245. * during the xmlrpc server code execution, this will be called
  8246. * to setup the object returned by {@link get_mnet_remote_client}
  8247. *
  8248. * @param mnet_remote_client $client the client to set up
  8249. * @throws moodle_exception
  8250. */
  8251. function set_mnet_remote_client($client) {
  8252. if (!defined('MNET_SERVER')) {
  8253. throw new moodle_exception('notinxmlrpcserver', 'mnet');
  8254. }
  8255. global $MNET_REMOTE_CLIENT;
  8256. $MNET_REMOTE_CLIENT = $client;
  8257. }
  8258. /**
  8259. * return the jump url for a given remote user
  8260. * this is used for rewriting forum post links in emails, etc
  8261. *
  8262. * @param stdclass $user the user to get the idp url for
  8263. */
  8264. function mnet_get_idp_jump_url($user) {
  8265. global $CFG;
  8266. static $mnetjumps = array();
  8267. if (!array_key_exists($user->mnethostid, $mnetjumps)) {
  8268. $idp = mnet_get_peer_host($user->mnethostid);
  8269. $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
  8270. $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
  8271. }
  8272. return $mnetjumps[$user->mnethostid];
  8273. }
  8274. /**
  8275. * Gets the homepage to use for the current user
  8276. *
  8277. * @return int One of HOMEPAGE_*
  8278. */
  8279. function get_home_page() {
  8280. global $CFG;
  8281. if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
  8282. if ($CFG->defaulthomepage == HOMEPAGE_MY) {
  8283. return HOMEPAGE_MY;
  8284. } else {
  8285. return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
  8286. }
  8287. }
  8288. return HOMEPAGE_SITE;
  8289. }
  8290. /**
  8291. * Gets the name of a course to be displayed when showing a list of courses.
  8292. * By default this is just $course->fullname but user can configure it. The
  8293. * result of this function should be passed through print_string.
  8294. * @param stdClass|course_in_list $course Moodle course object
  8295. * @return string Display name of course (either fullname or short + fullname)
  8296. */
  8297. function get_course_display_name_for_list($course) {
  8298. global $CFG;
  8299. if (!empty($CFG->courselistshortnames)) {
  8300. if (!($course instanceof stdClass)) {
  8301. $course = (object)convert_to_array($course);
  8302. }
  8303. return get_string('courseextendednamedisplay', '', $course);
  8304. } else {
  8305. return $course->fullname;
  8306. }
  8307. }
  8308. /**
  8309. * The lang_string class
  8310. *
  8311. * This special class is used to create an object representation of a string request.
  8312. * It is special because processing doesn't occur until the object is first used.
  8313. * The class was created especially to aid performance in areas where strings were
  8314. * required to be generated but were not necessarily used.
  8315. * As an example the admin tree when generated uses over 1500 strings, of which
  8316. * normally only 1/3 are ever actually printed at any time.
  8317. * The performance advantage is achieved by not actually processing strings that
  8318. * arn't being used, as such reducing the processing required for the page.
  8319. *
  8320. * How to use the lang_string class?
  8321. * There are two methods of using the lang_string class, first through the
  8322. * forth argument of the get_string function, and secondly directly.
  8323. * The following are examples of both.
  8324. * 1. Through get_string calls e.g.
  8325. * $string = get_string($identifier, $component, $a, true);
  8326. * $string = get_string('yes', 'moodle', null, true);
  8327. * 2. Direct instantiation
  8328. * $string = new lang_string($identifier, $component, $a, $lang);
  8329. * $string = new lang_string('yes');
  8330. *
  8331. * How do I use a lang_string object?
  8332. * The lang_string object makes use of a magic __toString method so that you
  8333. * are able to use the object exactly as you would use a string in most cases.
  8334. * This means you are able to collect it into a variable and then directly
  8335. * echo it, or concatenate it into another string, or similar.
  8336. * The other thing you can do is manually get the string by calling the
  8337. * lang_strings out method e.g.
  8338. * $string = new lang_string('yes');
  8339. * $string->out();
  8340. * Also worth noting is that the out method can take one argument, $lang which
  8341. * allows the developer to change the language on the fly.
  8342. *
  8343. * When should I use a lang_string object?
  8344. * The lang_string object is designed to be used in any situation where a
  8345. * string may not be needed, but needs to be generated.
  8346. * The admin tree is a good example of where lang_string objects should be
  8347. * used.
  8348. * A more practical example would be any class that requries strings that may
  8349. * not be printed (after all classes get renderer by renderers and who knows
  8350. * what they will do ;))
  8351. *
  8352. * When should I not use a lang_string object?
  8353. * Don't use lang_strings when you are going to use a string immediately.
  8354. * There is no need as it will be processed immediately and there will be no
  8355. * advantage, and in fact perhaps a negative hit as a class has to be
  8356. * instantiated for a lang_string object, however get_string won't require
  8357. * that.
  8358. *
  8359. * Limitations:
  8360. * 1. You cannot use a lang_string object as an array offset. Doing so will
  8361. * result in PHP throwing an error. (You can use it as an object property!)
  8362. *
  8363. * @package core
  8364. * @category string
  8365. * @copyright 2011 Sam Hemelryk
  8366. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  8367. */
  8368. class lang_string {
  8369. /** @var string The strings identifier */
  8370. protected $identifier;
  8371. /** @var string The strings component. Default '' */
  8372. protected $component = '';
  8373. /** @var array|stdClass Any arguments required for the string. Default null */
  8374. protected $a = null;
  8375. /** @var string The language to use when processing the string. Default null */
  8376. protected $lang = null;
  8377. /** @var string The processed string (once processed) */
  8378. protected $string = null;
  8379. /**
  8380. * A special boolean. If set to true then the object has been woken up and
  8381. * cannot be regenerated. If this is set then $this->string MUST be used.
  8382. * @var bool
  8383. */
  8384. protected $forcedstring = false;
  8385. /**
  8386. * Constructs a lang_string object
  8387. *
  8388. * This function should do as little processing as possible to ensure the best
  8389. * performance for strings that won't be used.
  8390. *
  8391. * @param string $identifier The strings identifier
  8392. * @param string $component The strings component
  8393. * @param stdClass|array $a Any arguments the string requires
  8394. * @param string $lang The language to use when processing the string.
  8395. * @throws coding_exception
  8396. */
  8397. public function __construct($identifier, $component = '', $a = null, $lang = null) {
  8398. if (empty($component)) {
  8399. $component = 'moodle';
  8400. }
  8401. $this->identifier = $identifier;
  8402. $this->component = $component;
  8403. $this->lang = $lang;
  8404. // We MUST duplicate $a to ensure that it if it changes by reference those
  8405. // changes are not carried across.
  8406. // To do this we always ensure $a or its properties/values are strings
  8407. // and that any properties/values that arn't convertable are forgotten.
  8408. if (!empty($a)) {
  8409. if (is_scalar($a)) {
  8410. $this->a = $a;
  8411. } else if ($a instanceof lang_string) {
  8412. $this->a = $a->out();
  8413. } else if (is_object($a) or is_array($a)) {
  8414. $a = (array)$a;
  8415. $this->a = array();
  8416. foreach ($a as $key => $value) {
  8417. // Make sure conversion errors don't get displayed (results in '').
  8418. if (is_array($value)) {
  8419. $this->a[$key] = '';
  8420. } else if (is_object($value)) {
  8421. if (method_exists($value, '__toString')) {
  8422. $this->a[$key] = $value->__toString();
  8423. } else {
  8424. $this->a[$key] = '';
  8425. }
  8426. } else {
  8427. $this->a[$key] = (string)$value;
  8428. }
  8429. }
  8430. }
  8431. }
  8432. if (debugging(false, DEBUG_DEVELOPER)) {
  8433. if (clean_param($this->identifier, PARAM_STRINGID) == '') {
  8434. throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
  8435. }
  8436. if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
  8437. throw new coding_exception('Invalid string compontent. Please check your string definition');
  8438. }
  8439. if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
  8440. debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
  8441. }
  8442. }
  8443. }
  8444. /**
  8445. * Processes the string.
  8446. *
  8447. * This function actually processes the string, stores it in the string property
  8448. * and then returns it.
  8449. * You will notice that this function is VERY similar to the get_string method.
  8450. * That is because it is pretty much doing the same thing.
  8451. * However as this function is an upgrade it isn't as tolerant to backwards
  8452. * compatibility.
  8453. *
  8454. * @return string
  8455. * @throws coding_exception
  8456. */
  8457. protected function get_string() {
  8458. global $CFG;
  8459. // Check if we need to process the string.
  8460. if ($this->string === null) {
  8461. // Check the quality of the identifier.
  8462. if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
  8463. 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);
  8464. }
  8465. // Process the string.
  8466. $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
  8467. // Debugging feature lets you display string identifier and component.
  8468. if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
  8469. $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
  8470. }
  8471. }
  8472. // Return the string.
  8473. return $this->string;
  8474. }
  8475. /**
  8476. * Returns the string
  8477. *
  8478. * @param string $lang The langauge to use when processing the string
  8479. * @return string
  8480. */
  8481. public function out($lang = null) {
  8482. if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
  8483. if ($this->forcedstring) {
  8484. debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
  8485. return $this->get_string();
  8486. }
  8487. $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
  8488. return $translatedstring->out();
  8489. }
  8490. return $this->get_string();
  8491. }
  8492. /**
  8493. * Magic __toString method for printing a string
  8494. *
  8495. * @return string
  8496. */
  8497. public function __toString() {
  8498. return $this->get_string();
  8499. }
  8500. /**
  8501. * Magic __set_state method used for var_export
  8502. *
  8503. * @return string
  8504. */
  8505. public function __set_state() {
  8506. return $this->get_string();
  8507. }
  8508. /**
  8509. * Prepares the lang_string for sleep and stores only the forcedstring and
  8510. * string properties... the string cannot be regenerated so we need to ensure
  8511. * it is generated for this.
  8512. *
  8513. * @return string
  8514. */
  8515. public function __sleep() {
  8516. $this->get_string();
  8517. $this->forcedstring = true;
  8518. return array('forcedstring', 'string', 'lang');
  8519. }
  8520. }