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

/lib/moodlelib.php

https://bitbucket.org/ngmares/moodle
PHP | 10996 lines | 6251 code | 1374 blank | 3371 comment | 1527 complexity | fbb73babaa355e854f73a97939e09b8c MD5 | raw file
Possible License(s): LGPL-2.1, AGPL-3.0, MPL-2.0-no-copyleft-exception, GPL-3.0, Apache-2.0, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * moodlelib.php - Moodle main library
  18. *
  19. * Main library file of miscellaneous general-purpose Moodle functions.
  20. * Other main libraries:
  21. * - weblib.php - functions that produce web output
  22. * - datalib.php - functions that access the database
  23. *
  24. * @package core
  25. * @subpackage lib
  26. * @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
  27. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  28. */
  29. defined('MOODLE_INTERNAL') || die();
  30. /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
  31. /// Date and time constants ///
  32. /**
  33. * Time constant - the number of seconds in a year
  34. */
  35. define('YEARSECS', 31536000);
  36. /**
  37. * Time constant - the number of seconds in a week
  38. */
  39. define('WEEKSECS', 604800);
  40. /**
  41. * Time constant - the number of seconds in a day
  42. */
  43. define('DAYSECS', 86400);
  44. /**
  45. * Time constant - the number of seconds in an hour
  46. */
  47. define('HOURSECS', 3600);
  48. /**
  49. * Time constant - the number of seconds in a minute
  50. */
  51. define('MINSECS', 60);
  52. /**
  53. * Time constant - the number of minutes in a day
  54. */
  55. define('DAYMINS', 1440);
  56. /**
  57. * Time constant - the number of minutes in an hour
  58. */
  59. define('HOURMINS', 60);
  60. /// Parameter constants - every call to optional_param(), required_param() ///
  61. /// or clean_param() should have a specified type of parameter. //////////////
  62. /**
  63. * PARAM_ALPHA - contains only english ascii letters a-zA-Z.
  64. */
  65. define('PARAM_ALPHA', 'alpha');
  66. /**
  67. * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
  68. * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
  69. */
  70. define('PARAM_ALPHAEXT', 'alphaext');
  71. /**
  72. * PARAM_ALPHANUM - expected numbers and letters only.
  73. */
  74. define('PARAM_ALPHANUM', 'alphanum');
  75. /**
  76. * PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
  77. */
  78. define('PARAM_ALPHANUMEXT', 'alphanumext');
  79. /**
  80. * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
  81. */
  82. define('PARAM_AUTH', 'auth');
  83. /**
  84. * PARAM_BASE64 - Base 64 encoded format
  85. */
  86. define('PARAM_BASE64', 'base64');
  87. /**
  88. * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
  89. */
  90. define('PARAM_BOOL', 'bool');
  91. /**
  92. * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
  93. * checked against the list of capabilities in the database.
  94. */
  95. define('PARAM_CAPABILITY', 'capability');
  96. /**
  97. * PARAM_CLEANHTML - cleans submitted HTML code. use only for text in HTML format. This cleaning may fix xhtml strictness too.
  98. */
  99. define('PARAM_CLEANHTML', 'cleanhtml');
  100. /**
  101. * PARAM_EMAIL - an email address following the RFC
  102. */
  103. define('PARAM_EMAIL', 'email');
  104. /**
  105. * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
  106. */
  107. define('PARAM_FILE', 'file');
  108. /**
  109. * PARAM_FLOAT - a real/floating point number.
  110. *
  111. * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
  112. * It does not work for languages that use , as a decimal separator.
  113. * Instead, do something like
  114. * $rawvalue = required_param('name', PARAM_RAW);
  115. * // ... other code including require_login, which sets current lang ...
  116. * $realvalue = unformat_float($rawvalue);
  117. * // ... then use $realvalue
  118. */
  119. define('PARAM_FLOAT', 'float');
  120. /**
  121. * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
  122. */
  123. define('PARAM_HOST', 'host');
  124. /**
  125. * PARAM_INT - integers only, use when expecting only numbers.
  126. */
  127. define('PARAM_INT', 'int');
  128. /**
  129. * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
  130. */
  131. define('PARAM_LANG', 'lang');
  132. /**
  133. * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
  134. */
  135. define('PARAM_LOCALURL', 'localurl');
  136. /**
  137. * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
  138. */
  139. define('PARAM_NOTAGS', 'notags');
  140. /**
  141. * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
  142. * note: the leading slash is not removed, window drive letter is not allowed
  143. */
  144. define('PARAM_PATH', 'path');
  145. /**
  146. * PARAM_PEM - Privacy Enhanced Mail format
  147. */
  148. define('PARAM_PEM', 'pem');
  149. /**
  150. * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
  151. */
  152. define('PARAM_PERMISSION', 'permission');
  153. /**
  154. * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
  155. */
  156. define('PARAM_RAW', 'raw');
  157. /**
  158. * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
  159. */
  160. define('PARAM_RAW_TRIMMED', 'raw_trimmed');
  161. /**
  162. * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
  163. */
  164. define('PARAM_SAFEDIR', 'safedir');
  165. /**
  166. * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
  167. */
  168. define('PARAM_SAFEPATH', 'safepath');
  169. /**
  170. * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
  171. */
  172. define('PARAM_SEQUENCE', 'sequence');
  173. /**
  174. * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
  175. */
  176. define('PARAM_TAG', 'tag');
  177. /**
  178. * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
  179. */
  180. define('PARAM_TAGLIST', 'taglist');
  181. /**
  182. * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
  183. */
  184. define('PARAM_TEXT', 'text');
  185. /**
  186. * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
  187. */
  188. define('PARAM_THEME', 'theme');
  189. /**
  190. * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but http://localhost.localdomain/ is ok.
  191. */
  192. define('PARAM_URL', 'url');
  193. /**
  194. * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user accounts, do NOT use when syncing with external systems!!
  195. */
  196. define('PARAM_USERNAME', 'username');
  197. /**
  198. * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
  199. */
  200. define('PARAM_STRINGID', 'stringid');
  201. ///// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE /////
  202. /**
  203. * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
  204. * It was one of the first types, that is why it is abused so much ;-)
  205. * @deprecated since 2.0
  206. */
  207. define('PARAM_CLEAN', 'clean');
  208. /**
  209. * PARAM_INTEGER - deprecated alias for PARAM_INT
  210. */
  211. define('PARAM_INTEGER', 'int');
  212. /**
  213. * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
  214. */
  215. define('PARAM_NUMBER', 'float');
  216. /**
  217. * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
  218. * NOTE: originally alias for PARAM_APLHA
  219. */
  220. define('PARAM_ACTION', 'alphanumext');
  221. /**
  222. * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
  223. * NOTE: originally alias for PARAM_APLHA
  224. */
  225. define('PARAM_FORMAT', 'alphanumext');
  226. /**
  227. * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
  228. */
  229. define('PARAM_MULTILANG', 'text');
  230. /**
  231. * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
  232. * string seperated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
  233. * America/Port-au-Prince)
  234. */
  235. define('PARAM_TIMEZONE', 'timezone');
  236. /**
  237. * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
  238. */
  239. define('PARAM_CLEANFILE', 'file');
  240. /**
  241. * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
  242. * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
  243. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  244. * NOTE: numbers and underscores are strongly discouraged in plugin names!
  245. */
  246. define('PARAM_COMPONENT', 'component');
  247. /**
  248. * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
  249. * It is usually used together with context id and component.
  250. * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
  251. */
  252. define('PARAM_AREA', 'area');
  253. /**
  254. * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
  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! Underscores are forbidden in module names.
  257. */
  258. define('PARAM_PLUGIN', 'plugin');
  259. /// Web Services ///
  260. /**
  261. * VALUE_REQUIRED - if the parameter is not supplied, there is an error
  262. */
  263. define('VALUE_REQUIRED', 1);
  264. /**
  265. * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
  266. */
  267. define('VALUE_OPTIONAL', 2);
  268. /**
  269. * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
  270. */
  271. define('VALUE_DEFAULT', 0);
  272. /**
  273. * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
  274. */
  275. define('NULL_NOT_ALLOWED', false);
  276. /**
  277. * NULL_ALLOWED - the parameter can be set to null in the database
  278. */
  279. define('NULL_ALLOWED', true);
  280. /// Page types ///
  281. /**
  282. * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
  283. */
  284. define('PAGE_COURSE_VIEW', 'course-view');
  285. /** Get remote addr constant */
  286. define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
  287. /** Get remote addr constant */
  288. define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
  289. /// Blog access level constant declaration ///
  290. define ('BLOG_USER_LEVEL', 1);
  291. define ('BLOG_GROUP_LEVEL', 2);
  292. define ('BLOG_COURSE_LEVEL', 3);
  293. define ('BLOG_SITE_LEVEL', 4);
  294. define ('BLOG_GLOBAL_LEVEL', 5);
  295. ///Tag constants///
  296. /**
  297. * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
  298. * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
  299. * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
  300. *
  301. * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
  302. */
  303. define('TAG_MAX_LENGTH', 50);
  304. /// Password policy constants ///
  305. define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
  306. define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  307. define ('PASSWORD_DIGITS', '0123456789');
  308. define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
  309. /// Feature constants ///
  310. // Used for plugin_supports() to report features that are, or are not, supported by a module.
  311. /** True if module can provide a grade */
  312. define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
  313. /** True if module supports outcomes */
  314. define('FEATURE_GRADE_OUTCOMES', 'outcomes');
  315. /** True if module supports advanced grading methods */
  316. define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
  317. /** True if module has code to track whether somebody viewed it */
  318. define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
  319. /** True if module has custom completion rules */
  320. define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
  321. /** True if module has no 'view' page (like label) */
  322. define('FEATURE_NO_VIEW_LINK', 'viewlink');
  323. /** True if module supports outcomes */
  324. define('FEATURE_IDNUMBER', 'idnumber');
  325. /** True if module supports groups */
  326. define('FEATURE_GROUPS', 'groups');
  327. /** True if module supports groupings */
  328. define('FEATURE_GROUPINGS', 'groupings');
  329. /** True if module supports groupmembersonly */
  330. define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
  331. /** Type of module */
  332. define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
  333. /** True if module supports intro editor */
  334. define('FEATURE_MOD_INTRO', 'mod_intro');
  335. /** True if module has default completion */
  336. define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
  337. define('FEATURE_COMMENT', 'comment');
  338. define('FEATURE_RATE', 'rate');
  339. /** True if module supports backup/restore of moodle2 format */
  340. define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
  341. /** True if module can show description on course main page */
  342. define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
  343. /** Unspecified module archetype */
  344. define('MOD_ARCHETYPE_OTHER', 0);
  345. /** Resource-like type module */
  346. define('MOD_ARCHETYPE_RESOURCE', 1);
  347. /** Assignment module archetype */
  348. define('MOD_ARCHETYPE_ASSIGNMENT', 2);
  349. /** System (not user-addable) module archetype */
  350. define('MOD_ARCHETYPE_SYSTEM', 3);
  351. /**
  352. * Security token used for allowing access
  353. * from external application such as web services.
  354. * Scripts do not use any session, performance is relatively
  355. * low because we need to load access info in each request.
  356. * Scripts are executed in parallel.
  357. */
  358. define('EXTERNAL_TOKEN_PERMANENT', 0);
  359. /**
  360. * Security token used for allowing access
  361. * of embedded applications, the code is executed in the
  362. * active user session. Token is invalidated after user logs out.
  363. * Scripts are executed serially - normal session locking is used.
  364. */
  365. define('EXTERNAL_TOKEN_EMBEDDED', 1);
  366. /**
  367. * The home page should be the site home
  368. */
  369. define('HOMEPAGE_SITE', 0);
  370. /**
  371. * The home page should be the users my page
  372. */
  373. define('HOMEPAGE_MY', 1);
  374. /**
  375. * The home page can be chosen by the user
  376. */
  377. define('HOMEPAGE_USER', 2);
  378. /**
  379. * Hub directory url (should be moodle.org)
  380. */
  381. define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
  382. /**
  383. * Moodle.org url (should be moodle.org)
  384. */
  385. define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
  386. /**
  387. * Moodle mobile app service name
  388. */
  389. define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
  390. /**
  391. * Indicates the user has the capabilities required to ignore activity and course file size restrictions
  392. */
  393. define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
  394. /// PARAMETER HANDLING ////////////////////////////////////////////////////
  395. /**
  396. * Returns a particular value for the named variable, taken from
  397. * POST or GET. If the parameter doesn't exist then an error is
  398. * thrown because we require this variable.
  399. *
  400. * This function should be used to initialise all required values
  401. * in a script that are based on parameters. Usually it will be
  402. * used like this:
  403. * $id = required_param('id', PARAM_INT);
  404. *
  405. * Please note the $type parameter is now required and the value can not be array.
  406. *
  407. * @param string $parname the name of the page parameter we want
  408. * @param string $type expected type of parameter
  409. * @return mixed
  410. */
  411. function required_param($parname, $type) {
  412. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  413. throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
  414. }
  415. if (isset($_POST[$parname])) { // POST has precedence
  416. $param = $_POST[$parname];
  417. } else if (isset($_GET[$parname])) {
  418. $param = $_GET[$parname];
  419. } else {
  420. print_error('missingparam', '', '', $parname);
  421. }
  422. if (is_array($param)) {
  423. debugging('Invalid array parameter detected in required_param(): '.$parname);
  424. // TODO: switch to fatal error in Moodle 2.3
  425. //print_error('missingparam', '', '', $parname);
  426. return required_param_array($parname, $type);
  427. }
  428. return clean_param($param, $type);
  429. }
  430. /**
  431. * Returns a particular array value for the named variable, taken from
  432. * POST or GET. If the parameter doesn't exist then an error is
  433. * thrown because we require this variable.
  434. *
  435. * This function should be used to initialise all required values
  436. * in a script that are based on parameters. Usually it will be
  437. * used like this:
  438. * $ids = required_param_array('ids', PARAM_INT);
  439. *
  440. * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
  441. *
  442. * @param string $parname the name of the page parameter we want
  443. * @param string $type expected type of parameter
  444. * @return array
  445. */
  446. function required_param_array($parname, $type) {
  447. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  448. throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
  449. }
  450. if (isset($_POST[$parname])) { // POST has precedence
  451. $param = $_POST[$parname];
  452. } else if (isset($_GET[$parname])) {
  453. $param = $_GET[$parname];
  454. } else {
  455. print_error('missingparam', '', '', $parname);
  456. }
  457. if (!is_array($param)) {
  458. print_error('missingparam', '', '', $parname);
  459. }
  460. $result = array();
  461. foreach($param as $key=>$value) {
  462. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  463. debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
  464. continue;
  465. }
  466. $result[$key] = clean_param($value, $type);
  467. }
  468. return $result;
  469. }
  470. /**
  471. * Returns a particular value for the named variable, taken from
  472. * POST or GET, otherwise returning a given default.
  473. *
  474. * This function should be used to initialise all optional values
  475. * in a script that are based on parameters. Usually it will be
  476. * used like this:
  477. * $name = optional_param('name', 'Fred', PARAM_TEXT);
  478. *
  479. * Please note the $type parameter is now required and the value can not be array.
  480. *
  481. * @param string $parname the name of the page parameter we want
  482. * @param mixed $default the default value to return if nothing is found
  483. * @param string $type expected type of parameter
  484. * @return mixed
  485. */
  486. function optional_param($parname, $default, $type) {
  487. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  488. throw new coding_exception('optional_param() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
  489. }
  490. if (!isset($default)) {
  491. $default = null;
  492. }
  493. if (isset($_POST[$parname])) { // POST has precedence
  494. $param = $_POST[$parname];
  495. } else if (isset($_GET[$parname])) {
  496. $param = $_GET[$parname];
  497. } else {
  498. return $default;
  499. }
  500. if (is_array($param)) {
  501. debugging('Invalid array parameter detected in required_param(): '.$parname);
  502. // TODO: switch to $default in Moodle 2.3
  503. //return $default;
  504. return optional_param_array($parname, $default, $type);
  505. }
  506. return clean_param($param, $type);
  507. }
  508. /**
  509. * Returns a particular array value for the named variable, taken from
  510. * POST or GET, otherwise returning a given default.
  511. *
  512. * This function should be used to initialise all optional values
  513. * in a script that are based on parameters. Usually it will be
  514. * used like this:
  515. * $ids = optional_param('id', array(), PARAM_INT);
  516. *
  517. * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
  518. *
  519. * @param string $parname the name of the page parameter we want
  520. * @param mixed $default the default value to return if nothing is found
  521. * @param string $type expected type of parameter
  522. * @return array
  523. */
  524. function optional_param_array($parname, $default, $type) {
  525. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  526. throw new coding_exception('optional_param_array() requires $parname, $default and $type to be specified (parameter: '.$parname.')');
  527. }
  528. if (isset($_POST[$parname])) { // POST has precedence
  529. $param = $_POST[$parname];
  530. } else if (isset($_GET[$parname])) {
  531. $param = $_GET[$parname];
  532. } else {
  533. return $default;
  534. }
  535. if (!is_array($param)) {
  536. debugging('optional_param_array() expects array parameters only: '.$parname);
  537. return $default;
  538. }
  539. $result = array();
  540. foreach($param as $key=>$value) {
  541. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  542. debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
  543. continue;
  544. }
  545. $result[$key] = clean_param($value, $type);
  546. }
  547. return $result;
  548. }
  549. /**
  550. * Strict validation of parameter values, the values are only converted
  551. * to requested PHP type. Internally it is using clean_param, the values
  552. * before and after cleaning must be equal - otherwise
  553. * an invalid_parameter_exception is thrown.
  554. * Objects and classes are not accepted.
  555. *
  556. * @param mixed $param
  557. * @param string $type PARAM_ constant
  558. * @param bool $allownull are nulls valid value?
  559. * @param string $debuginfo optional debug information
  560. * @return mixed the $param value converted to PHP type or invalid_parameter_exception
  561. */
  562. function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
  563. if (is_null($param)) {
  564. if ($allownull == NULL_ALLOWED) {
  565. return null;
  566. } else {
  567. throw new invalid_parameter_exception($debuginfo);
  568. }
  569. }
  570. if (is_array($param) or is_object($param)) {
  571. throw new invalid_parameter_exception($debuginfo);
  572. }
  573. $cleaned = clean_param($param, $type);
  574. if ((string)$param !== (string)$cleaned) {
  575. // conversion to string is usually lossless
  576. throw new invalid_parameter_exception($debuginfo);
  577. }
  578. return $cleaned;
  579. }
  580. /**
  581. * Makes sure array contains only the allowed types,
  582. * this function does not validate array key names!
  583. * <code>
  584. * $options = clean_param($options, PARAM_INT);
  585. * </code>
  586. *
  587. * @param array $param the variable array we are cleaning
  588. * @param string $type expected format of param after cleaning.
  589. * @param bool $recursive clean recursive arrays
  590. * @return array
  591. */
  592. function clean_param_array(array $param = null, $type, $recursive = false) {
  593. $param = (array)$param; // convert null to empty array
  594. foreach ($param as $key => $value) {
  595. if (is_array($value)) {
  596. if ($recursive) {
  597. $param[$key] = clean_param_array($value, $type, true);
  598. } else {
  599. throw new coding_exception('clean_param_array() can not process multidimensional arrays when $recursive is false.');
  600. }
  601. } else {
  602. $param[$key] = clean_param($value, $type);
  603. }
  604. }
  605. return $param;
  606. }
  607. /**
  608. * Used by {@link optional_param()} and {@link required_param()} to
  609. * clean the variables and/or cast to specific types, based on
  610. * an options field.
  611. * <code>
  612. * $course->format = clean_param($course->format, PARAM_ALPHA);
  613. * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_INT);
  614. * </code>
  615. *
  616. * @param mixed $param the variable we are cleaning
  617. * @param string $type expected format of param after cleaning.
  618. * @return mixed
  619. */
  620. function clean_param($param, $type) {
  621. global $CFG;
  622. if (is_array($param)) {
  623. throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
  624. } else if (is_object($param)) {
  625. if (method_exists($param, '__toString')) {
  626. $param = $param->__toString();
  627. } else {
  628. throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
  629. }
  630. }
  631. switch ($type) {
  632. case PARAM_RAW: // no cleaning at all
  633. $param = fix_utf8($param);
  634. return $param;
  635. case PARAM_RAW_TRIMMED: // no cleaning, but strip leading and trailing whitespace.
  636. $param = fix_utf8($param);
  637. return trim($param);
  638. case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
  639. // this is deprecated!, please use more specific type instead
  640. if (is_numeric($param)) {
  641. return $param;
  642. }
  643. $param = fix_utf8($param);
  644. return clean_text($param); // Sweep for scripts, etc
  645. case PARAM_CLEANHTML: // clean html fragment
  646. $param = fix_utf8($param);
  647. $param = clean_text($param, FORMAT_HTML); // Sweep for scripts, etc
  648. return trim($param);
  649. case PARAM_INT:
  650. return (int)$param; // Convert to integer
  651. case PARAM_FLOAT:
  652. case PARAM_NUMBER:
  653. return (float)$param; // Convert to float
  654. case PARAM_ALPHA: // Remove everything not a-z
  655. return preg_replace('/[^a-zA-Z]/i', '', $param);
  656. case PARAM_ALPHAEXT: // Remove everything not a-zA-Z_- (originally allowed "/" too)
  657. return preg_replace('/[^a-zA-Z_-]/i', '', $param);
  658. case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
  659. return preg_replace('/[^A-Za-z0-9]/i', '', $param);
  660. case PARAM_ALPHANUMEXT: // Remove everything not a-zA-Z0-9_-
  661. return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
  662. case PARAM_SEQUENCE: // Remove everything not 0-9,
  663. return preg_replace('/[^0-9,]/i', '', $param);
  664. case PARAM_BOOL: // Convert to 1 or 0
  665. $tempstr = strtolower($param);
  666. if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
  667. $param = 1;
  668. } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
  669. $param = 0;
  670. } else {
  671. $param = empty($param) ? 0 : 1;
  672. }
  673. return $param;
  674. case PARAM_NOTAGS: // Strip all tags
  675. $param = fix_utf8($param);
  676. return strip_tags($param);
  677. case PARAM_TEXT: // leave only tags needed for multilang
  678. $param = fix_utf8($param);
  679. // if the multilang syntax is not correct we strip all tags
  680. // because it would break xhtml strict which is required for accessibility standards
  681. // please note this cleaning does not strip unbalanced '>' for BC compatibility reasons
  682. do {
  683. if (strpos($param, '</lang>') !== false) {
  684. // old and future mutilang syntax
  685. $param = strip_tags($param, '<lang>');
  686. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  687. break;
  688. }
  689. $open = false;
  690. foreach ($matches[0] as $match) {
  691. if ($match === '</lang>') {
  692. if ($open) {
  693. $open = false;
  694. continue;
  695. } else {
  696. break 2;
  697. }
  698. }
  699. if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
  700. break 2;
  701. } else {
  702. $open = true;
  703. }
  704. }
  705. if ($open) {
  706. break;
  707. }
  708. return $param;
  709. } else if (strpos($param, '</span>') !== false) {
  710. // current problematic multilang syntax
  711. $param = strip_tags($param, '<span>');
  712. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  713. break;
  714. }
  715. $open = false;
  716. foreach ($matches[0] as $match) {
  717. if ($match === '</span>') {
  718. if ($open) {
  719. $open = false;
  720. continue;
  721. } else {
  722. break 2;
  723. }
  724. }
  725. if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
  726. break 2;
  727. } else {
  728. $open = true;
  729. }
  730. }
  731. if ($open) {
  732. break;
  733. }
  734. return $param;
  735. }
  736. } while (false);
  737. // easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string()
  738. return strip_tags($param);
  739. case PARAM_COMPONENT:
  740. // we do not want any guessing here, either the name is correct or not
  741. // please note only normalised component names are accepted
  742. if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]$/', $param)) {
  743. return '';
  744. }
  745. if (strpos($param, '__') !== false) {
  746. return '';
  747. }
  748. if (strpos($param, 'mod_') === 0) {
  749. // module names must not contain underscores because we need to differentiate them from invalid plugin types
  750. if (substr_count($param, '_') != 1) {
  751. return '';
  752. }
  753. }
  754. return $param;
  755. case PARAM_PLUGIN:
  756. case PARAM_AREA:
  757. // we do not want any guessing here, either the name is correct or not
  758. if (!preg_match('/^[a-z][a-z0-9_]*[a-z0-9]$/', $param)) {
  759. return '';
  760. }
  761. if (strpos($param, '__') !== false) {
  762. return '';
  763. }
  764. return $param;
  765. case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
  766. return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
  767. case PARAM_SAFEPATH: // Remove everything not a-zA-Z0-9/_-
  768. return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
  769. case PARAM_FILE: // Strip all suspicious characters from filename
  770. $param = fix_utf8($param);
  771. $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
  772. $param = preg_replace('~\.\.+~', '', $param);
  773. if ($param === '.') {
  774. $param = '';
  775. }
  776. return $param;
  777. case PARAM_PATH: // Strip all suspicious characters from file path
  778. $param = fix_utf8($param);
  779. $param = str_replace('\\', '/', $param);
  780. $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':]~u', '', $param);
  781. $param = preg_replace('~\.\.+~', '', $param);
  782. $param = preg_replace('~//+~', '/', $param);
  783. return preg_replace('~/(\./)+~', '/', $param);
  784. case PARAM_HOST: // allow FQDN or IPv4 dotted quad
  785. $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
  786. // match ipv4 dotted quad
  787. if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
  788. // confirm values are ok
  789. if ( $match[0] > 255
  790. || $match[1] > 255
  791. || $match[3] > 255
  792. || $match[4] > 255 ) {
  793. // hmmm, what kind of dotted quad is this?
  794. $param = '';
  795. }
  796. } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
  797. && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
  798. && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
  799. ) {
  800. // all is ok - $param is respected
  801. } else {
  802. // all is not ok...
  803. $param='';
  804. }
  805. return $param;
  806. case PARAM_URL: // allow safe ftp, http, mailto urls
  807. $param = fix_utf8($param);
  808. include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
  809. if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
  810. // all is ok, param is respected
  811. } else {
  812. $param =''; // not really ok
  813. }
  814. return $param;
  815. case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
  816. $param = clean_param($param, PARAM_URL);
  817. if (!empty($param)) {
  818. if (preg_match(':^/:', $param)) {
  819. // root-relative, ok!
  820. } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
  821. // absolute, and matches our wwwroot
  822. } else {
  823. // relative - let's make sure there are no tricks
  824. if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?')) {
  825. // looks ok.
  826. } else {
  827. $param = '';
  828. }
  829. }
  830. }
  831. return $param;
  832. case PARAM_PEM:
  833. $param = trim($param);
  834. // PEM formatted strings may contain letters/numbers and the symbols
  835. // forward slash: /
  836. // plus sign: +
  837. // equal sign: =
  838. // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
  839. if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
  840. list($wholething, $body) = $matches;
  841. unset($wholething, $matches);
  842. $b64 = clean_param($body, PARAM_BASE64);
  843. if (!empty($b64)) {
  844. return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
  845. } else {
  846. return '';
  847. }
  848. }
  849. return '';
  850. case PARAM_BASE64:
  851. if (!empty($param)) {
  852. // PEM formatted strings may contain letters/numbers and the symbols
  853. // forward slash: /
  854. // plus sign: +
  855. // equal sign: =
  856. if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
  857. return '';
  858. }
  859. $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
  860. // Each line of base64 encoded data must be 64 characters in
  861. // length, except for the last line which may be less than (or
  862. // equal to) 64 characters long.
  863. for ($i=0, $j=count($lines); $i < $j; $i++) {
  864. if ($i + 1 == $j) {
  865. if (64 < strlen($lines[$i])) {
  866. return '';
  867. }
  868. continue;
  869. }
  870. if (64 != strlen($lines[$i])) {
  871. return '';
  872. }
  873. }
  874. return implode("\n",$lines);
  875. } else {
  876. return '';
  877. }
  878. case PARAM_TAG:
  879. $param = fix_utf8($param);
  880. // Please note it is not safe to use the tag name directly anywhere,
  881. // it must be processed with s(), urlencode() before embedding anywhere.
  882. // remove some nasties
  883. $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
  884. //convert many whitespace chars into one
  885. $param = preg_replace('/\s+/', ' ', $param);
  886. $param = textlib::substr(trim($param), 0, TAG_MAX_LENGTH);
  887. return $param;
  888. case PARAM_TAGLIST:
  889. $param = fix_utf8($param);
  890. $tags = explode(',', $param);
  891. $result = array();
  892. foreach ($tags as $tag) {
  893. $res = clean_param($tag, PARAM_TAG);
  894. if ($res !== '') {
  895. $result[] = $res;
  896. }
  897. }
  898. if ($result) {
  899. return implode(',', $result);
  900. } else {
  901. return '';
  902. }
  903. case PARAM_CAPABILITY:
  904. if (get_capability_info($param)) {
  905. return $param;
  906. } else {
  907. return '';
  908. }
  909. case PARAM_PERMISSION:
  910. $param = (int)$param;
  911. if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
  912. return $param;
  913. } else {
  914. return CAP_INHERIT;
  915. }
  916. case PARAM_AUTH:
  917. $param = clean_param($param, PARAM_PLUGIN);
  918. if (empty($param)) {
  919. return '';
  920. } else if (exists_auth_plugin($param)) {
  921. return $param;
  922. } else {
  923. return '';
  924. }
  925. case PARAM_LANG:
  926. $param = clean_param($param, PARAM_SAFEDIR);
  927. if (get_string_manager()->translation_exists($param)) {
  928. return $param;
  929. } else {
  930. return ''; // Specified language is not installed or param malformed
  931. }
  932. case PARAM_THEME:
  933. $param = clean_param($param, PARAM_PLUGIN);
  934. if (empty($param)) {
  935. return '';
  936. } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
  937. return $param;
  938. } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
  939. return $param;
  940. } else {
  941. return ''; // Specified theme is not installed
  942. }
  943. case PARAM_USERNAME:
  944. $param = fix_utf8($param);
  945. $param = str_replace(" " , "", $param);
  946. $param = textlib::strtolower($param); // Convert uppercase to lowercase MDL-16919
  947. if (empty($CFG->extendedusernamechars)) {
  948. // regular expression, eliminate all chars EXCEPT:
  949. // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
  950. $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
  951. }
  952. return $param;
  953. case PARAM_EMAIL:
  954. $param = fix_utf8($param);
  955. if (validate_email($param)) {
  956. return $param;
  957. } else {
  958. return '';
  959. }
  960. case PARAM_STRINGID:
  961. if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
  962. return $param;
  963. } else {
  964. return '';
  965. }
  966. case PARAM_TIMEZONE: //can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'
  967. $param = fix_utf8($param);
  968. $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3]|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
  969. if (preg_match($timezonepattern, $param)) {
  970. return $param;
  971. } else {
  972. return '';
  973. }
  974. default: // throw error, switched parameters in optional_param or another serious problem
  975. print_error("unknownparamtype", '', '', $type);
  976. }
  977. }
  978. /**
  979. * Makes sure the data is using valid utf8, invalid characters are discarded.
  980. *
  981. * Note: this function is not intended for full objects with methods and private properties.
  982. *
  983. * @param mixed $value
  984. * @return mixed with proper utf-8 encoding
  985. */
  986. function fix_utf8($value) {
  987. if (is_null($value) or $value === '') {
  988. return $value;
  989. } else if (is_string($value)) {
  990. if ((string)(int)$value === $value) {
  991. // shortcut
  992. return $value;
  993. }
  994. // Lower error reporting because glibc throws bogus notices.
  995. $olderror = error_reporting();
  996. if ($olderror & E_NOTICE) {
  997. error_reporting($olderror ^ E_NOTICE);
  998. }
  999. // Note: this duplicates min_fix_utf8() intentionally.
  1000. static $buggyiconv = null;
  1001. if ($buggyiconv === null) {
  1002. $buggyiconv = (!function_exists('iconv') or iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
  1003. }
  1004. if ($buggyiconv) {
  1005. if (function_exists('mb_convert_encoding')) {
  1006. $subst = mb_substitute_character();
  1007. mb_substitute_character('');
  1008. $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
  1009. mb_substitute_character($subst);
  1010. } else {
  1011. // Warn admins on admin/index.php page.
  1012. $result = $value;
  1013. }
  1014. } else {
  1015. $result = iconv('UTF-8', 'UTF-8//IGNORE', $value);
  1016. }
  1017. if ($olderror & E_NOTICE) {
  1018. error_reporting($olderror);
  1019. }
  1020. return $result;
  1021. } else if (is_array($value)) {
  1022. foreach ($value as $k=>$v) {
  1023. $value[$k] = fix_utf8($v);
  1024. }
  1025. return $value;
  1026. } else if (is_object($value)) {
  1027. $value = clone($value); // do not modify original
  1028. foreach ($value as $k=>$v) {
  1029. $value->$k = fix_utf8($v);
  1030. }
  1031. return $value;
  1032. } else {
  1033. // this is some other type, no utf-8 here
  1034. return $value;
  1035. }
  1036. }
  1037. /**
  1038. * Return true if given value is integer or string with integer value
  1039. *
  1040. * @param mixed $value String or Int
  1041. * @return bool true if number, false if not
  1042. */
  1043. function is_number($value) {
  1044. if (is_int($value)) {
  1045. return true;
  1046. } else if (is_string($value)) {
  1047. return ((string)(int)$value) === $value;
  1048. } else {
  1049. return false;
  1050. }
  1051. }
  1052. /**
  1053. * Returns host part from url
  1054. * @param string $url full url
  1055. * @return string host, null if not found
  1056. */
  1057. function get_host_from_url($url) {
  1058. preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
  1059. if ($matches) {
  1060. return $matches[1];
  1061. }
  1062. return null;
  1063. }
  1064. /**
  1065. * Tests whether anything was returned by text editor
  1066. *
  1067. * This function is useful for testing whether something you got back from
  1068. * the HTML editor actually contains anything. Sometimes the HTML editor
  1069. * appear to be empty, but actually you get back a <br> tag or something.
  1070. *
  1071. * @param string $string a string containing HTML.
  1072. * @return boolean does the string contain any actual content - that is text,
  1073. * images, objects, etc.
  1074. */
  1075. function html_is_blank($string) {
  1076. return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
  1077. }
  1078. /**
  1079. * Set a key in global configuration
  1080. *
  1081. * Set a key/value pair in both this session's {@link $CFG} global variable
  1082. * and in the 'config' database table for future sessions.
  1083. *
  1084. * Can also be used to update keys for plugin-scoped configs in config_plugin table.
  1085. * In that case it doesn't affect $CFG.
  1086. *
  1087. * A NULL value will delete the entry.
  1088. *
  1089. * @global object
  1090. * @global object
  1091. * @param string $name the key to set
  1092. * @param string $value the value to set (without magic quotes)
  1093. * @param string $plugin (optional) the plugin scope, default NULL
  1094. * @return bool true or exception
  1095. */
  1096. function set_config($name, $value, $plugin=NULL) {
  1097. global $CFG, $DB;
  1098. if (empty($plugin)) {
  1099. if (!array_key_exists($name, $CFG->config_php_settings)) {
  1100. // So it's defined for this invocation at least
  1101. if (is_null($value)) {
  1102. unset($CFG->$name);
  1103. } else {
  1104. $CFG->$name = (string)$value; // settings from db are always strings
  1105. }
  1106. }
  1107. if ($DB->get_field('config', 'name', array('name'=>$name))) {
  1108. if ($value === null) {
  1109. $DB->delete_records('config', array('name'=>$name));
  1110. } else {
  1111. $DB->set_field('config', 'value', $value, array('name'=>$name));
  1112. }
  1113. } else {
  1114. if ($value !== null) {
  1115. $config = new stdClass();
  1116. $config->name = $name;
  1117. $config->value = $value;
  1118. $DB->insert_record('config', $config, false);
  1119. }
  1120. }
  1121. } else { // plugin scope
  1122. if ($id = $DB->get_field('config_plugins', 'id', array('name'=>$name, 'plugin'=>$plugin))) {
  1123. if ($value===null) {
  1124. $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
  1125. } else {
  1126. $DB->set_field('config_plugins', 'value', $value, array('id'=>$id));
  1127. }
  1128. } else {
  1129. if ($value !== null) {
  1130. $config = new stdClass();
  1131. $config->plugin = $plugin;
  1132. $config->name = $name;
  1133. $config->value = $value;
  1134. $DB->insert_record('config_plugins', $config, false);
  1135. }
  1136. }
  1137. }
  1138. return true;
  1139. }
  1140. /**
  1141. * Get configuration values from the global config table
  1142. * or the config_plugins table.
  1143. *
  1144. * If called with one parameter, it will load all the config
  1145. * variables for one plugin, and return them as an object.
  1146. *
  1147. * If called with 2 parameters it will return a string single
  1148. * value or false if the value is not found.
  1149. *
  1150. * @param string $plugin full component name
  1151. * @param string $name default NULL
  1152. * @return mixed hash-like object or single value, return false no config found
  1153. */
  1154. function get_config($plugin, $name = NULL) {
  1155. global $CFG, $DB;
  1156. // normalise component name
  1157. if ($plugin === 'moodle' or $plugin === 'core') {
  1158. $plugin = NULL;
  1159. }
  1160. if (!empty($name)) { // the user is asking for a specific value
  1161. if (!empty($plugin)) {
  1162. if (isset($CFG->forced_plugin_settings[$plugin]) and array_key_exists($name, $CFG->forced_plugin_settings[$plugin])) {
  1163. // setting forced in config file
  1164. return $CFG->forced_plugin_settings[$plugin][$name];
  1165. } else {
  1166. return $DB->get_field('config_plugins', 'value', array('plugin'=>$plugin, 'name'=>$name));
  1167. }
  1168. } else {
  1169. if (array_key_exists($name, $CFG->config_php_settings)) {
  1170. // setting force in config file
  1171. return $CFG->config_php_settings[$name];
  1172. } else {
  1173. return $DB->get_field('config', 'value', array('name'=>$name));
  1174. }
  1175. }
  1176. }
  1177. // the user is after a recordset
  1178. if ($plugin) {
  1179. $localcfg = $DB->get_records_menu('config_plugins', array('plugin'=>$plugin), '', 'name,value');
  1180. if (isset($CFG->forced_plugin_settings[$plugin])) {
  1181. foreach($CFG->forced_plugin_settings[$plugin] as $n=>$v) {
  1182. if (is_null($v) or is_array($v) or is_object($v)) {
  1183. // we do not want any extra mess here, just real settings that could be saved in db
  1184. unset($localcfg[$n]);
  1185. } else {
  1186. //convert to string as if it went through the DB
  1187. $localcfg[$n] = (string)$v;
  1188. }
  1189. }
  1190. }
  1191. if ($localcfg) {
  1192. return (object)$localcfg;
  1193. } else {
  1194. return new stdClass();
  1195. }
  1196. } else {
  1197. // this part is not really used any more, but anyway...
  1198. $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
  1199. foreach($CFG->config_php_settings as $n=>$v) {
  1200. if (is_null($v) or is_array($v) or is_object($v)) {
  1201. // we do not want any extra mess here, just real settings that could be saved in db
  1202. unset($localcfg[$n]);
  1203. } else {
  1204. //convert to string as if it went through the DB
  1205. $localcfg[$n] = (string)$v;
  1206. }
  1207. }
  1208. return (object)$localcfg;
  1209. }
  1210. }
  1211. /**
  1212. * Removes a key from global configuration
  1213. *
  1214. * @param string $name the key to set
  1215. * @param string $plugin (optional) the plugin scope
  1216. * @global object
  1217. * @return boolean whether the operation succeeded.
  1218. */
  1219. function unset_config($name, $plugin=NULL) {
  1220. global $CFG, $DB;
  1221. if (empty($plugin)) {
  1222. unset($CFG->$name);
  1223. $DB->delete_records('config', array('name'=>$name));
  1224. } else {
  1225. $DB->delete_records('config_plugins', array('name'=>$name, 'plugin'=>$plugin));
  1226. }
  1227. return true;
  1228. }
  1229. /**
  1230. * Remove all the config variables for a given plugin.
  1231. *
  1232. * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
  1233. * @return boolean whether the operation succeeded.
  1234. */
  1235. function unset_all_config_for_plugin($plugin) {
  1236. global $DB;
  1237. $DB->delete_records('config_plugins', array('plugin' => $plugin));
  1238. $like = $DB->sql_like('name', '?', true, true, false, '|');
  1239. $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
  1240. $DB->delete_records_select('config', $like, $params);
  1241. return true;
  1242. }
  1243. /**
  1244. * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
  1245. *
  1246. * All users are verified if they still have the necessary capability.
  1247. *
  1248. * @param string $value the value of the config setting.
  1249. * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
  1250. * @param bool $include admins, include administrators
  1251. * @return array of user objects.
  1252. */
  1253. function get_users_from_config($value, $capability, $includeadmins = true) {
  1254. global $CFG, $DB;
  1255. if (empty($value) or $value === '$@NONE@$') {
  1256. return array();
  1257. }
  1258. // we have to make sure that users still have the necessary capability,
  1259. // it should be faster to fetch them all first and then test if they are present
  1260. // instead of validating them one-by-one
  1261. $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
  1262. if ($includeadmins) {
  1263. $admins = get_admins();
  1264. foreach ($admins as $admin) {
  1265. $users[$admin->id] = $admin;
  1266. }
  1267. }
  1268. if ($value === '$@ALL@$') {
  1269. return $users;
  1270. }
  1271. $result = array(); // result in correct order
  1272. $allowed = explode(',', $value);
  1273. foreach ($allowed as $uid) {
  1274. if (isset($users[$uid])) {
  1275. $user = $users[$uid];
  1276. $result[$user->id] = $user;
  1277. }
  1278. }
  1279. return $result;
  1280. }
  1281. /**
  1282. * Invalidates browser caches and cached data in temp
  1283. * @return void
  1284. */
  1285. function purge_all_caches() {
  1286. global $CFG;
  1287. reset_text_filters_cache();
  1288. js_reset_all_caches();
  1289. theme_reset_all_caches();
  1290. get_string_manager()->reset_caches();
  1291. textlib::reset_caches();
  1292. // purge all other caches: rss, simplepie, etc.
  1293. remove_dir($CFG->cachedir.'', true);
  1294. // make sure cache dir is writable, throws exception if not
  1295. make_cache_directory('');
  1296. // hack: this script may get called after the purifier was initialised,
  1297. // but we do not want to verify repeatedly this exists in each call
  1298. make_cache_directory('htmlpurifier');
  1299. }
  1300. /**
  1301. * Get volatile flags
  1302. *
  1303. * @param string $type
  1304. * @param int $changedsince default null
  1305. * @return records array
  1306. */
  1307. function get_cache_flags($type, $changedsince=NULL) {
  1308. global $DB;
  1309. $params = array('type'=>$type, 'expiry'=>time());
  1310. $sqlwhere = "flagtype = :type AND expiry >= :expiry";
  1311. if ($changedsince !== NULL) {
  1312. $params['changedsince'] = $changedsince;
  1313. $sqlwhere .= " AND timemodified > :changedsince";
  1314. }
  1315. $cf = array();
  1316. if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
  1317. foreach ($flags as $flag) {
  1318. $cf[$flag->name] = $flag->value;
  1319. }
  1320. }
  1321. return $cf;
  1322. }
  1323. /**
  1324. * Get volatile flags
  1325. *
  1326. * @param string $type
  1327. * @param string $name
  1328. * @param int $changedsince default null
  1329. * @return records array
  1330. */
  1331. function get_cache_flag($type, $name, $changedsince=NULL) {
  1332. global $DB;
  1333. $params = array('type'=>$type, 'name'=>$name, 'expiry'=>time());
  1334. $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
  1335. if ($changedsince !== NULL) {
  1336. $params['changedsince'] = $changedsince;
  1337. $sqlwhere .= " AND timemodified > :changedsince";
  1338. }
  1339. return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
  1340. }
  1341. /**
  1342. * Set a volatile flag
  1343. *
  1344. * @param string $type the "type" namespace for the key
  1345. * @param string $name the key to set
  1346. * @param string $value the value to set (without magic quotes) - NULL will remove the flag
  1347. * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
  1348. * @return bool Always returns true
  1349. */
  1350. function set_cache_flag($type, $name, $value, $expiry=NULL) {
  1351. global $DB;
  1352. $timemodified = time();
  1353. if ($expiry===NULL || $expiry < $timemodified) {
  1354. $expiry = $timemodified + 24 * 60 * 60;
  1355. } else {
  1356. $expiry = (int)$expiry;
  1357. }
  1358. if ($value === NULL) {
  1359. unset_cache_flag($type,$name);
  1360. return true;
  1361. }
  1362. if ($f = $DB->get_record('cache_flags', array('name'=>$name, 'flagtype'=>$type), '*', IGNORE_MULTIPLE)) { // this is a potential problem in DEBUG_DEVELOPER
  1363. if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
  1364. return true; //no need to update; helps rcache too
  1365. }
  1366. $f->value = $value;
  1367. $f->expiry = $expiry;
  1368. $f->timemodified = $timemodified;
  1369. $DB->update_record('cache_flags', $f);
  1370. } else {
  1371. $f = new stdClass();
  1372. $f->flagtype = $type;
  1373. $f->name = $name;
  1374. $f->value = $value;
  1375. $f->expiry = $expiry;
  1376. $f->timemodified = $timemodified;
  1377. $DB->insert_record('cache_flags', $f);
  1378. }
  1379. return true;
  1380. }
  1381. /**
  1382. * Removes a single volatile flag
  1383. *
  1384. * @global object
  1385. * @param string $type the "type" namespace for the key
  1386. * @param string $name the key to set
  1387. * @return bool
  1388. */
  1389. function unset_cache_flag($type, $name) {
  1390. global $DB;
  1391. $DB->delete_records('cache_flags', array('name'=>$name, 'flagtype'=>$type));
  1392. return true;
  1393. }
  1394. /**
  1395. * Garbage-collect volatile flags
  1396. *
  1397. * @return bool Always returns true
  1398. */
  1399. function gc_cache_flags() {
  1400. global $DB;
  1401. $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
  1402. return true;
  1403. }
  1404. // USER PREFERENCE API
  1405. /**
  1406. * Refresh user preference cache. This is used most often for $USER
  1407. * object that is stored in session, but it also helps with performance in cron script.
  1408. *
  1409. * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
  1410. *
  1411. * @package core
  1412. * @category preference
  1413. * @access public
  1414. * @param stdClass $user User object. Preferences are preloaded into 'preference' property
  1415. * @param int $cachelifetime Cache life time on the current page (in seconds)
  1416. * @throws coding_exception
  1417. * @return null
  1418. */
  1419. function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
  1420. global $DB;
  1421. static $loadedusers = array(); // Static cache, we need to check on each page load, not only every 2 minutes.
  1422. if (!isset($user->id)) {
  1423. throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
  1424. }
  1425. if (empty($user->id) or isguestuser($user->id)) {
  1426. // No permanent storage for not-logged-in users and guest
  1427. if (!isset($user->preference)) {
  1428. $user->preference = array();
  1429. }
  1430. return;
  1431. }
  1432. $timenow = time();
  1433. if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
  1434. // Already loaded at least once on this page. Are we up to date?
  1435. if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
  1436. // no need to reload - we are on the same page and we loaded prefs just a moment ago
  1437. return;
  1438. } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
  1439. // no change since the lastcheck on this page
  1440. $user->preference['_lastloaded'] = $timenow;
  1441. return;
  1442. }
  1443. }
  1444. // OK, so we have to reload all preferences
  1445. $loadedusers[$user->id] = true;
  1446. $user->preference = $DB->get_records_menu('user_preferences', array('userid'=>$user->id), '', 'name,value'); // All values
  1447. $user->preference['_lastloaded'] = $timenow;
  1448. }
  1449. /**
  1450. * Called from set/unset_user_preferences, so that the prefs can
  1451. * be correctly reloaded in different sessions.
  1452. *
  1453. * NOTE: internal function, do not call from other code.
  1454. *
  1455. * @package core
  1456. * @access private
  1457. * @param integer $userid the user whose prefs were changed.
  1458. */
  1459. function mark_user_preferences_changed($userid) {
  1460. global $CFG;
  1461. if (empty($userid) or isguestuser($userid)) {
  1462. // no cache flags for guest and not-logged-in users
  1463. return;
  1464. }
  1465. set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
  1466. }
  1467. /**
  1468. * Sets a preference for the specified user.
  1469. *
  1470. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1471. *
  1472. * @package core
  1473. * @category preference
  1474. * @access public
  1475. * @param string $name The key to set as preference for the specified user
  1476. * @param string $value The value to set for the $name key in the specified user's
  1477. * record, null means delete current value.
  1478. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1479. * @throws coding_exception
  1480. * @return bool Always true or exception
  1481. */
  1482. function set_user_preference($name, $value, $user = null) {
  1483. global $USER, $DB;
  1484. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1485. throw new coding_exception('Invalid preference name in set_user_preference() call');
  1486. }
  1487. if (is_null($value)) {
  1488. // null means delete current
  1489. return unset_user_preference($name, $user);
  1490. } else if (is_object($value)) {
  1491. throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
  1492. } else if (is_array($value)) {
  1493. throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
  1494. }
  1495. $value = (string)$value;
  1496. if (textlib::strlen($value) > 1333) { //value column maximum length is 1333 characters
  1497. throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
  1498. }
  1499. if (is_null($user)) {
  1500. $user = $USER;
  1501. } else if (isset($user->id)) {
  1502. // $user is valid object
  1503. } else if (is_numeric($user)) {
  1504. $user = (object)array('id'=>(int)$user);
  1505. } else {
  1506. throw new coding_exception('Invalid $user parameter in set_user_preference() call');
  1507. }
  1508. check_user_preferences_loaded($user);
  1509. if (empty($user->id) or isguestuser($user->id)) {
  1510. // no permanent storage for not-logged-in users and guest
  1511. $user->preference[$name] = $value;
  1512. return true;
  1513. }
  1514. if ($preference = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>$name))) {
  1515. if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
  1516. // preference already set to this value
  1517. return true;
  1518. }
  1519. $DB->set_field('user_preferences', 'value', $value, array('id'=>$preference->id));
  1520. } else {
  1521. $preference = new stdClass();
  1522. $preference->userid = $user->id;
  1523. $preference->name = $name;
  1524. $preference->value = $value;
  1525. $DB->insert_record('user_preferences', $preference);
  1526. }
  1527. // update value in cache
  1528. $user->preference[$name] = $value;
  1529. // set reload flag for other sessions
  1530. mark_user_preferences_changed($user->id);
  1531. return true;
  1532. }
  1533. /**
  1534. * Sets a whole array of preferences for the current user
  1535. *
  1536. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1537. *
  1538. * @package core
  1539. * @category preference
  1540. * @access public
  1541. * @param array $prefarray An array of key/value pairs to be set
  1542. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1543. * @return bool Always true or exception
  1544. */
  1545. function set_user_preferences(array $prefarray, $user = null) {
  1546. foreach ($prefarray as $name => $value) {
  1547. set_user_preference($name, $value, $user);
  1548. }
  1549. return true;
  1550. }
  1551. /**
  1552. * Unsets a preference completely by deleting it from the database
  1553. *
  1554. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1555. *
  1556. * @package core
  1557. * @category preference
  1558. * @access public
  1559. * @param string $name The key to unset as preference for the specified user
  1560. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1561. * @throws coding_exception
  1562. * @return bool Always true or exception
  1563. */
  1564. function unset_user_preference($name, $user = null) {
  1565. global $USER, $DB;
  1566. if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
  1567. throw new coding_exception('Invalid preference name in unset_user_preference() call');
  1568. }
  1569. if (is_null($user)) {
  1570. $user = $USER;
  1571. } else if (isset($user->id)) {
  1572. // $user is valid object
  1573. } else if (is_numeric($user)) {
  1574. $user = (object)array('id'=>(int)$user);
  1575. } else {
  1576. throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
  1577. }
  1578. check_user_preferences_loaded($user);
  1579. if (empty($user->id) or isguestuser($user->id)) {
  1580. // no permanent storage for not-logged-in user and guest
  1581. unset($user->preference[$name]);
  1582. return true;
  1583. }
  1584. // delete from DB
  1585. $DB->delete_records('user_preferences', array('userid'=>$user->id, 'name'=>$name));
  1586. // delete the preference from cache
  1587. unset($user->preference[$name]);
  1588. // set reload flag for other sessions
  1589. mark_user_preferences_changed($user->id);
  1590. return true;
  1591. }
  1592. /**
  1593. * Used to fetch user preference(s)
  1594. *
  1595. * If no arguments are supplied this function will return
  1596. * all of the current user preferences as an array.
  1597. *
  1598. * If a name is specified then this function
  1599. * attempts to return that particular preference value. If
  1600. * none is found, then the optional value $default is returned,
  1601. * otherwise NULL.
  1602. *
  1603. * If a $user object is submitted it's 'preference' property is used for the preferences cache.
  1604. *
  1605. * @package core
  1606. * @category preference
  1607. * @access public
  1608. * @param string $name Name of the key to use in finding a preference value
  1609. * @param mixed|null $default Value to be returned if the $name key is not set in the user preferences
  1610. * @param stdClass|int|null $user A moodle user object or id, null means current user
  1611. * @throws coding_exception
  1612. * @return string|mixed|null A string containing the value of a single preference. An
  1613. * array with all of the preferences or null
  1614. */
  1615. function get_user_preferences($name = null, $default = null, $user = null) {
  1616. global $USER;
  1617. if (is_null($name)) {
  1618. // all prefs
  1619. } else if (is_numeric($name) or $name === '_lastloaded') {
  1620. throw new coding_exception('Invalid preference name in get_user_preferences() call');
  1621. }
  1622. if (is_null($user)) {
  1623. $user = $USER;
  1624. } else if (isset($user->id)) {
  1625. // $user is valid object
  1626. } else if (is_numeric($user)) {
  1627. $user = (object)array('id'=>(int)$user);
  1628. } else {
  1629. throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
  1630. }
  1631. check_user_preferences_loaded($user);
  1632. if (empty($name)) {
  1633. return $user->preference; // All values
  1634. } else if (isset($user->preference[$name])) {
  1635. return $user->preference[$name]; // The single string value
  1636. } else {
  1637. return $default; // Default value (null if not specified)
  1638. }
  1639. }
  1640. /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
  1641. /**
  1642. * Given date parts in user time produce a GMT timestamp.
  1643. *
  1644. * @package core
  1645. * @category time
  1646. * @param int $year The year part to create timestamp of
  1647. * @param int $month The month part to create timestamp of
  1648. * @param int $day The day part to create timestamp of
  1649. * @param int $hour The hour part to create timestamp of
  1650. * @param int $minute The minute part to create timestamp of
  1651. * @param int $second The second part to create timestamp of
  1652. * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
  1653. * if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1654. * @param bool $applydst Toggle Daylight Saving Time, default true, will be
  1655. * applied only if timezone is 99 or string.
  1656. * @return int GMT timestamp
  1657. */
  1658. function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
  1659. //save input timezone, required for dst offset check.
  1660. $passedtimezone = $timezone;
  1661. $timezone = get_user_timezone_offset($timezone);
  1662. if (abs($timezone) > 13) { //server time
  1663. $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
  1664. } else {
  1665. $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
  1666. $time = usertime($time, $timezone);
  1667. //Apply dst for string timezones or if 99 then try dst offset with user's default timezone
  1668. if ($applydst && ((99 == $passedtimezone) || !is_numeric($passedtimezone))) {
  1669. $time -= dst_offset_on($time, $passedtimezone);
  1670. }
  1671. }
  1672. return $time;
  1673. }
  1674. /**
  1675. * Format a date/time (seconds) as weeks, days, hours etc as needed
  1676. *
  1677. * Given an amount of time in seconds, returns string
  1678. * formatted nicely as weeks, days, hours etc as needed
  1679. *
  1680. * @package core
  1681. * @category time
  1682. * @uses MINSECS
  1683. * @uses HOURSECS
  1684. * @uses DAYSECS
  1685. * @uses YEARSECS
  1686. * @param int $totalsecs Time in seconds
  1687. * @param object $str Should be a time object
  1688. * @return string A nicely formatted date/time string
  1689. */
  1690. function format_time($totalsecs, $str=NULL) {
  1691. $totalsecs = abs($totalsecs);
  1692. if (!$str) { // Create the str structure the slow way
  1693. $str = new stdClass();
  1694. $str->day = get_string('day');
  1695. $str->days = get_string('days');
  1696. $str->hour = get_string('hour');
  1697. $str->hours = get_string('hours');
  1698. $str->min = get_string('min');
  1699. $str->mins = get_string('mins');
  1700. $str->sec = get_string('sec');
  1701. $str->secs = get_string('secs');
  1702. $str->year = get_string('year');
  1703. $str->years = get_string('years');
  1704. }
  1705. $years = floor($totalsecs/YEARSECS);
  1706. $remainder = $totalsecs - ($years*YEARSECS);
  1707. $days = floor($remainder/DAYSECS);
  1708. $remainder = $totalsecs - ($days*DAYSECS);
  1709. $hours = floor($remainder/HOURSECS);
  1710. $remainder = $remainder - ($hours*HOURSECS);
  1711. $mins = floor($remainder/MINSECS);
  1712. $secs = $remainder - ($mins*MINSECS);
  1713. $ss = ($secs == 1) ? $str->sec : $str->secs;
  1714. $sm = ($mins == 1) ? $str->min : $str->mins;
  1715. $sh = ($hours == 1) ? $str->hour : $str->hours;
  1716. $sd = ($days == 1) ? $str->day : $str->days;
  1717. $sy = ($years == 1) ? $str->year : $str->years;
  1718. $oyears = '';
  1719. $odays = '';
  1720. $ohours = '';
  1721. $omins = '';
  1722. $osecs = '';
  1723. if ($years) $oyears = $years .' '. $sy;
  1724. if ($days) $odays = $days .' '. $sd;
  1725. if ($hours) $ohours = $hours .' '. $sh;
  1726. if ($mins) $omins = $mins .' '. $sm;
  1727. if ($secs) $osecs = $secs .' '. $ss;
  1728. if ($years) return trim($oyears .' '. $odays);
  1729. if ($days) return trim($odays .' '. $ohours);
  1730. if ($hours) return trim($ohours .' '. $omins);
  1731. if ($mins) return trim($omins .' '. $osecs);
  1732. if ($secs) return $osecs;
  1733. return get_string('now');
  1734. }
  1735. /**
  1736. * Returns a formatted string that represents a date in user time
  1737. *
  1738. * Returns a formatted string that represents a date in user time
  1739. * <b>WARNING: note that the format is for strftime(), not date().</b>
  1740. * Because of a bug in most Windows time libraries, we can't use
  1741. * the nicer %e, so we have to use %d which has leading zeroes.
  1742. * A lot of the fuss in the function is just getting rid of these leading
  1743. * zeroes as efficiently as possible.
  1744. *
  1745. * If parameter fixday = true (default), then take off leading
  1746. * zero from %d, else maintain it.
  1747. *
  1748. * @package core
  1749. * @category time
  1750. * @param int $date the timestamp in UTC, as obtained from the database.
  1751. * @param string $format strftime format. You should probably get this using
  1752. * get_string('strftime...', 'langconfig');
  1753. * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
  1754. * not 99 then daylight saving will not be added.
  1755. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1756. * @param bool $fixday If true (default) then the leading zero from %d is removed.
  1757. * If false then the leading zero is maintained.
  1758. * @param bool $fixhour If true (default) then the leading zero from %I is removed.
  1759. * @return string the formatted date/time.
  1760. */
  1761. function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
  1762. global $CFG;
  1763. if (empty($format)) {
  1764. $format = get_string('strftimedaydatetime', 'langconfig');
  1765. }
  1766. if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
  1767. $fixday = false;
  1768. } else if ($fixday) {
  1769. $formatnoday = str_replace('%d', 'DD', $format);
  1770. $fixday = ($formatnoday != $format);
  1771. $format = $formatnoday;
  1772. }
  1773. // Note: This logic about fixing 12-hour time to remove unnecessary leading
  1774. // zero is required because on Windows, PHP strftime function does not
  1775. // support the correct 'hour without leading zero' parameter (%l).
  1776. if (!empty($CFG->nofixhour)) {
  1777. // Config.php can force %I not to be fixed.
  1778. $fixhour = false;
  1779. } else if ($fixhour) {
  1780. $formatnohour = str_replace('%I', 'HH', $format);
  1781. $fixhour = ($formatnohour != $format);
  1782. $format = $formatnohour;
  1783. }
  1784. //add daylight saving offset for string timezones only, as we can't get dst for
  1785. //float values. if timezone is 99 (user default timezone), then try update dst.
  1786. if ((99 == $timezone) || !is_numeric($timezone)) {
  1787. $date += dst_offset_on($date, $timezone);
  1788. }
  1789. $timezone = get_user_timezone_offset($timezone);
  1790. // If we are running under Windows convert to windows encoding and then back to UTF-8
  1791. // (because it's impossible to specify UTF-8 to fetch locale info in Win32)
  1792. if (abs($timezone) > 13) { /// Server time
  1793. if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
  1794. $format = textlib::convert($format, 'utf-8', $localewincharset);
  1795. $datestring = strftime($format, $date);
  1796. $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
  1797. } else {
  1798. $datestring = strftime($format, $date);
  1799. }
  1800. if ($fixday) {
  1801. $daystring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %d', $date)));
  1802. $datestring = str_replace('DD', $daystring, $datestring);
  1803. }
  1804. if ($fixhour) {
  1805. $hourstring = ltrim(str_replace(array(' 0', ' '), '', strftime(' %I', $date)));
  1806. $datestring = str_replace('HH', $hourstring, $datestring);
  1807. }
  1808. } else {
  1809. $date += (int)($timezone * 3600);
  1810. if ($CFG->ostype == 'WINDOWS' and ($localewincharset = get_string('localewincharset', 'langconfig'))) {
  1811. $format = textlib::convert($format, 'utf-8', $localewincharset);
  1812. $datestring = gmstrftime($format, $date);
  1813. $datestring = textlib::convert($datestring, $localewincharset, 'utf-8');
  1814. } else {
  1815. $datestring = gmstrftime($format, $date);
  1816. }
  1817. if ($fixday) {
  1818. $daystring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %d', $date)));
  1819. $datestring = str_replace('DD', $daystring, $datestring);
  1820. }
  1821. if ($fixhour) {
  1822. $hourstring = ltrim(str_replace(array(' 0', ' '), '', gmstrftime(' %I', $date)));
  1823. $datestring = str_replace('HH', $hourstring, $datestring);
  1824. }
  1825. }
  1826. return $datestring;
  1827. }
  1828. /**
  1829. * Given a $time timestamp in GMT (seconds since epoch),
  1830. * returns an array that represents the date in user time
  1831. *
  1832. * @package core
  1833. * @category time
  1834. * @uses HOURSECS
  1835. * @param int $time Timestamp in GMT
  1836. * @param float|int|string $timezone offset's time with timezone, if float and not 99, then no
  1837. * dst offset is applyed {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1838. * @return array An array that represents the date in user time
  1839. */
  1840. function usergetdate($time, $timezone=99) {
  1841. //save input timezone, required for dst offset check.
  1842. $passedtimezone = $timezone;
  1843. $timezone = get_user_timezone_offset($timezone);
  1844. if (abs($timezone) > 13) { // Server time
  1845. return getdate($time);
  1846. }
  1847. //add daylight saving offset for string timezones only, as we can't get dst for
  1848. //float values. if timezone is 99 (user default timezone), then try update dst.
  1849. if ($passedtimezone == 99 || !is_numeric($passedtimezone)) {
  1850. $time += dst_offset_on($time, $passedtimezone);
  1851. }
  1852. $time += intval((float)$timezone * HOURSECS);
  1853. $datestring = gmstrftime('%B_%A_%j_%Y_%m_%w_%d_%H_%M_%S', $time);
  1854. //be careful to ensure the returned array matches that produced by getdate() above
  1855. list(
  1856. $getdate['month'],
  1857. $getdate['weekday'],
  1858. $getdate['yday'],
  1859. $getdate['year'],
  1860. $getdate['mon'],
  1861. $getdate['wday'],
  1862. $getdate['mday'],
  1863. $getdate['hours'],
  1864. $getdate['minutes'],
  1865. $getdate['seconds']
  1866. ) = explode('_', $datestring);
  1867. // set correct datatype to match with getdate()
  1868. $getdate['seconds'] = (int)$getdate['seconds'];
  1869. $getdate['yday'] = (int)$getdate['yday'] - 1; // gettime returns 0 through 365
  1870. $getdate['year'] = (int)$getdate['year'];
  1871. $getdate['mon'] = (int)$getdate['mon'];
  1872. $getdate['wday'] = (int)$getdate['wday'];
  1873. $getdate['mday'] = (int)$getdate['mday'];
  1874. $getdate['hours'] = (int)$getdate['hours'];
  1875. $getdate['minutes'] = (int)$getdate['minutes'];
  1876. return $getdate;
  1877. }
  1878. /**
  1879. * Given a GMT timestamp (seconds since epoch), offsets it by
  1880. * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
  1881. *
  1882. * @package core
  1883. * @category time
  1884. * @uses HOURSECS
  1885. * @param int $date Timestamp in GMT
  1886. * @param float|int|string $timezone timezone to calculate GMT time offset before
  1887. * calculating user time, 99 is default user timezone
  1888. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1889. * @return int
  1890. */
  1891. function usertime($date, $timezone=99) {
  1892. $timezone = get_user_timezone_offset($timezone);
  1893. if (abs($timezone) > 13) {
  1894. return $date;
  1895. }
  1896. return $date - (int)($timezone * HOURSECS);
  1897. }
  1898. /**
  1899. * Given a time, return the GMT timestamp of the most recent midnight
  1900. * for the current user.
  1901. *
  1902. * @package core
  1903. * @category time
  1904. * @param int $date Timestamp in GMT
  1905. * @param float|int|string $timezone timezone to calculate GMT time offset before
  1906. * calculating user midnight time, 99 is default user timezone
  1907. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1908. * @return int Returns a GMT timestamp
  1909. */
  1910. function usergetmidnight($date, $timezone=99) {
  1911. $userdate = usergetdate($date, $timezone);
  1912. // Time of midnight of this user's day, in GMT
  1913. return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
  1914. }
  1915. /**
  1916. * Returns a string that prints the user's timezone
  1917. *
  1918. * @package core
  1919. * @category time
  1920. * @param float|int|string $timezone timezone to calculate GMT time offset before
  1921. * calculating user timezone, 99 is default user timezone
  1922. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1923. * @return string
  1924. */
  1925. function usertimezone($timezone=99) {
  1926. $tz = get_user_timezone($timezone);
  1927. if (!is_float($tz)) {
  1928. return $tz;
  1929. }
  1930. if(abs($tz) > 13) { // Server time
  1931. return get_string('serverlocaltime');
  1932. }
  1933. if($tz == intval($tz)) {
  1934. // Don't show .0 for whole hours
  1935. $tz = intval($tz);
  1936. }
  1937. if($tz == 0) {
  1938. return 'UTC';
  1939. }
  1940. else if($tz > 0) {
  1941. return 'UTC+'.$tz;
  1942. }
  1943. else {
  1944. return 'UTC'.$tz;
  1945. }
  1946. }
  1947. /**
  1948. * Returns a float which represents the user's timezone difference from GMT in hours
  1949. * Checks various settings and picks the most dominant of those which have a value
  1950. *
  1951. * @package core
  1952. * @category time
  1953. * @param float|int|string $tz timezone to calculate GMT time offset for user,
  1954. * 99 is default user timezone
  1955. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1956. * @return float
  1957. */
  1958. function get_user_timezone_offset($tz = 99) {
  1959. global $USER, $CFG;
  1960. $tz = get_user_timezone($tz);
  1961. if (is_float($tz)) {
  1962. return $tz;
  1963. } else {
  1964. $tzrecord = get_timezone_record($tz);
  1965. if (empty($tzrecord)) {
  1966. return 99.0;
  1967. }
  1968. return (float)$tzrecord->gmtoff / HOURMINS;
  1969. }
  1970. }
  1971. /**
  1972. * Returns an int which represents the systems's timezone difference from GMT in seconds
  1973. *
  1974. * @package core
  1975. * @category time
  1976. * @param float|int|string $tz timezone for which offset is required.
  1977. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  1978. * @return int|bool if found, false is timezone 99 or error
  1979. */
  1980. function get_timezone_offset($tz) {
  1981. global $CFG;
  1982. if ($tz == 99) {
  1983. return false;
  1984. }
  1985. if (is_numeric($tz)) {
  1986. return intval($tz * 60*60);
  1987. }
  1988. if (!$tzrecord = get_timezone_record($tz)) {
  1989. return false;
  1990. }
  1991. return intval($tzrecord->gmtoff * 60);
  1992. }
  1993. /**
  1994. * Returns a float or a string which denotes the user's timezone
  1995. * 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)
  1996. * means that for this timezone there are also DST rules to be taken into account
  1997. * Checks various settings and picks the most dominant of those which have a value
  1998. *
  1999. * @package core
  2000. * @category time
  2001. * @param float|int|string $tz timezone to calculate GMT time offset before
  2002. * calculating user timezone, 99 is default user timezone
  2003. * {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2004. * @return float|string
  2005. */
  2006. function get_user_timezone($tz = 99) {
  2007. global $USER, $CFG;
  2008. $timezones = array(
  2009. $tz,
  2010. isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
  2011. isset($USER->timezone) ? $USER->timezone : 99,
  2012. isset($CFG->timezone) ? $CFG->timezone : 99,
  2013. );
  2014. $tz = 99;
  2015. while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
  2016. $tz = $next['value'];
  2017. }
  2018. return is_numeric($tz) ? (float) $tz : $tz;
  2019. }
  2020. /**
  2021. * Returns cached timezone record for given $timezonename
  2022. *
  2023. * @package core
  2024. * @param string $timezonename name of the timezone
  2025. * @return stdClass|bool timezonerecord or false
  2026. */
  2027. function get_timezone_record($timezonename) {
  2028. global $CFG, $DB;
  2029. static $cache = NULL;
  2030. if ($cache === NULL) {
  2031. $cache = array();
  2032. }
  2033. if (isset($cache[$timezonename])) {
  2034. return $cache[$timezonename];
  2035. }
  2036. return $cache[$timezonename] = $DB->get_record_sql('SELECT * FROM {timezone}
  2037. WHERE name = ? ORDER BY year DESC', array($timezonename), IGNORE_MULTIPLE);
  2038. }
  2039. /**
  2040. * Build and store the users Daylight Saving Time (DST) table
  2041. *
  2042. * @package core
  2043. * @param int $from_year Start year for the table, defaults to 1971
  2044. * @param int $to_year End year for the table, defaults to 2035
  2045. * @param int|float|string $strtimezone, timezone to check if dst should be applyed.
  2046. * @return bool
  2047. */
  2048. function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
  2049. global $CFG, $SESSION, $DB;
  2050. $usertz = get_user_timezone($strtimezone);
  2051. if (is_float($usertz)) {
  2052. // Trivial timezone, no DST
  2053. return false;
  2054. }
  2055. if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
  2056. // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
  2057. unset($SESSION->dst_offsets);
  2058. unset($SESSION->dst_range);
  2059. }
  2060. if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
  2061. // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
  2062. // This will be the return path most of the time, pretty light computationally
  2063. return true;
  2064. }
  2065. // Reaching here means we either need to extend our table or create it from scratch
  2066. // Remember which TZ we calculated these changes for
  2067. $SESSION->dst_offsettz = $usertz;
  2068. if(empty($SESSION->dst_offsets)) {
  2069. // If we 're creating from scratch, put the two guard elements in there
  2070. $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
  2071. }
  2072. if(empty($SESSION->dst_range)) {
  2073. // If creating from scratch
  2074. $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
  2075. $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
  2076. // Fill in the array with the extra years we need to process
  2077. $yearstoprocess = array();
  2078. for($i = $from; $i <= $to; ++$i) {
  2079. $yearstoprocess[] = $i;
  2080. }
  2081. // Take note of which years we have processed for future calls
  2082. $SESSION->dst_range = array($from, $to);
  2083. }
  2084. else {
  2085. // If needing to extend the table, do the same
  2086. $yearstoprocess = array();
  2087. $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
  2088. $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
  2089. if($from < $SESSION->dst_range[0]) {
  2090. // Take note of which years we need to process and then note that we have processed them for future calls
  2091. for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
  2092. $yearstoprocess[] = $i;
  2093. }
  2094. $SESSION->dst_range[0] = $from;
  2095. }
  2096. if($to > $SESSION->dst_range[1]) {
  2097. // Take note of which years we need to process and then note that we have processed them for future calls
  2098. for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
  2099. $yearstoprocess[] = $i;
  2100. }
  2101. $SESSION->dst_range[1] = $to;
  2102. }
  2103. }
  2104. if(empty($yearstoprocess)) {
  2105. // This means that there was a call requesting a SMALLER range than we have already calculated
  2106. return true;
  2107. }
  2108. // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
  2109. // Also, the array is sorted in descending timestamp order!
  2110. // Get DB data
  2111. static $presets_cache = array();
  2112. if (!isset($presets_cache[$usertz])) {
  2113. $presets_cache[$usertz] = $DB->get_records('timezone', array('name'=>$usertz), 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
  2114. }
  2115. if(empty($presets_cache[$usertz])) {
  2116. return false;
  2117. }
  2118. // Remove ending guard (first element of the array)
  2119. reset($SESSION->dst_offsets);
  2120. unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
  2121. // Add all required change timestamps
  2122. foreach($yearstoprocess as $y) {
  2123. // Find the record which is in effect for the year $y
  2124. foreach($presets_cache[$usertz] as $year => $preset) {
  2125. if($year <= $y) {
  2126. break;
  2127. }
  2128. }
  2129. $changes = dst_changes_for_year($y, $preset);
  2130. if($changes === NULL) {
  2131. continue;
  2132. }
  2133. if($changes['dst'] != 0) {
  2134. $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
  2135. }
  2136. if($changes['std'] != 0) {
  2137. $SESSION->dst_offsets[$changes['std']] = 0;
  2138. }
  2139. }
  2140. // Put in a guard element at the top
  2141. $maxtimestamp = max(array_keys($SESSION->dst_offsets));
  2142. $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
  2143. // Sort again
  2144. krsort($SESSION->dst_offsets);
  2145. return true;
  2146. }
  2147. /**
  2148. * Calculates the required DST change and returns a Timestamp Array
  2149. *
  2150. * @package core
  2151. * @category time
  2152. * @uses HOURSECS
  2153. * @uses MINSECS
  2154. * @param int|string $year Int or String Year to focus on
  2155. * @param object $timezone Instatiated Timezone object
  2156. * @return array|null Array dst=>xx, 0=>xx, std=>yy, 1=>yy or NULL
  2157. */
  2158. function dst_changes_for_year($year, $timezone) {
  2159. if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
  2160. return NULL;
  2161. }
  2162. $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
  2163. $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
  2164. list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
  2165. list($std_hour, $std_min) = explode(':', $timezone->std_time);
  2166. $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
  2167. $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
  2168. // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
  2169. // This has the advantage of being able to have negative values for hour, i.e. for timezones
  2170. // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
  2171. $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
  2172. $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
  2173. return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
  2174. }
  2175. /**
  2176. * Calculates the Daylight Saving Offset for a given date/time (timestamp)
  2177. * - Note: Daylight saving only works for string timezones and not for float.
  2178. *
  2179. * @package core
  2180. * @category time
  2181. * @param int $time must NOT be compensated at all, it has to be a pure timestamp
  2182. * @param int|float|string $strtimezone timezone for which offset is expected, if 99 or null
  2183. * then user's default timezone is used. {@link http://docs.moodle.org/dev/Time_API#Timezone}
  2184. * @return int
  2185. */
  2186. function dst_offset_on($time, $strtimezone = NULL) {
  2187. global $SESSION;
  2188. if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
  2189. return 0;
  2190. }
  2191. reset($SESSION->dst_offsets);
  2192. while(list($from, $offset) = each($SESSION->dst_offsets)) {
  2193. if($from <= $time) {
  2194. break;
  2195. }
  2196. }
  2197. // This is the normal return path
  2198. if($offset !== NULL) {
  2199. return $offset;
  2200. }
  2201. // Reaching this point means we haven't calculated far enough, do it now:
  2202. // Calculate extra DST changes if needed and recurse. The recursion always
  2203. // moves toward the stopping condition, so will always end.
  2204. if($from == 0) {
  2205. // We need a year smaller than $SESSION->dst_range[0]
  2206. if($SESSION->dst_range[0] == 1971) {
  2207. return 0;
  2208. }
  2209. calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
  2210. return dst_offset_on($time, $strtimezone);
  2211. }
  2212. else {
  2213. // We need a year larger than $SESSION->dst_range[1]
  2214. if($SESSION->dst_range[1] == 2035) {
  2215. return 0;
  2216. }
  2217. calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
  2218. return dst_offset_on($time, $strtimezone);
  2219. }
  2220. }
  2221. /**
  2222. * Calculates when the day appears in specific month
  2223. *
  2224. * @package core
  2225. * @category time
  2226. * @param int $startday starting day of the month
  2227. * @param int $weekday The day when week starts (normally taken from user preferences)
  2228. * @param int $month The month whose day is sought
  2229. * @param int $year The year of the month whose day is sought
  2230. * @return int
  2231. */
  2232. function find_day_in_month($startday, $weekday, $month, $year) {
  2233. $daysinmonth = days_in_month($month, $year);
  2234. if($weekday == -1) {
  2235. // Don't care about weekday, so return:
  2236. // abs($startday) if $startday != -1
  2237. // $daysinmonth otherwise
  2238. return ($startday == -1) ? $daysinmonth : abs($startday);
  2239. }
  2240. // From now on we 're looking for a specific weekday
  2241. // Give "end of month" its actual value, since we know it
  2242. if($startday == -1) {
  2243. $startday = -1 * $daysinmonth;
  2244. }
  2245. // Starting from day $startday, the sign is the direction
  2246. if($startday < 1) {
  2247. $startday = abs($startday);
  2248. $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year));
  2249. // This is the last such weekday of the month
  2250. $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
  2251. if($lastinmonth > $daysinmonth) {
  2252. $lastinmonth -= 7;
  2253. }
  2254. // Find the first such weekday <= $startday
  2255. while($lastinmonth > $startday) {
  2256. $lastinmonth -= 7;
  2257. }
  2258. return $lastinmonth;
  2259. }
  2260. else {
  2261. $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year));
  2262. $diff = $weekday - $indexweekday;
  2263. if($diff < 0) {
  2264. $diff += 7;
  2265. }
  2266. // This is the first such weekday of the month equal to or after $startday
  2267. $firstfromindex = $startday + $diff;
  2268. return $firstfromindex;
  2269. }
  2270. }
  2271. /**
  2272. * Calculate the number of days in a given month
  2273. *
  2274. * @package core
  2275. * @category time
  2276. * @param int $month The month whose day count is sought
  2277. * @param int $year The year of the month whose day count is sought
  2278. * @return int
  2279. */
  2280. function days_in_month($month, $year) {
  2281. return intval(date('t', mktime(12, 0, 0, $month, 1, $year)));
  2282. }
  2283. /**
  2284. * Calculate the position in the week of a specific calendar day
  2285. *
  2286. * @package core
  2287. * @category time
  2288. * @param int $day The day of the date whose position in the week is sought
  2289. * @param int $month The month of the date whose position in the week is sought
  2290. * @param int $year The year of the date whose position in the week is sought
  2291. * @return int
  2292. */
  2293. function dayofweek($day, $month, $year) {
  2294. // I wonder if this is any different from
  2295. // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
  2296. return intval(date('w', mktime(12, 0, 0, $month, $day, $year)));
  2297. }
  2298. /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
  2299. /**
  2300. * Returns full login url.
  2301. *
  2302. * @return string login url
  2303. */
  2304. function get_login_url() {
  2305. global $CFG;
  2306. $url = "$CFG->wwwroot/login/index.php";
  2307. if (!empty($CFG->loginhttps)) {
  2308. $url = str_replace('http:', 'https:', $url);
  2309. }
  2310. return $url;
  2311. }
  2312. /**
  2313. * This function checks that the current user is logged in and has the
  2314. * required privileges
  2315. *
  2316. * This function checks that the current user is logged in, and optionally
  2317. * whether they are allowed to be in a particular course and view a particular
  2318. * course module.
  2319. * If they are not logged in, then it redirects them to the site login unless
  2320. * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
  2321. * case they are automatically logged in as guests.
  2322. * If $courseid is given and the user is not enrolled in that course then the
  2323. * user is redirected to the course enrolment page.
  2324. * If $cm is given and the course module is hidden and the user is not a teacher
  2325. * in the course then the user is redirected to the course home page.
  2326. *
  2327. * When $cm parameter specified, this function sets page layout to 'module'.
  2328. * You need to change it manually later if some other layout needed.
  2329. *
  2330. * @package core_access
  2331. * @category access
  2332. *
  2333. * @param mixed $courseorid id of the course or course object
  2334. * @param bool $autologinguest default true
  2335. * @param object $cm course module object
  2336. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  2337. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  2338. * in order to keep redirects working properly. MDL-14495
  2339. * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
  2340. * @return mixed Void, exit, and die depending on path
  2341. */
  2342. function require_login($courseorid = NULL, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
  2343. global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
  2344. // setup global $COURSE, themes, language and locale
  2345. if (!empty($courseorid)) {
  2346. if (is_object($courseorid)) {
  2347. $course = $courseorid;
  2348. } else if ($courseorid == SITEID) {
  2349. $course = clone($SITE);
  2350. } else {
  2351. $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
  2352. }
  2353. if ($cm) {
  2354. if ($cm->course != $course->id) {
  2355. throw new coding_exception('course and cm parameters in require_login() call do not match!!');
  2356. }
  2357. // make sure we have a $cm from get_fast_modinfo as this contains activity access details
  2358. if (!($cm instanceof cm_info)) {
  2359. // note: nearly all pages call get_fast_modinfo anyway and it does not make any
  2360. // db queries so this is not really a performance concern, however it is obviously
  2361. // better if you use get_fast_modinfo to get the cm before calling this.
  2362. $modinfo = get_fast_modinfo($course);
  2363. $cm = $modinfo->get_cm($cm->id);
  2364. }
  2365. $PAGE->set_cm($cm, $course); // set's up global $COURSE
  2366. $PAGE->set_pagelayout('incourse');
  2367. } else {
  2368. $PAGE->set_course($course); // set's up global $COURSE
  2369. }
  2370. } else {
  2371. // do not touch global $COURSE via $PAGE->set_course(),
  2372. // the reasons is we need to be able to call require_login() at any time!!
  2373. $course = $SITE;
  2374. if ($cm) {
  2375. throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
  2376. }
  2377. }
  2378. // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
  2379. // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
  2380. // risk leading the user back to the AJAX request URL.
  2381. if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
  2382. $setwantsurltome = false;
  2383. }
  2384. // If the user is not even logged in yet then make sure they are
  2385. if (!isloggedin()) {
  2386. if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
  2387. if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
  2388. // misconfigured site guest, just redirect to login page
  2389. redirect(get_login_url());
  2390. exit; // never reached
  2391. }
  2392. $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
  2393. complete_user_login($guest);
  2394. $USER->autologinguest = true;
  2395. $SESSION->lang = $lang;
  2396. } else {
  2397. //NOTE: $USER->site check was obsoleted by session test cookie,
  2398. // $USER->confirmed test is in login/index.php
  2399. if ($preventredirect) {
  2400. throw new require_login_exception('You are not logged in');
  2401. }
  2402. if ($setwantsurltome) {
  2403. $SESSION->wantsurl = qualified_me();
  2404. }
  2405. if (!empty($_SERVER['HTTP_REFERER'])) {
  2406. $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
  2407. }
  2408. redirect(get_login_url());
  2409. exit; // never reached
  2410. }
  2411. }
  2412. // loginas as redirection if needed
  2413. if ($course->id != SITEID and session_is_loggedinas()) {
  2414. if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
  2415. if ($USER->loginascontext->instanceid != $course->id) {
  2416. print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
  2417. }
  2418. }
  2419. }
  2420. // check whether the user should be changing password (but only if it is REALLY them)
  2421. if (get_user_preferences('auth_forcepasswordchange') && !session_is_loggedinas()) {
  2422. $userauth = get_auth_plugin($USER->auth);
  2423. if ($userauth->can_change_password() and !$preventredirect) {
  2424. if ($setwantsurltome) {
  2425. $SESSION->wantsurl = qualified_me();
  2426. }
  2427. if ($changeurl = $userauth->change_password_url()) {
  2428. //use plugin custom url
  2429. redirect($changeurl);
  2430. } else {
  2431. //use moodle internal method
  2432. if (empty($CFG->loginhttps)) {
  2433. redirect($CFG->wwwroot .'/login/change_password.php');
  2434. } else {
  2435. $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
  2436. redirect($wwwroot .'/login/change_password.php');
  2437. }
  2438. }
  2439. } else {
  2440. print_error('nopasswordchangeforced', 'auth');
  2441. }
  2442. }
  2443. // Check that the user account is properly set up
  2444. if (user_not_fully_set_up($USER)) {
  2445. if ($preventredirect) {
  2446. throw new require_login_exception('User not fully set-up');
  2447. }
  2448. if ($setwantsurltome) {
  2449. $SESSION->wantsurl = qualified_me();
  2450. }
  2451. redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
  2452. }
  2453. // Make sure the USER has a sesskey set up. Used for CSRF protection.
  2454. sesskey();
  2455. // Do not bother admins with any formalities
  2456. if (is_siteadmin()) {
  2457. //set accesstime or the user will appear offline which messes up messaging
  2458. user_accesstime_log($course->id);
  2459. return;
  2460. }
  2461. // Check that the user has agreed to a site policy if there is one - do not test in case of admins
  2462. if (!$USER->policyagreed and !is_siteadmin()) {
  2463. if (!empty($CFG->sitepolicy) and !isguestuser()) {
  2464. if ($preventredirect) {
  2465. throw new require_login_exception('Policy not agreed');
  2466. }
  2467. if ($setwantsurltome) {
  2468. $SESSION->wantsurl = qualified_me();
  2469. }
  2470. redirect($CFG->wwwroot .'/user/policy.php');
  2471. } else if (!empty($CFG->sitepolicyguest) and isguestuser()) {
  2472. if ($preventredirect) {
  2473. throw new require_login_exception('Policy not agreed');
  2474. }
  2475. if ($setwantsurltome) {
  2476. $SESSION->wantsurl = qualified_me();
  2477. }
  2478. redirect($CFG->wwwroot .'/user/policy.php');
  2479. }
  2480. }
  2481. // Fetch the system context, the course context, and prefetch its child contexts
  2482. $sysctx = get_context_instance(CONTEXT_SYSTEM);
  2483. $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id, MUST_EXIST);
  2484. if ($cm) {
  2485. $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id, MUST_EXIST);
  2486. } else {
  2487. $cmcontext = null;
  2488. }
  2489. // If the site is currently under maintenance, then print a message
  2490. if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:config', $sysctx)) {
  2491. if ($preventredirect) {
  2492. throw new require_login_exception('Maintenance in progress');
  2493. }
  2494. print_maintenance_message();
  2495. }
  2496. // make sure the course itself is not hidden
  2497. if ($course->id == SITEID) {
  2498. // frontpage can not be hidden
  2499. } else {
  2500. if (is_role_switched($course->id)) {
  2501. // when switching roles ignore the hidden flag - user had to be in course to do the switch
  2502. } else {
  2503. if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
  2504. // originally there was also test of parent category visibility,
  2505. // BUT is was very slow in complex queries involving "my courses"
  2506. // now it is also possible to simply hide all courses user is not enrolled in :-)
  2507. if ($preventredirect) {
  2508. throw new require_login_exception('Course is hidden');
  2509. }
  2510. // We need to override the navigation URL as the course won't have
  2511. // been added to the navigation and thus the navigation will mess up
  2512. // when trying to find it.
  2513. navigation_node::override_active_url(new moodle_url('/'));
  2514. notice(get_string('coursehidden'), $CFG->wwwroot .'/');
  2515. }
  2516. }
  2517. }
  2518. // is the user enrolled?
  2519. if ($course->id == SITEID) {
  2520. // everybody is enrolled on the frontpage
  2521. } else {
  2522. if (session_is_loggedinas()) {
  2523. // Make sure the REAL person can access this course first
  2524. $realuser = session_get_realuser();
  2525. if (!is_enrolled($coursecontext, $realuser->id, '', true) and !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
  2526. if ($preventredirect) {
  2527. throw new require_login_exception('Invalid course login-as access');
  2528. }
  2529. echo $OUTPUT->header();
  2530. notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
  2531. }
  2532. }
  2533. $access = false;
  2534. if (is_role_switched($course->id)) {
  2535. // ok, user had to be inside this course before the switch
  2536. $access = true;
  2537. } else if (is_viewing($coursecontext, $USER)) {
  2538. // ok, no need to mess with enrol
  2539. $access = true;
  2540. } else {
  2541. if (isset($USER->enrol['enrolled'][$course->id])) {
  2542. if ($USER->enrol['enrolled'][$course->id] > time()) {
  2543. $access = true;
  2544. if (isset($USER->enrol['tempguest'][$course->id])) {
  2545. unset($USER->enrol['tempguest'][$course->id]);
  2546. remove_temp_course_roles($coursecontext);
  2547. }
  2548. } else {
  2549. //expired
  2550. unset($USER->enrol['enrolled'][$course->id]);
  2551. }
  2552. }
  2553. if (isset($USER->enrol['tempguest'][$course->id])) {
  2554. if ($USER->enrol['tempguest'][$course->id] == 0) {
  2555. $access = true;
  2556. } else if ($USER->enrol['tempguest'][$course->id] > time()) {
  2557. $access = true;
  2558. } else {
  2559. //expired
  2560. unset($USER->enrol['tempguest'][$course->id]);
  2561. remove_temp_course_roles($coursecontext);
  2562. }
  2563. }
  2564. if ($access) {
  2565. // cache ok
  2566. } else {
  2567. $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
  2568. if ($until !== false) {
  2569. // active participants may always access, a timestamp in the future, 0 (always) or false.
  2570. if ($until == 0) {
  2571. $until = ENROL_MAX_TIMESTAMP;
  2572. }
  2573. $USER->enrol['enrolled'][$course->id] = $until;
  2574. $access = true;
  2575. } else {
  2576. $instances = $DB->get_records('enrol', array('courseid'=>$course->id, 'status'=>ENROL_INSTANCE_ENABLED), 'sortorder, id ASC');
  2577. $enrols = enrol_get_plugins(true);
  2578. // first ask all enabled enrol instances in course if they want to auto enrol user
  2579. foreach($instances as $instance) {
  2580. if (!isset($enrols[$instance->enrol])) {
  2581. continue;
  2582. }
  2583. // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
  2584. $until = $enrols[$instance->enrol]->try_autoenrol($instance);
  2585. if ($until !== false) {
  2586. if ($until == 0) {
  2587. $until = ENROL_MAX_TIMESTAMP;
  2588. }
  2589. $USER->enrol['enrolled'][$course->id] = $until;
  2590. $access = true;
  2591. break;
  2592. }
  2593. }
  2594. // if not enrolled yet try to gain temporary guest access
  2595. if (!$access) {
  2596. foreach($instances as $instance) {
  2597. if (!isset($enrols[$instance->enrol])) {
  2598. continue;
  2599. }
  2600. // Get a duration for the guest access, a timestamp in the future or false.
  2601. $until = $enrols[$instance->enrol]->try_guestaccess($instance);
  2602. if ($until !== false and $until > time()) {
  2603. $USER->enrol['tempguest'][$course->id] = $until;
  2604. $access = true;
  2605. break;
  2606. }
  2607. }
  2608. }
  2609. }
  2610. }
  2611. }
  2612. if (!$access) {
  2613. if ($preventredirect) {
  2614. throw new require_login_exception('Not enrolled');
  2615. }
  2616. if ($setwantsurltome) {
  2617. $SESSION->wantsurl = qualified_me();
  2618. }
  2619. redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
  2620. }
  2621. }
  2622. // Check visibility of activity to current user; includes visible flag, groupmembersonly,
  2623. // conditional availability, etc
  2624. if ($cm && !$cm->uservisible) {
  2625. if ($preventredirect) {
  2626. throw new require_login_exception('Activity is hidden');
  2627. }
  2628. redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
  2629. }
  2630. // Finally access granted, update lastaccess times
  2631. user_accesstime_log($course->id);
  2632. }
  2633. /**
  2634. * This function just makes sure a user is logged out.
  2635. *
  2636. * @package core_access
  2637. */
  2638. function require_logout() {
  2639. global $USER;
  2640. $params = $USER;
  2641. if (isloggedin()) {
  2642. add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
  2643. $authsequence = get_enabled_auth_plugins(); // auths, in sequence
  2644. foreach($authsequence as $authname) {
  2645. $authplugin = get_auth_plugin($authname);
  2646. $authplugin->prelogout_hook();
  2647. }
  2648. }
  2649. events_trigger('user_logout', $params);
  2650. session_get_instance()->terminate_current();
  2651. unset($params);
  2652. }
  2653. /**
  2654. * Weaker version of require_login()
  2655. *
  2656. * This is a weaker version of {@link require_login()} which only requires login
  2657. * when called from within a course rather than the site page, unless
  2658. * the forcelogin option is turned on.
  2659. * @see require_login()
  2660. *
  2661. * @package core_access
  2662. * @category access
  2663. *
  2664. * @param mixed $courseorid The course object or id in question
  2665. * @param bool $autologinguest Allow autologin guests if that is wanted
  2666. * @param object $cm Course activity module if known
  2667. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  2668. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  2669. * in order to keep redirects working properly. MDL-14495
  2670. * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
  2671. * @return void
  2672. */
  2673. function require_course_login($courseorid, $autologinguest = true, $cm = NULL, $setwantsurltome = true, $preventredirect = false) {
  2674. global $CFG, $PAGE, $SITE;
  2675. $issite = (is_object($courseorid) and $courseorid->id == SITEID)
  2676. or (!is_object($courseorid) and $courseorid == SITEID);
  2677. if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
  2678. // note: nearly all pages call get_fast_modinfo anyway and it does not make any
  2679. // db queries so this is not really a performance concern, however it is obviously
  2680. // better if you use get_fast_modinfo to get the cm before calling this.
  2681. if (is_object($courseorid)) {
  2682. $course = $courseorid;
  2683. } else {
  2684. $course = clone($SITE);
  2685. }
  2686. $modinfo = get_fast_modinfo($course);
  2687. $cm = $modinfo->get_cm($cm->id);
  2688. }
  2689. if (!empty($CFG->forcelogin)) {
  2690. // login required for both SITE and courses
  2691. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2692. } else if ($issite && !empty($cm) and !$cm->uservisible) {
  2693. // always login for hidden activities
  2694. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2695. } else if ($issite) {
  2696. //login for SITE not required
  2697. if ($cm and empty($cm->visible)) {
  2698. // hidden activities are not accessible without login
  2699. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2700. } else if ($cm and !empty($CFG->enablegroupmembersonly) and $cm->groupmembersonly) {
  2701. // not-logged-in users do not have any group membership
  2702. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2703. } else {
  2704. // We still need to instatiate PAGE vars properly so that things
  2705. // that rely on it like navigation function correctly.
  2706. if (!empty($courseorid)) {
  2707. if (is_object($courseorid)) {
  2708. $course = $courseorid;
  2709. } else {
  2710. $course = clone($SITE);
  2711. }
  2712. if ($cm) {
  2713. if ($cm->course != $course->id) {
  2714. throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
  2715. }
  2716. $PAGE->set_cm($cm, $course);
  2717. $PAGE->set_pagelayout('incourse');
  2718. } else {
  2719. $PAGE->set_course($course);
  2720. }
  2721. } else {
  2722. // If $PAGE->course, and hence $PAGE->context, have not already been set
  2723. // up properly, set them up now.
  2724. $PAGE->set_course($PAGE->course);
  2725. }
  2726. //TODO: verify conditional activities here
  2727. user_accesstime_log(SITEID);
  2728. return;
  2729. }
  2730. } else {
  2731. // course login always required
  2732. require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
  2733. }
  2734. }
  2735. /**
  2736. * Require key login. Function terminates with error if key not found or incorrect.
  2737. *
  2738. * @global object
  2739. * @global object
  2740. * @global object
  2741. * @global object
  2742. * @uses NO_MOODLE_COOKIES
  2743. * @uses PARAM_ALPHANUM
  2744. * @param string $script unique script identifier
  2745. * @param int $instance optional instance id
  2746. * @return int Instance ID
  2747. */
  2748. function require_user_key_login($script, $instance=null) {
  2749. global $USER, $SESSION, $CFG, $DB;
  2750. if (!NO_MOODLE_COOKIES) {
  2751. print_error('sessioncookiesdisable');
  2752. }
  2753. /// extra safety
  2754. @session_write_close();
  2755. $keyvalue = required_param('key', PARAM_ALPHANUM);
  2756. if (!$key = $DB->get_record('user_private_key', array('script'=>$script, 'value'=>$keyvalue, 'instance'=>$instance))) {
  2757. print_error('invalidkey');
  2758. }
  2759. if (!empty($key->validuntil) and $key->validuntil < time()) {
  2760. print_error('expiredkey');
  2761. }
  2762. if ($key->iprestriction) {
  2763. $remoteaddr = getremoteaddr(null);
  2764. if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
  2765. print_error('ipmismatch');
  2766. }
  2767. }
  2768. if (!$user = $DB->get_record('user', array('id'=>$key->userid))) {
  2769. print_error('invaliduserid');
  2770. }
  2771. /// emulate normal session
  2772. enrol_check_plugins($user);
  2773. session_set_user($user);
  2774. /// note we are not using normal login
  2775. if (!defined('USER_KEY_LOGIN')) {
  2776. define('USER_KEY_LOGIN', true);
  2777. }
  2778. /// return instance id - it might be empty
  2779. return $key->instance;
  2780. }
  2781. /**
  2782. * Creates a new private user access key.
  2783. *
  2784. * @global object
  2785. * @param string $script unique target identifier
  2786. * @param int $userid
  2787. * @param int $instance optional instance id
  2788. * @param string $iprestriction optional ip restricted access
  2789. * @param timestamp $validuntil key valid only until given data
  2790. * @return string access key value
  2791. */
  2792. function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
  2793. global $DB;
  2794. $key = new stdClass();
  2795. $key->script = $script;
  2796. $key->userid = $userid;
  2797. $key->instance = $instance;
  2798. $key->iprestriction = $iprestriction;
  2799. $key->validuntil = $validuntil;
  2800. $key->timecreated = time();
  2801. $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
  2802. while ($DB->record_exists('user_private_key', array('value'=>$key->value))) {
  2803. // must be unique
  2804. $key->value = md5($userid.'_'.time().random_string(40));
  2805. }
  2806. $DB->insert_record('user_private_key', $key);
  2807. return $key->value;
  2808. }
  2809. /**
  2810. * Delete the user's new private user access keys for a particular script.
  2811. *
  2812. * @global object
  2813. * @param string $script unique target identifier
  2814. * @param int $userid
  2815. * @return void
  2816. */
  2817. function delete_user_key($script,$userid) {
  2818. global $DB;
  2819. $DB->delete_records('user_private_key', array('script'=>$script, 'userid'=>$userid));
  2820. }
  2821. /**
  2822. * Gets a private user access key (and creates one if one doesn't exist).
  2823. *
  2824. * @global object
  2825. * @param string $script unique target identifier
  2826. * @param int $userid
  2827. * @param int $instance optional instance id
  2828. * @param string $iprestriction optional ip restricted access
  2829. * @param timestamp $validuntil key valid only until given data
  2830. * @return string access key value
  2831. */
  2832. function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
  2833. global $DB;
  2834. if ($key = $DB->get_record('user_private_key', array('script'=>$script, 'userid'=>$userid,
  2835. 'instance'=>$instance, 'iprestriction'=>$iprestriction,
  2836. 'validuntil'=>$validuntil))) {
  2837. return $key->value;
  2838. } else {
  2839. return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
  2840. }
  2841. }
  2842. /**
  2843. * Modify the user table by setting the currently logged in user's
  2844. * last login to now.
  2845. *
  2846. * @global object
  2847. * @global object
  2848. * @return bool Always returns true
  2849. */
  2850. function update_user_login_times() {
  2851. global $USER, $DB;
  2852. $user = new stdClass();
  2853. $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
  2854. $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
  2855. $user->id = $USER->id;
  2856. $DB->update_record('user', $user);
  2857. return true;
  2858. }
  2859. /**
  2860. * Determines if a user has completed setting up their account.
  2861. *
  2862. * @param user $user A {@link $USER} object to test for the existence of a valid name and email
  2863. * @return bool
  2864. */
  2865. function user_not_fully_set_up($user) {
  2866. if (isguestuser($user)) {
  2867. return false;
  2868. }
  2869. return (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user));
  2870. }
  2871. /**
  2872. * Check whether the user has exceeded the bounce threshold
  2873. *
  2874. * @global object
  2875. * @global object
  2876. * @param user $user A {@link $USER} object
  2877. * @return bool true=>User has exceeded bounce threshold
  2878. */
  2879. function over_bounce_threshold($user) {
  2880. global $CFG, $DB;
  2881. if (empty($CFG->handlebounces)) {
  2882. return false;
  2883. }
  2884. if (empty($user->id)) { /// No real (DB) user, nothing to do here.
  2885. return false;
  2886. }
  2887. // set sensible defaults
  2888. if (empty($CFG->minbounces)) {
  2889. $CFG->minbounces = 10;
  2890. }
  2891. if (empty($CFG->bounceratio)) {
  2892. $CFG->bounceratio = .20;
  2893. }
  2894. $bouncecount = 0;
  2895. $sendcount = 0;
  2896. if ($bounce = $DB->get_record('user_preferences', array ('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
  2897. $bouncecount = $bounce->value;
  2898. }
  2899. if ($send = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
  2900. $sendcount = $send->value;
  2901. }
  2902. return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
  2903. }
  2904. /**
  2905. * Used to increment or reset email sent count
  2906. *
  2907. * @global object
  2908. * @param user $user object containing an id
  2909. * @param bool $reset will reset the count to 0
  2910. * @return void
  2911. */
  2912. function set_send_count($user,$reset=false) {
  2913. global $DB;
  2914. if (empty($user->id)) { /// No real (DB) user, nothing to do here.
  2915. return;
  2916. }
  2917. if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_send_count'))) {
  2918. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  2919. $DB->update_record('user_preferences', $pref);
  2920. }
  2921. else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
  2922. // make a new one
  2923. $pref = new stdClass();
  2924. $pref->name = 'email_send_count';
  2925. $pref->value = 1;
  2926. $pref->userid = $user->id;
  2927. $DB->insert_record('user_preferences', $pref, false);
  2928. }
  2929. }
  2930. /**
  2931. * Increment or reset user's email bounce count
  2932. *
  2933. * @global object
  2934. * @param user $user object containing an id
  2935. * @param bool $reset will reset the count to 0
  2936. */
  2937. function set_bounce_count($user,$reset=false) {
  2938. global $DB;
  2939. if ($pref = $DB->get_record('user_preferences', array('userid'=>$user->id, 'name'=>'email_bounce_count'))) {
  2940. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  2941. $DB->update_record('user_preferences', $pref);
  2942. }
  2943. else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
  2944. // make a new one
  2945. $pref = new stdClass();
  2946. $pref->name = 'email_bounce_count';
  2947. $pref->value = 1;
  2948. $pref->userid = $user->id;
  2949. $DB->insert_record('user_preferences', $pref, false);
  2950. }
  2951. }
  2952. /**
  2953. * Keeps track of login attempts
  2954. *
  2955. * @global object
  2956. */
  2957. function update_login_count() {
  2958. global $SESSION;
  2959. $max_logins = 10;
  2960. if (empty($SESSION->logincount)) {
  2961. $SESSION->logincount = 1;
  2962. } else {
  2963. $SESSION->logincount++;
  2964. }
  2965. if ($SESSION->logincount > $max_logins) {
  2966. unset($SESSION->wantsurl);
  2967. print_error('errortoomanylogins');
  2968. }
  2969. }
  2970. /**
  2971. * Resets login attempts
  2972. *
  2973. * @global object
  2974. */
  2975. function reset_login_count() {
  2976. global $SESSION;
  2977. $SESSION->logincount = 0;
  2978. }
  2979. /**
  2980. * Determines if the currently logged in user is in editing mode.
  2981. * Note: originally this function had $userid parameter - it was not usable anyway
  2982. *
  2983. * @deprecated since Moodle 2.0 - use $PAGE->user_is_editing() instead.
  2984. * @todo Deprecated function remove when ready
  2985. *
  2986. * @global object
  2987. * @uses DEBUG_DEVELOPER
  2988. * @return bool
  2989. */
  2990. function isediting() {
  2991. global $PAGE;
  2992. debugging('call to deprecated function isediting(). Please use $PAGE->user_is_editing() instead', DEBUG_DEVELOPER);
  2993. return $PAGE->user_is_editing();
  2994. }
  2995. /**
  2996. * Determines if the logged in user is currently moving an activity
  2997. *
  2998. * @global object
  2999. * @param int $courseid The id of the course being tested
  3000. * @return bool
  3001. */
  3002. function ismoving($courseid) {
  3003. global $USER;
  3004. if (!empty($USER->activitycopy)) {
  3005. return ($USER->activitycopycourse == $courseid);
  3006. }
  3007. return false;
  3008. }
  3009. /**
  3010. * Returns a persons full name
  3011. *
  3012. * Given an object containing firstname and lastname
  3013. * values, this function returns a string with the
  3014. * full name of the person.
  3015. * The result may depend on system settings
  3016. * or language. 'override' will force both names
  3017. * to be used even if system settings specify one.
  3018. *
  3019. * @global object
  3020. * @global object
  3021. * @param object $user A {@link $USER} object to get full name of
  3022. * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
  3023. * @return string
  3024. */
  3025. function fullname($user, $override=false) {
  3026. global $CFG, $SESSION;
  3027. if (!isset($user->firstname) and !isset($user->lastname)) {
  3028. return '';
  3029. }
  3030. if (!$override) {
  3031. if (!empty($CFG->forcefirstname)) {
  3032. $user->firstname = $CFG->forcefirstname;
  3033. }
  3034. if (!empty($CFG->forcelastname)) {
  3035. $user->lastname = $CFG->forcelastname;
  3036. }
  3037. }
  3038. if (!empty($SESSION->fullnamedisplay)) {
  3039. $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
  3040. }
  3041. if (!isset($CFG->fullnamedisplay) or $CFG->fullnamedisplay === 'firstname lastname') {
  3042. return $user->firstname .' '. $user->lastname;
  3043. } else if ($CFG->fullnamedisplay == 'lastname firstname') {
  3044. return $user->lastname .' '. $user->firstname;
  3045. } else if ($CFG->fullnamedisplay == 'firstname') {
  3046. if ($override) {
  3047. return get_string('fullnamedisplay', '', $user);
  3048. } else {
  3049. return $user->firstname;
  3050. }
  3051. }
  3052. return get_string('fullnamedisplay', '', $user);
  3053. }
  3054. /**
  3055. * Checks if current user is shown any extra fields when listing users.
  3056. * @param object $context Context
  3057. * @param array $already Array of fields that we're going to show anyway
  3058. * so don't bother listing them
  3059. * @return array Array of field names from user table, not including anything
  3060. * listed in $already
  3061. */
  3062. function get_extra_user_fields($context, $already = array()) {
  3063. global $CFG;
  3064. // Only users with permission get the extra fields
  3065. if (!has_capability('moodle/site:viewuseridentity', $context)) {
  3066. return array();
  3067. }
  3068. // Split showuseridentity on comma
  3069. if (empty($CFG->showuseridentity)) {
  3070. // Explode gives wrong result with empty string
  3071. $extra = array();
  3072. } else {
  3073. $extra = explode(',', $CFG->showuseridentity);
  3074. }
  3075. $renumber = false;
  3076. foreach ($extra as $key => $field) {
  3077. if (in_array($field, $already)) {
  3078. unset($extra[$key]);
  3079. $renumber = true;
  3080. }
  3081. }
  3082. if ($renumber) {
  3083. // For consistency, if entries are removed from array, renumber it
  3084. // so they are numbered as you would expect
  3085. $extra = array_merge($extra);
  3086. }
  3087. return $extra;
  3088. }
  3089. /**
  3090. * If the current user is to be shown extra user fields when listing or
  3091. * selecting users, returns a string suitable for including in an SQL select
  3092. * clause to retrieve those fields.
  3093. * @param object $context Context
  3094. * @param string $alias Alias of user table, e.g. 'u' (default none)
  3095. * @param string $prefix Prefix for field names using AS, e.g. 'u_' (default none)
  3096. * @param array $already Array of fields that we're going to include anyway
  3097. * so don't list them (default none)
  3098. * @return string Partial SQL select clause, beginning with comma, for example
  3099. * ',u.idnumber,u.department' unless it is blank
  3100. */
  3101. function get_extra_user_fields_sql($context, $alias='', $prefix='',
  3102. $already = array()) {
  3103. $fields = get_extra_user_fields($context, $already);
  3104. $result = '';
  3105. // Add punctuation for alias
  3106. if ($alias !== '') {
  3107. $alias .= '.';
  3108. }
  3109. foreach ($fields as $field) {
  3110. $result .= ', ' . $alias . $field;
  3111. if ($prefix) {
  3112. $result .= ' AS ' . $prefix . $field;
  3113. }
  3114. }
  3115. return $result;
  3116. }
  3117. /**
  3118. * Returns the display name of a field in the user table. Works for most fields
  3119. * that are commonly displayed to users.
  3120. * @param string $field Field name, e.g. 'phone1'
  3121. * @return string Text description taken from language file, e.g. 'Phone number'
  3122. */
  3123. function get_user_field_name($field) {
  3124. // Some fields have language strings which are not the same as field name
  3125. switch ($field) {
  3126. case 'phone1' : return get_string('phone');
  3127. }
  3128. // Otherwise just use the same lang string
  3129. return get_string($field);
  3130. }
  3131. /**
  3132. * Returns whether a given authentication plugin exists.
  3133. *
  3134. * @global object
  3135. * @param string $auth Form of authentication to check for. Defaults to the
  3136. * global setting in {@link $CFG}.
  3137. * @return boolean Whether the plugin is available.
  3138. */
  3139. function exists_auth_plugin($auth) {
  3140. global $CFG;
  3141. if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
  3142. return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
  3143. }
  3144. return false;
  3145. }
  3146. /**
  3147. * Checks if a given plugin is in the list of enabled authentication plugins.
  3148. *
  3149. * @param string $auth Authentication plugin.
  3150. * @return boolean Whether the plugin is enabled.
  3151. */
  3152. function is_enabled_auth($auth) {
  3153. if (empty($auth)) {
  3154. return false;
  3155. }
  3156. $enabled = get_enabled_auth_plugins();
  3157. return in_array($auth, $enabled);
  3158. }
  3159. /**
  3160. * Returns an authentication plugin instance.
  3161. *
  3162. * @global object
  3163. * @param string $auth name of authentication plugin
  3164. * @return auth_plugin_base An instance of the required authentication plugin.
  3165. */
  3166. function get_auth_plugin($auth) {
  3167. global $CFG;
  3168. // check the plugin exists first
  3169. if (! exists_auth_plugin($auth)) {
  3170. print_error('authpluginnotfound', 'debug', '', $auth);
  3171. }
  3172. // return auth plugin instance
  3173. require_once "{$CFG->dirroot}/auth/$auth/auth.php";
  3174. $class = "auth_plugin_$auth";
  3175. return new $class;
  3176. }
  3177. /**
  3178. * Returns array of active auth plugins.
  3179. *
  3180. * @param bool $fix fix $CFG->auth if needed
  3181. * @return array
  3182. */
  3183. function get_enabled_auth_plugins($fix=false) {
  3184. global $CFG;
  3185. $default = array('manual', 'nologin');
  3186. if (empty($CFG->auth)) {
  3187. $auths = array();
  3188. } else {
  3189. $auths = explode(',', $CFG->auth);
  3190. }
  3191. if ($fix) {
  3192. $auths = array_unique($auths);
  3193. foreach($auths as $k=>$authname) {
  3194. if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
  3195. unset($auths[$k]);
  3196. }
  3197. }
  3198. $newconfig = implode(',', $auths);
  3199. if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
  3200. set_config('auth', $newconfig);
  3201. }
  3202. }
  3203. return (array_merge($default, $auths));
  3204. }
  3205. /**
  3206. * Returns true if an internal authentication method is being used.
  3207. * if method not specified then, global default is assumed
  3208. *
  3209. * @param string $auth Form of authentication required
  3210. * @return bool
  3211. */
  3212. function is_internal_auth($auth) {
  3213. $authplugin = get_auth_plugin($auth); // throws error if bad $auth
  3214. return $authplugin->is_internal();
  3215. }
  3216. /**
  3217. * Returns true if the user is a 'restored' one
  3218. *
  3219. * Used in the login process to inform the user
  3220. * and allow him/her to reset the password
  3221. *
  3222. * @uses $CFG
  3223. * @uses $DB
  3224. * @param string $username username to be checked
  3225. * @return bool
  3226. */
  3227. function is_restored_user($username) {
  3228. global $CFG, $DB;
  3229. return $DB->record_exists('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id, 'password'=>'restored'));
  3230. }
  3231. /**
  3232. * Returns an array of user fields
  3233. *
  3234. * @return array User field/column names
  3235. */
  3236. function get_user_fieldnames() {
  3237. global $DB;
  3238. $fieldarray = $DB->get_columns('user');
  3239. unset($fieldarray['id']);
  3240. $fieldarray = array_keys($fieldarray);
  3241. return $fieldarray;
  3242. }
  3243. /**
  3244. * Creates a bare-bones user record
  3245. *
  3246. * @todo Outline auth types and provide code example
  3247. *
  3248. * @param string $username New user's username to add to record
  3249. * @param string $password New user's password to add to record
  3250. * @param string $auth Form of authentication required
  3251. * @return stdClass A complete user object
  3252. */
  3253. function create_user_record($username, $password, $auth = 'manual') {
  3254. global $CFG, $DB;
  3255. //just in case check text case
  3256. $username = trim(textlib::strtolower($username));
  3257. $authplugin = get_auth_plugin($auth);
  3258. $newuser = new stdClass();
  3259. if ($newinfo = $authplugin->get_userinfo($username)) {
  3260. $newinfo = truncate_userinfo($newinfo);
  3261. foreach ($newinfo as $key => $value){
  3262. $newuser->$key = $value;
  3263. }
  3264. }
  3265. if (!empty($newuser->email)) {
  3266. if (email_is_not_allowed($newuser->email)) {
  3267. unset($newuser->email);
  3268. }
  3269. }
  3270. if (!isset($newuser->city)) {
  3271. $newuser->city = '';
  3272. }
  3273. $newuser->auth = $auth;
  3274. $newuser->username = $username;
  3275. // fix for MDL-8480
  3276. // user CFG lang for user if $newuser->lang is empty
  3277. // or $user->lang is not an installed language
  3278. if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
  3279. $newuser->lang = $CFG->lang;
  3280. }
  3281. $newuser->confirmed = 1;
  3282. $newuser->lastip = getremoteaddr();
  3283. $newuser->timecreated = time();
  3284. $newuser->timemodified = $newuser->timecreated;
  3285. $newuser->mnethostid = $CFG->mnet_localhost_id;
  3286. $newuser->id = $DB->insert_record('user', $newuser);
  3287. $user = get_complete_user_data('id', $newuser->id);
  3288. if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
  3289. set_user_preference('auth_forcepasswordchange', 1, $user);
  3290. }
  3291. update_internal_user_password($user, $password);
  3292. // fetch full user record for the event, the complete user data contains too much info
  3293. // and we want to be consistent with other places that trigger this event
  3294. events_trigger('user_created', $DB->get_record('user', array('id'=>$user->id)));
  3295. return $user;
  3296. }
  3297. /**
  3298. * Will update a local user record from an external source.
  3299. * (MNET users can not be updated using this method!)
  3300. *
  3301. * @param string $username user's username to update the record
  3302. * @return stdClass A complete user object
  3303. */
  3304. function update_user_record($username) {
  3305. global $DB, $CFG;
  3306. $username = trim(textlib::strtolower($username)); /// just in case check text case
  3307. $oldinfo = $DB->get_record('user', array('username'=>$username, 'mnethostid'=>$CFG->mnet_localhost_id), '*', MUST_EXIST);
  3308. $newuser = array();
  3309. $userauth = get_auth_plugin($oldinfo->auth);
  3310. if ($newinfo = $userauth->get_userinfo($username)) {
  3311. $newinfo = truncate_userinfo($newinfo);
  3312. foreach ($newinfo as $key => $value){
  3313. $key = strtolower($key);
  3314. if (!property_exists($oldinfo, $key) or $key === 'username' or $key === 'id'
  3315. or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
  3316. // unknown or must not be changed
  3317. continue;
  3318. }
  3319. $confval = $userauth->config->{'field_updatelocal_' . $key};
  3320. $lockval = $userauth->config->{'field_lock_' . $key};
  3321. if (empty($confval) || empty($lockval)) {
  3322. continue;
  3323. }
  3324. if ($confval === 'onlogin') {
  3325. // MDL-4207 Don't overwrite modified user profile values with
  3326. // empty LDAP values when 'unlocked if empty' is set. The purpose
  3327. // of the setting 'unlocked if empty' is to allow the user to fill
  3328. // in a value for the selected field _if LDAP is giving
  3329. // nothing_ for this field. Thus it makes sense to let this value
  3330. // stand in until LDAP is giving a value for this field.
  3331. if (!(empty($value) && $lockval === 'unlockedifempty')) {
  3332. if ((string)$oldinfo->$key !== (string)$value) {
  3333. $newuser[$key] = (string)$value;
  3334. }
  3335. }
  3336. }
  3337. }
  3338. if ($newuser) {
  3339. $newuser['id'] = $oldinfo->id;
  3340. $newuser['timemodified'] = time();
  3341. $DB->update_record('user', $newuser);
  3342. // fetch full user record for the event, the complete user data contains too much info
  3343. // and we want to be consistent with other places that trigger this event
  3344. events_trigger('user_updated', $DB->get_record('user', array('id'=>$oldinfo->id)));
  3345. }
  3346. }
  3347. return get_complete_user_data('id', $oldinfo->id);
  3348. }
  3349. /**
  3350. * Will truncate userinfo as it comes from auth_get_userinfo (from external auth)
  3351. * which may have large fields
  3352. *
  3353. * @todo Add vartype handling to ensure $info is an array
  3354. *
  3355. * @param array $info Array of user properties to truncate if needed
  3356. * @return array The now truncated information that was passed in
  3357. */
  3358. function truncate_userinfo($info) {
  3359. // define the limits
  3360. $limit = array(
  3361. 'username' => 100,
  3362. 'idnumber' => 255,
  3363. 'firstname' => 100,
  3364. 'lastname' => 100,
  3365. 'email' => 100,
  3366. 'icq' => 15,
  3367. 'phone1' => 20,
  3368. 'phone2' => 20,
  3369. 'institution' => 40,
  3370. 'department' => 30,
  3371. 'address' => 70,
  3372. 'city' => 120,
  3373. 'country' => 2,
  3374. 'url' => 255,
  3375. );
  3376. // apply where needed
  3377. foreach (array_keys($info) as $key) {
  3378. if (!empty($limit[$key])) {
  3379. $info[$key] = trim(textlib::substr($info[$key],0, $limit[$key]));
  3380. }
  3381. }
  3382. return $info;
  3383. }
  3384. /**
  3385. * Marks user deleted in internal user database and notifies the auth plugin.
  3386. * Also unenrols user from all roles and does other cleanup.
  3387. *
  3388. * Any plugin that needs to purge user data should register the 'user_deleted' event.
  3389. *
  3390. * @param stdClass $user full user object before delete
  3391. * @return boolean always true
  3392. */
  3393. function delete_user($user) {
  3394. global $CFG, $DB;
  3395. require_once($CFG->libdir.'/grouplib.php');
  3396. require_once($CFG->libdir.'/gradelib.php');
  3397. require_once($CFG->dirroot.'/message/lib.php');
  3398. require_once($CFG->dirroot.'/tag/lib.php');
  3399. // delete all grades - backup is kept in grade_grades_history table
  3400. grade_user_delete($user->id);
  3401. //move unread messages from this user to read
  3402. message_move_userfrom_unread2read($user->id);
  3403. // TODO: remove from cohorts using standard API here
  3404. // remove user tags
  3405. tag_set('user', $user->id, array());
  3406. // unconditionally unenrol from all courses
  3407. enrol_user_delete($user);
  3408. // unenrol from all roles in all contexts
  3409. role_unassign_all(array('userid'=>$user->id)); // this might be slow but it is really needed - modules might do some extra cleanup!
  3410. //now do a brute force cleanup
  3411. // remove from all cohorts
  3412. $DB->delete_records('cohort_members', array('userid'=>$user->id));
  3413. // remove from all groups
  3414. $DB->delete_records('groups_members', array('userid'=>$user->id));
  3415. // brute force unenrol from all courses
  3416. $DB->delete_records('user_enrolments', array('userid'=>$user->id));
  3417. // purge user preferences
  3418. $DB->delete_records('user_preferences', array('userid'=>$user->id));
  3419. // purge user extra profile info
  3420. $DB->delete_records('user_info_data', array('userid'=>$user->id));
  3421. // last course access not necessary either
  3422. $DB->delete_records('user_lastaccess', array('userid'=>$user->id));
  3423. // remove all user tokens
  3424. $DB->delete_records('external_tokens', array('userid'=>$user->id));
  3425. // unauthorise the user for all services
  3426. $DB->delete_records('external_services_users', array('userid'=>$user->id));
  3427. // force logout - may fail if file based sessions used, sorry
  3428. session_kill_user($user->id);
  3429. // now do a final accesslib cleanup - removes all role assignments in user context and context itself
  3430. delete_context(CONTEXT_USER, $user->id);
  3431. // workaround for bulk deletes of users with the same email address
  3432. $delname = "$user->email.".time();
  3433. while ($DB->record_exists('user', array('username'=>$delname))) { // no need to use mnethostid here
  3434. $delname++;
  3435. }
  3436. // mark internal user record as "deleted"
  3437. $updateuser = new stdClass();
  3438. $updateuser->id = $user->id;
  3439. $updateuser->deleted = 1;
  3440. $updateuser->username = $delname; // Remember it just in case
  3441. $updateuser->email = md5($user->username);// Store hash of username, useful importing/restoring users
  3442. $updateuser->idnumber = ''; // Clear this field to free it up
  3443. $updateuser->picture = 0;
  3444. $updateuser->timemodified = time();
  3445. $DB->update_record('user', $updateuser);
  3446. // Add this action to log
  3447. add_to_log(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
  3448. // We will update the user's timemodified, as it will be passed to the user_deleted event, which
  3449. // should know about this updated property persisted to the user's table.
  3450. $user->timemodified = $updateuser->timemodified;
  3451. // notify auth plugin - do not block the delete even when plugin fails
  3452. $authplugin = get_auth_plugin($user->auth);
  3453. $authplugin->user_delete($user);
  3454. // any plugin that needs to cleanup should register this event
  3455. events_trigger('user_deleted', $user);
  3456. return true;
  3457. }
  3458. /**
  3459. * Retrieve the guest user object
  3460. *
  3461. * @global object
  3462. * @global object
  3463. * @return user A {@link $USER} object
  3464. */
  3465. function guest_user() {
  3466. global $CFG, $DB;
  3467. if ($newuser = $DB->get_record('user', array('id'=>$CFG->siteguest))) {
  3468. $newuser->confirmed = 1;
  3469. $newuser->lang = $CFG->lang;
  3470. $newuser->lastip = getremoteaddr();
  3471. }
  3472. return $newuser;
  3473. }
  3474. /**
  3475. * Authenticates a user against the chosen authentication mechanism
  3476. *
  3477. * Given a username and password, this function looks them
  3478. * up using the currently selected authentication mechanism,
  3479. * and if the authentication is successful, it returns a
  3480. * valid $user object from the 'user' table.
  3481. *
  3482. * Uses auth_ functions from the currently active auth module
  3483. *
  3484. * After authenticate_user_login() returns success, you will need to
  3485. * log that the user has logged in, and call complete_user_login() to set
  3486. * the session up.
  3487. *
  3488. * Note: this function works only with non-mnet accounts!
  3489. *
  3490. * @param string $username User's username
  3491. * @param string $password User's password
  3492. * @return user|flase A {@link $USER} object or false if error
  3493. */
  3494. function authenticate_user_login($username, $password) {
  3495. global $CFG, $DB;
  3496. $authsenabled = get_enabled_auth_plugins();
  3497. if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
  3498. $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
  3499. if (!empty($user->suspended)) {
  3500. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3501. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3502. return false;
  3503. }
  3504. if ($auth=='nologin' or !is_enabled_auth($auth)) {
  3505. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3506. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3507. return false;
  3508. }
  3509. $auths = array($auth);
  3510. } else {
  3511. // check if there's a deleted record (cheaply)
  3512. if ($DB->get_field('user', 'id', array('username'=>$username, 'deleted'=>1))) {
  3513. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3514. return false;
  3515. }
  3516. // User does not exist
  3517. $auths = $authsenabled;
  3518. $user = new stdClass();
  3519. $user->id = 0;
  3520. }
  3521. foreach ($auths as $auth) {
  3522. $authplugin = get_auth_plugin($auth);
  3523. // on auth fail fall through to the next plugin
  3524. if (!$authplugin->user_login($username, $password)) {
  3525. continue;
  3526. }
  3527. // successful authentication
  3528. if ($user->id) { // User already exists in database
  3529. if (empty($user->auth)) { // For some reason auth isn't set yet
  3530. $DB->set_field('user', 'auth', $auth, array('username'=>$username));
  3531. $user->auth = $auth;
  3532. }
  3533. if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
  3534. $DB->set_field('user','firstaccess', $user->timemodified, array('id' => $user->id));
  3535. $user->firstaccess = $user->timemodified;
  3536. }
  3537. update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
  3538. if ($authplugin->is_synchronised_with_external()) { // update user record from external DB
  3539. $user = update_user_record($username);
  3540. }
  3541. } else {
  3542. // if user not found and user creation is not disabled, create it
  3543. if (empty($CFG->authpreventaccountcreation)) {
  3544. $user = create_user_record($username, $password, $auth);
  3545. } else {
  3546. continue;
  3547. }
  3548. }
  3549. $authplugin->sync_roles($user);
  3550. foreach ($authsenabled as $hau) {
  3551. $hauth = get_auth_plugin($hau);
  3552. $hauth->user_authenticated_hook($user, $username, $password);
  3553. }
  3554. if (empty($user->id)) {
  3555. return false;
  3556. }
  3557. if (!empty($user->suspended)) {
  3558. // just in case some auth plugin suspended account
  3559. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3560. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Suspended Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3561. return false;
  3562. }
  3563. return $user;
  3564. }
  3565. // failed if all the plugins have failed
  3566. add_to_log(SITEID, 'login', 'error', 'index.php', $username);
  3567. if (debugging('', DEBUG_ALL)) {
  3568. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  3569. }
  3570. return false;
  3571. }
  3572. /**
  3573. * Call to complete the user login process after authenticate_user_login()
  3574. * has succeeded. It will setup the $USER variable and other required bits
  3575. * and pieces.
  3576. *
  3577. * NOTE:
  3578. * - It will NOT log anything -- up to the caller to decide what to log.
  3579. * - this function does not set any cookies any more!
  3580. *
  3581. * @param object $user
  3582. * @return object A {@link $USER} object - BC only, do not use
  3583. */
  3584. function complete_user_login($user) {
  3585. global $CFG, $USER;
  3586. // regenerate session id and delete old session,
  3587. // this helps prevent session fixation attacks from the same domain
  3588. session_regenerate_id(true);
  3589. // let enrol plugins deal with new enrolments if necessary
  3590. enrol_check_plugins($user);
  3591. // check enrolments, load caps and setup $USER object
  3592. session_set_user($user);
  3593. // reload preferences from DB
  3594. unset($USER->preference);
  3595. check_user_preferences_loaded($USER);
  3596. // update login times
  3597. update_user_login_times();
  3598. // extra session prefs init
  3599. set_login_session_preferences();
  3600. if (isguestuser()) {
  3601. // no need to continue when user is THE guest
  3602. return $USER;
  3603. }
  3604. /// Select password change url
  3605. $userauth = get_auth_plugin($USER->auth);
  3606. /// check whether the user should be changing password
  3607. if (get_user_preferences('auth_forcepasswordchange', false)){
  3608. if ($userauth->can_change_password()) {
  3609. if ($changeurl = $userauth->change_password_url()) {
  3610. redirect($changeurl);
  3611. } else {
  3612. redirect($CFG->httpswwwroot.'/login/change_password.php');
  3613. }
  3614. } else {
  3615. print_error('nopasswordchangeforced', 'auth');
  3616. }
  3617. }
  3618. return $USER;
  3619. }
  3620. /**
  3621. * Compare password against hash stored in internal user table.
  3622. * If necessary it also updates the stored hash to new format.
  3623. *
  3624. * @param stdClass $user (password property may be updated)
  3625. * @param string $password plain text password
  3626. * @return bool is password valid?
  3627. */
  3628. function validate_internal_user_password($user, $password) {
  3629. global $CFG;
  3630. if (!isset($CFG->passwordsaltmain)) {
  3631. $CFG->passwordsaltmain = '';
  3632. }
  3633. $validated = false;
  3634. if ($user->password === 'not cached') {
  3635. // internal password is not used at all, it can not validate
  3636. } else if ($user->password === md5($password.$CFG->passwordsaltmain)
  3637. or $user->password === md5($password)
  3638. or $user->password === md5(addslashes($password).$CFG->passwordsaltmain)
  3639. or $user->password === md5(addslashes($password))) {
  3640. // note: we are intentionally using the addslashes() here because we
  3641. // need to accept old password hashes of passwords with magic quotes
  3642. $validated = true;
  3643. } else {
  3644. for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
  3645. $alt = 'passwordsaltalt'.$i;
  3646. if (!empty($CFG->$alt)) {
  3647. if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
  3648. $validated = true;
  3649. break;
  3650. }
  3651. }
  3652. }
  3653. }
  3654. if ($validated) {
  3655. // force update of password hash using latest main password salt and encoding if needed
  3656. update_internal_user_password($user, $password);
  3657. }
  3658. return $validated;
  3659. }
  3660. /**
  3661. * Calculate hashed value from password using current hash mechanism.
  3662. *
  3663. * @param string $password
  3664. * @return string password hash
  3665. */
  3666. function hash_internal_user_password($password) {
  3667. global $CFG;
  3668. if (isset($CFG->passwordsaltmain)) {
  3669. return md5($password.$CFG->passwordsaltmain);
  3670. } else {
  3671. return md5($password);
  3672. }
  3673. }
  3674. /**
  3675. * Update password hash in user object.
  3676. *
  3677. * @param stdClass $user (password property may be updated)
  3678. * @param string $password plain text password
  3679. * @return bool always returns true
  3680. */
  3681. function update_internal_user_password($user, $password) {
  3682. global $DB;
  3683. $authplugin = get_auth_plugin($user->auth);
  3684. if ($authplugin->prevent_local_passwords()) {
  3685. $hashedpassword = 'not cached';
  3686. } else {
  3687. $hashedpassword = hash_internal_user_password($password);
  3688. }
  3689. if ($user->password !== $hashedpassword) {
  3690. $DB->set_field('user', 'password', $hashedpassword, array('id'=>$user->id));
  3691. $user->password = $hashedpassword;
  3692. }
  3693. return true;
  3694. }
  3695. /**
  3696. * Get a complete user record, which includes all the info
  3697. * in the user record.
  3698. *
  3699. * Intended for setting as $USER session variable
  3700. *
  3701. * @param string $field The user field to be checked for a given value.
  3702. * @param string $value The value to match for $field.
  3703. * @param int $mnethostid
  3704. * @return mixed False, or A {@link $USER} object.
  3705. */
  3706. function get_complete_user_data($field, $value, $mnethostid = null) {
  3707. global $CFG, $DB;
  3708. if (!$field || !$value) {
  3709. return false;
  3710. }
  3711. /// Build the WHERE clause for an SQL query
  3712. $params = array('fieldval'=>$value);
  3713. $constraints = "$field = :fieldval AND deleted <> 1";
  3714. // If we are loading user data based on anything other than id,
  3715. // we must also restrict our search based on mnet host.
  3716. if ($field != 'id') {
  3717. if (empty($mnethostid)) {
  3718. // if empty, we restrict to local users
  3719. $mnethostid = $CFG->mnet_localhost_id;
  3720. }
  3721. }
  3722. if (!empty($mnethostid)) {
  3723. $params['mnethostid'] = $mnethostid;
  3724. $constraints .= " AND mnethostid = :mnethostid";
  3725. }
  3726. /// Get all the basic user data
  3727. if (! $user = $DB->get_record_select('user', $constraints, $params)) {
  3728. return false;
  3729. }
  3730. /// Get various settings and preferences
  3731. // preload preference cache
  3732. check_user_preferences_loaded($user);
  3733. // load course enrolment related stuff
  3734. $user->lastcourseaccess = array(); // during last session
  3735. $user->currentcourseaccess = array(); // during current session
  3736. if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid'=>$user->id))) {
  3737. foreach ($lastaccesses as $lastaccess) {
  3738. $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
  3739. }
  3740. }
  3741. $sql = "SELECT g.id, g.courseid
  3742. FROM {groups} g, {groups_members} gm
  3743. WHERE gm.groupid=g.id AND gm.userid=?";
  3744. // this is a special hack to speedup calendar display
  3745. $user->groupmember = array();
  3746. if (!isguestuser($user)) {
  3747. if ($groups = $DB->get_records_sql($sql, array($user->id))) {
  3748. foreach ($groups as $group) {
  3749. if (!array_key_exists($group->courseid, $user->groupmember)) {
  3750. $user->groupmember[$group->courseid] = array();
  3751. }
  3752. $user->groupmember[$group->courseid][$group->id] = $group->id;
  3753. }
  3754. }
  3755. }
  3756. /// Add the custom profile fields to the user record
  3757. $user->profile = array();
  3758. if (!isguestuser($user)) {
  3759. require_once($CFG->dirroot.'/user/profile/lib.php');
  3760. profile_load_custom_fields($user);
  3761. }
  3762. /// Rewrite some variables if necessary
  3763. if (!empty($user->description)) {
  3764. $user->description = true; // No need to cart all of it around
  3765. }
  3766. if (isguestuser($user)) {
  3767. $user->lang = $CFG->lang; // Guest language always same as site
  3768. $user->firstname = get_string('guestuser'); // Name always in current language
  3769. $user->lastname = ' ';
  3770. }
  3771. return $user;
  3772. }
  3773. /**
  3774. * Validate a password against the configured password policy
  3775. *
  3776. * @global object
  3777. * @param string $password the password to be checked against the password policy
  3778. * @param string $errmsg the error message to display when the password doesn't comply with the policy.
  3779. * @return bool true if the password is valid according to the policy. false otherwise.
  3780. */
  3781. function check_password_policy($password, &$errmsg) {
  3782. global $CFG;
  3783. if (empty($CFG->passwordpolicy)) {
  3784. return true;
  3785. }
  3786. $errmsg = '';
  3787. if (textlib::strlen($password) < $CFG->minpasswordlength) {
  3788. $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
  3789. }
  3790. if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
  3791. $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
  3792. }
  3793. if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
  3794. $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
  3795. }
  3796. if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
  3797. $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
  3798. }
  3799. if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
  3800. $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
  3801. }
  3802. if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
  3803. $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
  3804. }
  3805. if ($errmsg == '') {
  3806. return true;
  3807. } else {
  3808. return false;
  3809. }
  3810. }
  3811. /**
  3812. * When logging in, this function is run to set certain preferences
  3813. * for the current SESSION
  3814. *
  3815. * @global object
  3816. * @global object
  3817. */
  3818. function set_login_session_preferences() {
  3819. global $SESSION, $CFG;
  3820. $SESSION->justloggedin = true;
  3821. unset($SESSION->lang);
  3822. }
  3823. /**
  3824. * Delete a course, including all related data from the database,
  3825. * and any associated files.
  3826. *
  3827. * @global object
  3828. * @global object
  3829. * @param mixed $courseorid The id of the course or course object to delete.
  3830. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  3831. * @return bool true if all the removals succeeded. false if there were any failures. If this
  3832. * method returns false, some of the removals will probably have succeeded, and others
  3833. * failed, but you have no way of knowing which.
  3834. */
  3835. function delete_course($courseorid, $showfeedback = true) {
  3836. global $DB;
  3837. if (is_object($courseorid)) {
  3838. $courseid = $courseorid->id;
  3839. $course = $courseorid;
  3840. } else {
  3841. $courseid = $courseorid;
  3842. if (!$course = $DB->get_record('course', array('id'=>$courseid))) {
  3843. return false;
  3844. }
  3845. }
  3846. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  3847. // frontpage course can not be deleted!!
  3848. if ($courseid == SITEID) {
  3849. return false;
  3850. }
  3851. // make the course completely empty
  3852. remove_course_contents($courseid, $showfeedback);
  3853. // delete the course and related context instance
  3854. delete_context(CONTEXT_COURSE, $courseid);
  3855. // We will update the course's timemodified, as it will be passed to the course_deleted event,
  3856. // which should know about this updated property, as this event is meant to pass the full course record
  3857. $course->timemodified = time();
  3858. $DB->delete_records("course", array("id"=>$courseid));
  3859. //trigger events
  3860. $course->context = $context; // you can not fetch context in the event because it was already deleted
  3861. events_trigger('course_deleted', $course);
  3862. return true;
  3863. }
  3864. /**
  3865. * Clear a course out completely, deleting all content
  3866. * but don't delete the course itself.
  3867. * This function does not verify any permissions.
  3868. *
  3869. * Please note this function also deletes all user enrolments,
  3870. * enrolment instances and role assignments by default.
  3871. *
  3872. * $options:
  3873. * - 'keep_roles_and_enrolments' - false by default
  3874. * - 'keep_groups_and_groupings' - false by default
  3875. *
  3876. * @param int $courseid The id of the course that is being deleted
  3877. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  3878. * @param array $options extra options
  3879. * @return bool true if all the removals succeeded. false if there were any failures. If this
  3880. * method returns false, some of the removals will probably have succeeded, and others
  3881. * failed, but you have no way of knowing which.
  3882. */
  3883. function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
  3884. global $CFG, $DB, $OUTPUT;
  3885. require_once($CFG->libdir.'/completionlib.php');
  3886. require_once($CFG->libdir.'/questionlib.php');
  3887. require_once($CFG->libdir.'/gradelib.php');
  3888. require_once($CFG->dirroot.'/group/lib.php');
  3889. require_once($CFG->dirroot.'/tag/coursetagslib.php');
  3890. require_once($CFG->dirroot.'/comment/lib.php');
  3891. require_once($CFG->dirroot.'/rating/lib.php');
  3892. // NOTE: these concatenated strings are suboptimal, but it is just extra info...
  3893. $strdeleted = get_string('deleted').' - ';
  3894. // Some crazy wishlist of stuff we should skip during purging of course content
  3895. $options = (array)$options;
  3896. $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
  3897. $coursecontext = context_course::instance($courseid);
  3898. $fs = get_file_storage();
  3899. // Delete course completion information, this has to be done before grades and enrols
  3900. $cc = new completion_info($course);
  3901. $cc->clear_criteria();
  3902. if ($showfeedback) {
  3903. echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
  3904. }
  3905. // Remove all data from gradebook - this needs to be done before course modules
  3906. // because while deleting this information, the system may need to reference
  3907. // the course modules that own the grades.
  3908. remove_course_grades($courseid, $showfeedback);
  3909. remove_grade_letters($coursecontext, $showfeedback);
  3910. // Delete course blocks in any all child contexts,
  3911. // they may depend on modules so delete them first
  3912. $childcontexts = $coursecontext->get_child_contexts(); // returns all subcontexts since 2.2
  3913. foreach ($childcontexts as $childcontext) {
  3914. blocks_delete_all_for_context($childcontext->id);
  3915. }
  3916. unset($childcontexts);
  3917. blocks_delete_all_for_context($coursecontext->id);
  3918. if ($showfeedback) {
  3919. echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
  3920. }
  3921. // Delete every instance of every module,
  3922. // this has to be done before deleting of course level stuff
  3923. $locations = get_plugin_list('mod');
  3924. foreach ($locations as $modname=>$moddir) {
  3925. if ($modname === 'NEWMODULE') {
  3926. continue;
  3927. }
  3928. if ($module = $DB->get_record('modules', array('name'=>$modname))) {
  3929. include_once("$moddir/lib.php"); // Shows php warning only if plugin defective
  3930. $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
  3931. $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
  3932. if ($instances = $DB->get_records($modname, array('course'=>$course->id))) {
  3933. foreach ($instances as $instance) {
  3934. if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
  3935. /// Delete activity context questions and question categories
  3936. question_delete_activity($cm, $showfeedback);
  3937. }
  3938. if (function_exists($moddelete)) {
  3939. // This purges all module data in related tables, extra user prefs, settings, etc.
  3940. $moddelete($instance->id);
  3941. } else {
  3942. // NOTE: we should not allow installation of modules with missing delete support!
  3943. debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
  3944. $DB->delete_records($modname, array('id'=>$instance->id));
  3945. }
  3946. if ($cm) {
  3947. // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition
  3948. context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
  3949. $DB->delete_records('course_modules', array('id'=>$cm->id));
  3950. }
  3951. }
  3952. }
  3953. if (function_exists($moddeletecourse)) {
  3954. // Execute ptional course cleanup callback
  3955. $moddeletecourse($course, $showfeedback);
  3956. }
  3957. if ($instances and $showfeedback) {
  3958. echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
  3959. }
  3960. } else {
  3961. // Ooops, this module is not properly installed, force-delete it in the next block
  3962. }
  3963. }
  3964. // We have tried to delete everything the nice way - now let's force-delete any remaining module data
  3965. // Remove all data from availability and completion tables that is associated
  3966. // with course-modules belonging to this course. Note this is done even if the
  3967. // features are not enabled now, in case they were enabled previously.
  3968. $DB->delete_records_select('course_modules_completion',
  3969. 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
  3970. array($courseid));
  3971. $DB->delete_records_select('course_modules_availability',
  3972. 'coursemoduleid IN (SELECT id from {course_modules} WHERE course=?)',
  3973. array($courseid));
  3974. // Remove course-module data.
  3975. $cms = $DB->get_records('course_modules', array('course'=>$course->id));
  3976. foreach ($cms as $cm) {
  3977. if ($module = $DB->get_record('modules', array('id'=>$cm->module))) {
  3978. try {
  3979. $DB->delete_records($module->name, array('id'=>$cm->instance));
  3980. } catch (Exception $e) {
  3981. // Ignore weird or missing table problems
  3982. }
  3983. }
  3984. context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
  3985. $DB->delete_records('course_modules', array('id'=>$cm->id));
  3986. }
  3987. if ($showfeedback) {
  3988. echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
  3989. }
  3990. // Cleanup the rest of plugins
  3991. $cleanuplugintypes = array('report', 'coursereport', 'format');
  3992. foreach ($cleanuplugintypes as $type) {
  3993. $plugins = get_plugin_list_with_function($type, 'delete_course', 'lib.php');
  3994. foreach ($plugins as $plugin=>$pluginfunction) {
  3995. $pluginfunction($course->id, $showfeedback);
  3996. }
  3997. if ($showfeedback) {
  3998. echo $OUTPUT->notification($strdeleted.get_string('type_'.$type.'_plural', 'plugin'), 'notifysuccess');
  3999. }
  4000. }
  4001. // Delete questions and question categories
  4002. question_delete_course($course, $showfeedback);
  4003. if ($showfeedback) {
  4004. echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
  4005. }
  4006. // Make sure there are no subcontexts left - all valid blocks and modules should be already gone
  4007. $childcontexts = $coursecontext->get_child_contexts(); // returns all subcontexts since 2.2
  4008. foreach ($childcontexts as $childcontext) {
  4009. $childcontext->delete();
  4010. }
  4011. unset($childcontexts);
  4012. // Remove all roles and enrolments by default
  4013. if (empty($options['keep_roles_and_enrolments'])) {
  4014. // this hack is used in restore when deleting contents of existing course
  4015. role_unassign_all(array('contextid'=>$coursecontext->id, 'component'=>''), true);
  4016. enrol_course_delete($course);
  4017. if ($showfeedback) {
  4018. echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
  4019. }
  4020. }
  4021. // Delete any groups, removing members and grouping/course links first.
  4022. if (empty($options['keep_groups_and_groupings'])) {
  4023. groups_delete_groupings($course->id, $showfeedback);
  4024. groups_delete_groups($course->id, $showfeedback);
  4025. }
  4026. // filters be gone!
  4027. filter_delete_all_for_context($coursecontext->id);
  4028. // die comments!
  4029. comment::delete_comments($coursecontext->id);
  4030. // ratings are history too
  4031. $delopt = new stdclass();
  4032. $delopt->contextid = $coursecontext->id;
  4033. $rm = new rating_manager();
  4034. $rm->delete_ratings($delopt);
  4035. // Delete course tags
  4036. coursetag_delete_course_tags($course->id, $showfeedback);
  4037. // Delete calendar events
  4038. $DB->delete_records('event', array('courseid'=>$course->id));
  4039. $fs->delete_area_files($coursecontext->id, 'calendar');
  4040. // Delete all related records in other core tables that may have a courseid
  4041. // This array stores the tables that need to be cleared, as
  4042. // table_name => column_name that contains the course id.
  4043. $tablestoclear = array(
  4044. 'log' => 'course', // Course logs (NOTE: this might be changed in the future)
  4045. 'backup_courses' => 'courseid', // Scheduled backup stuff
  4046. 'user_lastaccess' => 'courseid', // User access info
  4047. );
  4048. foreach ($tablestoclear as $table => $col) {
  4049. $DB->delete_records($table, array($col=>$course->id));
  4050. }
  4051. // delete all course backup files
  4052. $fs->delete_area_files($coursecontext->id, 'backup');
  4053. // cleanup course record - remove links to deleted stuff
  4054. $oldcourse = new stdClass();
  4055. $oldcourse->id = $course->id;
  4056. $oldcourse->summary = '';
  4057. $oldcourse->modinfo = NULL;
  4058. $oldcourse->legacyfiles = 0;
  4059. $oldcourse->enablecompletion = 0;
  4060. if (!empty($options['keep_groups_and_groupings'])) {
  4061. $oldcourse->defaultgroupingid = 0;
  4062. }
  4063. $DB->update_record('course', $oldcourse);
  4064. // Delete course sections and availability options.
  4065. $DB->delete_records_select('course_sections_availability',
  4066. 'coursesectionid IN (SELECT id from {course_sections} WHERE course=?)',
  4067. array($course->id));
  4068. $DB->delete_records('course_sections', array('course'=>$course->id));
  4069. // delete legacy, section and any other course files
  4070. $fs->delete_area_files($coursecontext->id, 'course'); // files from summary and section
  4071. // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
  4072. if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
  4073. // Easy, do not delete the context itself...
  4074. $coursecontext->delete_content();
  4075. } else {
  4076. // Hack alert!!!!
  4077. // We can not drop all context stuff because it would bork enrolments and roles,
  4078. // there might be also files used by enrol plugins...
  4079. }
  4080. // Delete legacy files - just in case some files are still left there after conversion to new file api,
  4081. // also some non-standard unsupported plugins may try to store something there
  4082. fulldelete($CFG->dataroot.'/'.$course->id);
  4083. // Finally trigger the event
  4084. $course->context = $coursecontext; // you can not access context in cron event later after course is deleted
  4085. $course->options = $options; // not empty if we used any crazy hack
  4086. events_trigger('course_content_removed', $course);
  4087. return true;
  4088. }
  4089. /**
  4090. * Change dates in module - used from course reset.
  4091. *
  4092. * @global object
  4093. * @global object
  4094. * @param string $modname forum, assignment, etc
  4095. * @param array $fields array of date fields from mod table
  4096. * @param int $timeshift time difference
  4097. * @param int $courseid
  4098. * @return bool success
  4099. */
  4100. function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
  4101. global $CFG, $DB;
  4102. include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
  4103. $return = true;
  4104. foreach ($fields as $field) {
  4105. $updatesql = "UPDATE {".$modname."}
  4106. SET $field = $field + ?
  4107. WHERE course=? AND $field<>0 AND $field<>0";
  4108. $return = $DB->execute($updatesql, array($timeshift, $courseid)) && $return;
  4109. }
  4110. $refreshfunction = $modname.'_refresh_events';
  4111. if (function_exists($refreshfunction)) {
  4112. $refreshfunction($courseid);
  4113. }
  4114. return $return;
  4115. }
  4116. /**
  4117. * This function will empty a course of user data.
  4118. * It will retain the activities and the structure of the course.
  4119. *
  4120. * @param object $data an object containing all the settings including courseid (without magic quotes)
  4121. * @return array status array of array component, item, error
  4122. */
  4123. function reset_course_userdata($data) {
  4124. global $CFG, $USER, $DB;
  4125. require_once($CFG->libdir.'/gradelib.php');
  4126. require_once($CFG->libdir.'/completionlib.php');
  4127. require_once($CFG->dirroot.'/group/lib.php');
  4128. $data->courseid = $data->id;
  4129. $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
  4130. // calculate the time shift of dates
  4131. if (!empty($data->reset_start_date)) {
  4132. // time part of course startdate should be zero
  4133. $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
  4134. } else {
  4135. $data->timeshift = 0;
  4136. }
  4137. // result array: component, item, error
  4138. $status = array();
  4139. // start the resetting
  4140. $componentstr = get_string('general');
  4141. // move the course start time
  4142. if (!empty($data->reset_start_date) and $data->timeshift) {
  4143. // change course start data
  4144. $DB->set_field('course', 'startdate', $data->reset_start_date, array('id'=>$data->courseid));
  4145. // update all course and group events - do not move activity events
  4146. $updatesql = "UPDATE {event}
  4147. SET timestart = timestart + ?
  4148. WHERE courseid=? AND instance=0";
  4149. $DB->execute($updatesql, array($data->timeshift, $data->courseid));
  4150. $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
  4151. }
  4152. if (!empty($data->reset_logs)) {
  4153. $DB->delete_records('log', array('course'=>$data->courseid));
  4154. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelogs'), 'error'=>false);
  4155. }
  4156. if (!empty($data->reset_events)) {
  4157. $DB->delete_records('event', array('courseid'=>$data->courseid));
  4158. $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteevents', 'calendar'), 'error'=>false);
  4159. }
  4160. if (!empty($data->reset_notes)) {
  4161. require_once($CFG->dirroot.'/notes/lib.php');
  4162. note_delete_all($data->courseid);
  4163. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotes', 'notes'), 'error'=>false);
  4164. }
  4165. if (!empty($data->delete_blog_associations)) {
  4166. require_once($CFG->dirroot.'/blog/lib.php');
  4167. blog_remove_associations_for_course($data->courseid);
  4168. $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteblogassociations', 'blog'), 'error'=>false);
  4169. }
  4170. if (!empty($data->reset_course_completion)) {
  4171. // Delete course completion information
  4172. $course = $DB->get_record('course', array('id'=>$data->courseid));
  4173. $cc = new completion_info($course);
  4174. $cc->delete_course_completion_data();
  4175. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecoursecompletiondata', 'completion'), 'error'=>false);
  4176. }
  4177. $componentstr = get_string('roles');
  4178. if (!empty($data->reset_roles_overrides)) {
  4179. $children = get_child_contexts($context);
  4180. foreach ($children as $child) {
  4181. $DB->delete_records('role_capabilities', array('contextid'=>$child->id));
  4182. }
  4183. $DB->delete_records('role_capabilities', array('contextid'=>$context->id));
  4184. //force refresh for logged in users
  4185. mark_context_dirty($context->path);
  4186. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecourseoverrides', 'role'), 'error'=>false);
  4187. }
  4188. if (!empty($data->reset_roles_local)) {
  4189. $children = get_child_contexts($context);
  4190. foreach ($children as $child) {
  4191. role_unassign_all(array('contextid'=>$child->id));
  4192. }
  4193. //force refresh for logged in users
  4194. mark_context_dirty($context->path);
  4195. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelocalroles', 'role'), 'error'=>false);
  4196. }
  4197. // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
  4198. $data->unenrolled = array();
  4199. if (!empty($data->unenrol_users)) {
  4200. $plugins = enrol_get_plugins(true);
  4201. $instances = enrol_get_instances($data->courseid, true);
  4202. foreach ($instances as $key=>$instance) {
  4203. if (!isset($plugins[$instance->enrol])) {
  4204. unset($instances[$key]);
  4205. continue;
  4206. }
  4207. }
  4208. foreach($data->unenrol_users as $withroleid) {
  4209. if ($withroleid) {
  4210. $sql = "SELECT ue.*
  4211. FROM {user_enrolments} ue
  4212. JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
  4213. JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
  4214. JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
  4215. $params = array('courseid'=>$data->courseid, 'roleid'=>$withroleid, 'courselevel'=>CONTEXT_COURSE);
  4216. } else {
  4217. // without any role assigned at course context
  4218. $sql = "SELECT ue.*
  4219. FROM {user_enrolments} ue
  4220. JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
  4221. JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
  4222. LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
  4223. WHERE ra.id IS NULL";
  4224. $params = array('courseid'=>$data->courseid, 'courselevel'=>CONTEXT_COURSE);
  4225. }
  4226. $rs = $DB->get_recordset_sql($sql, $params);
  4227. foreach ($rs as $ue) {
  4228. if (!isset($instances[$ue->enrolid])) {
  4229. continue;
  4230. }
  4231. $instance = $instances[$ue->enrolid];
  4232. $plugin = $plugins[$instance->enrol];
  4233. if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
  4234. continue;
  4235. }
  4236. $plugin->unenrol_user($instance, $ue->userid);
  4237. $data->unenrolled[$ue->userid] = $ue->userid;
  4238. }
  4239. $rs->close();
  4240. }
  4241. }
  4242. if (!empty($data->unenrolled)) {
  4243. $status[] = array('component'=>$componentstr, 'item'=>get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')', 'error'=>false);
  4244. }
  4245. $componentstr = get_string('groups');
  4246. // remove all group members
  4247. if (!empty($data->reset_groups_members)) {
  4248. groups_delete_group_members($data->courseid);
  4249. $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupsmembers', 'group'), 'error'=>false);
  4250. }
  4251. // remove all groups
  4252. if (!empty($data->reset_groups_remove)) {
  4253. groups_delete_groups($data->courseid, false);
  4254. $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroups', 'group'), 'error'=>false);
  4255. }
  4256. // remove all grouping members
  4257. if (!empty($data->reset_groupings_members)) {
  4258. groups_delete_groupings_groups($data->courseid, false);
  4259. $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupingsmembers', 'group'), 'error'=>false);
  4260. }
  4261. // remove all groupings
  4262. if (!empty($data->reset_groupings_remove)) {
  4263. groups_delete_groupings($data->courseid, false);
  4264. $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroupings', 'group'), 'error'=>false);
  4265. }
  4266. // Look in every instance of every module for data to delete
  4267. $unsupported_mods = array();
  4268. if ($allmods = $DB->get_records('modules') ) {
  4269. foreach ($allmods as $mod) {
  4270. $modname = $mod->name;
  4271. if (!$DB->count_records($modname, array('course'=>$data->courseid))) {
  4272. continue; // skip mods with no instances
  4273. }
  4274. $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
  4275. $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data
  4276. if (file_exists($modfile)) {
  4277. include_once($modfile);
  4278. if (function_exists($moddeleteuserdata)) {
  4279. $modstatus = $moddeleteuserdata($data);
  4280. if (is_array($modstatus)) {
  4281. $status = array_merge($status, $modstatus);
  4282. } else {
  4283. debugging('Module '.$modname.' returned incorrect staus - must be an array!');
  4284. }
  4285. } else {
  4286. $unsupported_mods[] = $mod;
  4287. }
  4288. } else {
  4289. debugging('Missing lib.php in '.$modname.' module!');
  4290. }
  4291. }
  4292. }
  4293. // mention unsupported mods
  4294. if (!empty($unsupported_mods)) {
  4295. foreach($unsupported_mods as $mod) {
  4296. $status[] = array('component'=>get_string('modulenameplural', $mod->name), 'item'=>'', 'error'=>get_string('resetnotimplemented'));
  4297. }
  4298. }
  4299. $componentstr = get_string('gradebook', 'grades');
  4300. // reset gradebook
  4301. if (!empty($data->reset_gradebook_items)) {
  4302. remove_course_grades($data->courseid, false);
  4303. grade_grab_course_grades($data->courseid);
  4304. grade_regrade_final_grades($data->courseid);
  4305. $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcourseitems', 'grades'), 'error'=>false);
  4306. } else if (!empty($data->reset_gradebook_grades)) {
  4307. grade_course_reset($data->courseid);
  4308. $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcoursegrades', 'grades'), 'error'=>false);
  4309. }
  4310. // reset comments
  4311. if (!empty($data->reset_comments)) {
  4312. require_once($CFG->dirroot.'/comment/lib.php');
  4313. comment::reset_course_page_comments($context);
  4314. }
  4315. return $status;
  4316. }
  4317. /**
  4318. * Generate an email processing address
  4319. *
  4320. * @param int $modid
  4321. * @param string $modargs
  4322. * @return string Returns email processing address
  4323. */
  4324. function generate_email_processing_address($modid,$modargs) {
  4325. global $CFG;
  4326. $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
  4327. return $header . substr(md5($header.get_site_identifier()),0,16).'@'.$CFG->maildomain;
  4328. }
  4329. /**
  4330. * ?
  4331. *
  4332. * @todo Finish documenting this function
  4333. *
  4334. * @global object
  4335. * @param string $modargs
  4336. * @param string $body Currently unused
  4337. */
  4338. function moodle_process_email($modargs,$body) {
  4339. global $DB;
  4340. // the first char should be an unencoded letter. We'll take this as an action
  4341. switch ($modargs{0}) {
  4342. case 'B': { // bounce
  4343. list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
  4344. if ($user = $DB->get_record("user", array('id'=>$userid), "id,email")) {
  4345. // check the half md5 of their email
  4346. $md5check = substr(md5($user->email),0,16);
  4347. if ($md5check == substr($modargs, -16)) {
  4348. set_bounce_count($user);
  4349. }
  4350. // else maybe they've already changed it?
  4351. }
  4352. }
  4353. break;
  4354. // maybe more later?
  4355. }
  4356. }
  4357. /// CORRESPONDENCE ////////////////////////////////////////////////
  4358. /**
  4359. * Get mailer instance, enable buffering, flush buffer or disable buffering.
  4360. *
  4361. * @global object
  4362. * @param string $action 'get', 'buffer', 'close' or 'flush'
  4363. * @return object|null mailer instance if 'get' used or nothing
  4364. */
  4365. function get_mailer($action='get') {
  4366. global $CFG;
  4367. static $mailer = null;
  4368. static $counter = 0;
  4369. if (!isset($CFG->smtpmaxbulk)) {
  4370. $CFG->smtpmaxbulk = 1;
  4371. }
  4372. if ($action == 'get') {
  4373. $prevkeepalive = false;
  4374. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  4375. if ($counter < $CFG->smtpmaxbulk and !$mailer->IsError()) {
  4376. $counter++;
  4377. // reset the mailer
  4378. $mailer->Priority = 3;
  4379. $mailer->CharSet = 'UTF-8'; // our default
  4380. $mailer->ContentType = "text/plain";
  4381. $mailer->Encoding = "8bit";
  4382. $mailer->From = "root@localhost";
  4383. $mailer->FromName = "Root User";
  4384. $mailer->Sender = "";
  4385. $mailer->Subject = "";
  4386. $mailer->Body = "";
  4387. $mailer->AltBody = "";
  4388. $mailer->ConfirmReadingTo = "";
  4389. $mailer->ClearAllRecipients();
  4390. $mailer->ClearReplyTos();
  4391. $mailer->ClearAttachments();
  4392. $mailer->ClearCustomHeaders();
  4393. return $mailer;
  4394. }
  4395. $prevkeepalive = $mailer->SMTPKeepAlive;
  4396. get_mailer('flush');
  4397. }
  4398. include_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
  4399. $mailer = new moodle_phpmailer();
  4400. $counter = 1;
  4401. $mailer->Version = 'Moodle '.$CFG->version; // mailer version
  4402. $mailer->PluginDir = $CFG->libdir.'/phpmailer/'; // plugin directory (eg smtp plugin)
  4403. $mailer->CharSet = 'UTF-8';
  4404. // some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis
  4405. if (isset($CFG->mailnewline) and $CFG->mailnewline == 'CRLF') {
  4406. $mailer->LE = "\r\n";
  4407. } else {
  4408. $mailer->LE = "\n";
  4409. }
  4410. if ($CFG->smtphosts == 'qmail') {
  4411. $mailer->IsQmail(); // use Qmail system
  4412. } else if (empty($CFG->smtphosts)) {
  4413. $mailer->IsMail(); // use PHP mail() = sendmail
  4414. } else {
  4415. $mailer->IsSMTP(); // use SMTP directly
  4416. if (!empty($CFG->debugsmtp)) {
  4417. $mailer->SMTPDebug = true;
  4418. }
  4419. $mailer->Host = $CFG->smtphosts; // specify main and backup servers
  4420. $mailer->SMTPSecure = $CFG->smtpsecure; // specify secure connection protocol
  4421. $mailer->SMTPKeepAlive = $prevkeepalive; // use previous keepalive
  4422. if ($CFG->smtpuser) { // Use SMTP authentication
  4423. $mailer->SMTPAuth = true;
  4424. $mailer->Username = $CFG->smtpuser;
  4425. $mailer->Password = $CFG->smtppass;
  4426. }
  4427. }
  4428. return $mailer;
  4429. }
  4430. $nothing = null;
  4431. // keep smtp session open after sending
  4432. if ($action == 'buffer') {
  4433. if (!empty($CFG->smtpmaxbulk)) {
  4434. get_mailer('flush');
  4435. $m = get_mailer();
  4436. if ($m->Mailer == 'smtp') {
  4437. $m->SMTPKeepAlive = true;
  4438. }
  4439. }
  4440. return $nothing;
  4441. }
  4442. // close smtp session, but continue buffering
  4443. if ($action == 'flush') {
  4444. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  4445. if (!empty($mailer->SMTPDebug)) {
  4446. echo '<pre>'."\n";
  4447. }
  4448. $mailer->SmtpClose();
  4449. if (!empty($mailer->SMTPDebug)) {
  4450. echo '</pre>';
  4451. }
  4452. }
  4453. return $nothing;
  4454. }
  4455. // close smtp session, do not buffer anymore
  4456. if ($action == 'close') {
  4457. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  4458. get_mailer('flush');
  4459. $mailer->SMTPKeepAlive = false;
  4460. }
  4461. $mailer = null; // better force new instance
  4462. return $nothing;
  4463. }
  4464. }
  4465. /**
  4466. * Send an email to a specified user
  4467. *
  4468. * @global object
  4469. * @global string
  4470. * @global string IdentityProvider(IDP) URL user hits to jump to mnet peer.
  4471. * @uses SITEID
  4472. * @param stdClass $user A {@link $USER} object
  4473. * @param stdClass $from A {@link $USER} object
  4474. * @param string $subject plain text subject line of the email
  4475. * @param string $messagetext plain text version of the message
  4476. * @param string $messagehtml complete html version of the message (optional)
  4477. * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
  4478. * @param string $attachname the name of the file (extension indicates MIME)
  4479. * @param bool $usetrueaddress determines whether $from email address should
  4480. * be sent out. Will be overruled by user profile setting for maildisplay
  4481. * @param string $replyto Email address to reply to
  4482. * @param string $replytoname Name of reply to recipient
  4483. * @param int $wordwrapwidth custom word wrap width, default 79
  4484. * @return bool Returns true if mail was sent OK and false if there was an error.
  4485. */
  4486. function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='', $wordwrapwidth=79) {
  4487. global $CFG;
  4488. if (empty($user) || empty($user->email)) {
  4489. $nulluser = 'User is null or has no email';
  4490. error_log($nulluser);
  4491. if (CLI_SCRIPT) {
  4492. mtrace('Error: lib/moodlelib.php email_to_user(): '.$nulluser);
  4493. }
  4494. return false;
  4495. }
  4496. if (!empty($user->deleted)) {
  4497. // do not mail deleted users
  4498. $userdeleted = 'User is deleted';
  4499. error_log($userdeleted);
  4500. if (CLI_SCRIPT) {
  4501. mtrace('Error: lib/moodlelib.php email_to_user(): '.$userdeleted);
  4502. }
  4503. return false;
  4504. }
  4505. if (!empty($CFG->noemailever)) {
  4506. // hidden setting for development sites, set in config.php if needed
  4507. $noemail = 'Not sending email due to noemailever config setting';
  4508. error_log($noemail);
  4509. if (CLI_SCRIPT) {
  4510. mtrace('Error: lib/moodlelib.php email_to_user(): '.$noemail);
  4511. }
  4512. return true;
  4513. }
  4514. if (!empty($CFG->divertallemailsto)) {
  4515. $subject = "[DIVERTED {$user->email}] $subject";
  4516. $user = clone($user);
  4517. $user->email = $CFG->divertallemailsto;
  4518. }
  4519. // skip mail to suspended users
  4520. if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
  4521. return true;
  4522. }
  4523. if (!validate_email($user->email)) {
  4524. // we can not send emails to invalid addresses - it might create security issue or confuse the mailer
  4525. $invalidemail = "User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.";
  4526. error_log($invalidemail);
  4527. if (CLI_SCRIPT) {
  4528. mtrace('Error: lib/moodlelib.php email_to_user(): '.$invalidemail);
  4529. }
  4530. return false;
  4531. }
  4532. if (over_bounce_threshold($user)) {
  4533. $bouncemsg = "User $user->id (".fullname($user).") is over bounce threshold! Not sending.";
  4534. error_log($bouncemsg);
  4535. if (CLI_SCRIPT) {
  4536. mtrace('Error: lib/moodlelib.php email_to_user(): '.$bouncemsg);
  4537. }
  4538. return false;
  4539. }
  4540. // If the user is a remote mnet user, parse the email text for URL to the
  4541. // wwwroot and modify the url to direct the user's browser to login at their
  4542. // home site (identity provider - idp) before hitting the link itself
  4543. if (is_mnet_remote_user($user)) {
  4544. require_once($CFG->dirroot.'/mnet/lib.php');
  4545. $jumpurl = mnet_get_idp_jump_url($user);
  4546. $callback = partial('mnet_sso_apply_indirection', $jumpurl);
  4547. $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
  4548. $callback,
  4549. $messagetext);
  4550. $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
  4551. $callback,
  4552. $messagehtml);
  4553. }
  4554. $mail = get_mailer();
  4555. if (!empty($mail->SMTPDebug)) {
  4556. echo '<pre>' . "\n";
  4557. }
  4558. $temprecipients = array();
  4559. $tempreplyto = array();
  4560. $supportuser = generate_email_supportuser();
  4561. // make up an email address for handling bounces
  4562. if (!empty($CFG->handlebounces)) {
  4563. $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
  4564. $mail->Sender = generate_email_processing_address(0,$modargs);
  4565. } else {
  4566. $mail->Sender = $supportuser->email;
  4567. }
  4568. if (is_string($from)) { // So we can pass whatever we want if there is need
  4569. $mail->From = $CFG->noreplyaddress;
  4570. $mail->FromName = $from;
  4571. } else if ($usetrueaddress and $from->maildisplay) {
  4572. $mail->From = $from->email;
  4573. $mail->FromName = fullname($from);
  4574. } else {
  4575. $mail->From = $CFG->noreplyaddress;
  4576. $mail->FromName = fullname($from);
  4577. if (empty($replyto)) {
  4578. $tempreplyto[] = array($CFG->noreplyaddress, get_string('noreplyname'));
  4579. }
  4580. }
  4581. if (!empty($replyto)) {
  4582. $tempreplyto[] = array($replyto, $replytoname);
  4583. }
  4584. $mail->Subject = substr($subject, 0, 900);
  4585. $temprecipients[] = array($user->email, fullname($user));
  4586. $mail->WordWrap = $wordwrapwidth; // set word wrap
  4587. if (!empty($from->customheaders)) { // Add custom headers
  4588. if (is_array($from->customheaders)) {
  4589. foreach ($from->customheaders as $customheader) {
  4590. $mail->AddCustomHeader($customheader);
  4591. }
  4592. } else {
  4593. $mail->AddCustomHeader($from->customheaders);
  4594. }
  4595. }
  4596. if (!empty($from->priority)) {
  4597. $mail->Priority = $from->priority;
  4598. }
  4599. if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
  4600. $mail->IsHTML(true);
  4601. $mail->Encoding = 'quoted-printable'; // Encoding to use
  4602. $mail->Body = $messagehtml;
  4603. $mail->AltBody = "\n$messagetext\n";
  4604. } else {
  4605. $mail->IsHTML(false);
  4606. $mail->Body = "\n$messagetext\n";
  4607. }
  4608. if ($attachment && $attachname) {
  4609. if (preg_match( "~\\.\\.~" ,$attachment )) { // Security check for ".." in dir path
  4610. $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
  4611. $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
  4612. } else {
  4613. require_once($CFG->libdir.'/filelib.php');
  4614. $mimetype = mimeinfo('type', $attachname);
  4615. $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
  4616. }
  4617. }
  4618. // Check if the email should be sent in an other charset then the default UTF-8
  4619. if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
  4620. // use the defined site mail charset or eventually the one preferred by the recipient
  4621. $charset = $CFG->sitemailcharset;
  4622. if (!empty($CFG->allowusermailcharset)) {
  4623. if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
  4624. $charset = $useremailcharset;
  4625. }
  4626. }
  4627. // convert all the necessary strings if the charset is supported
  4628. $charsets = get_list_of_charsets();
  4629. unset($charsets['UTF-8']);
  4630. if (in_array($charset, $charsets)) {
  4631. $mail->CharSet = $charset;
  4632. $mail->FromName = textlib::convert($mail->FromName, 'utf-8', strtolower($charset));
  4633. $mail->Subject = textlib::convert($mail->Subject, 'utf-8', strtolower($charset));
  4634. $mail->Body = textlib::convert($mail->Body, 'utf-8', strtolower($charset));
  4635. $mail->AltBody = textlib::convert($mail->AltBody, 'utf-8', strtolower($charset));
  4636. foreach ($temprecipients as $key => $values) {
  4637. $temprecipients[$key][1] = textlib::convert($values[1], 'utf-8', strtolower($charset));
  4638. }
  4639. foreach ($tempreplyto as $key => $values) {
  4640. $tempreplyto[$key][1] = textlib::convert($values[1], 'utf-8', strtolower($charset));
  4641. }
  4642. }
  4643. }
  4644. foreach ($temprecipients as $values) {
  4645. $mail->AddAddress($values[0], $values[1]);
  4646. }
  4647. foreach ($tempreplyto as $values) {
  4648. $mail->AddReplyTo($values[0], $values[1]);
  4649. }
  4650. if ($mail->Send()) {
  4651. set_send_count($user);
  4652. $mail->IsSMTP(); // use SMTP directly
  4653. if (!empty($mail->SMTPDebug)) {
  4654. echo '</pre>';
  4655. }
  4656. return true;
  4657. } else {
  4658. add_to_log(SITEID, 'library', 'mailer', qualified_me(), 'ERROR: '. $mail->ErrorInfo);
  4659. if (CLI_SCRIPT) {
  4660. mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
  4661. }
  4662. if (!empty($mail->SMTPDebug)) {
  4663. echo '</pre>';
  4664. }
  4665. return false;
  4666. }
  4667. }
  4668. /**
  4669. * Generate a signoff for emails based on support settings
  4670. *
  4671. * @global object
  4672. * @return string
  4673. */
  4674. function generate_email_signoff() {
  4675. global $CFG;
  4676. $signoff = "\n";
  4677. if (!empty($CFG->supportname)) {
  4678. $signoff .= $CFG->supportname."\n";
  4679. }
  4680. if (!empty($CFG->supportemail)) {
  4681. $signoff .= $CFG->supportemail."\n";
  4682. }
  4683. if (!empty($CFG->supportpage)) {
  4684. $signoff .= $CFG->supportpage."\n";
  4685. }
  4686. return $signoff;
  4687. }
  4688. /**
  4689. * Generate a fake user for emails based on support settings
  4690. * @global object
  4691. * @return object user info
  4692. */
  4693. function generate_email_supportuser() {
  4694. global $CFG;
  4695. static $supportuser;
  4696. if (!empty($supportuser)) {
  4697. return $supportuser;
  4698. }
  4699. $supportuser = new stdClass();
  4700. $supportuser->email = $CFG->supportemail ? $CFG->supportemail : $CFG->noreplyaddress;
  4701. $supportuser->firstname = $CFG->supportname ? $CFG->supportname : get_string('noreplyname');
  4702. $supportuser->lastname = '';
  4703. $supportuser->maildisplay = true;
  4704. return $supportuser;
  4705. }
  4706. /**
  4707. * Sets specified user's password and send the new password to the user via email.
  4708. *
  4709. * @global object
  4710. * @global object
  4711. * @param user $user A {@link $USER} object
  4712. * @return boolean|string Returns "true" if mail was sent OK and "false" if there was an error
  4713. */
  4714. function setnew_password_and_mail($user) {
  4715. global $CFG, $DB;
  4716. // we try to send the mail in language the user understands,
  4717. // unfortunately the filter_string() does not support alternative langs yet
  4718. // so multilang will not work properly for site->fullname
  4719. $lang = empty($user->lang) ? $CFG->lang : $user->lang;
  4720. $site = get_site();
  4721. $supportuser = generate_email_supportuser();
  4722. $newpassword = generate_password();
  4723. $DB->set_field('user', 'password', hash_internal_user_password($newpassword), array('id'=>$user->id));
  4724. $a = new stdClass();
  4725. $a->firstname = fullname($user, true);
  4726. $a->sitename = format_string($site->fullname);
  4727. $a->username = $user->username;
  4728. $a->newpassword = $newpassword;
  4729. $a->link = $CFG->wwwroot .'/login/';
  4730. $a->signoff = generate_email_signoff();
  4731. $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
  4732. $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
  4733. //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
  4734. return email_to_user($user, $supportuser, $subject, $message);
  4735. }
  4736. /**
  4737. * Resets specified user's password and send the new password to the user via email.
  4738. *
  4739. * @param stdClass $user A {@link $USER} object
  4740. * @return bool Returns true if mail was sent OK and false if there was an error.
  4741. */
  4742. function reset_password_and_mail($user) {
  4743. global $CFG;
  4744. $site = get_site();
  4745. $supportuser = generate_email_supportuser();
  4746. $userauth = get_auth_plugin($user->auth);
  4747. if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
  4748. trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
  4749. return false;
  4750. }
  4751. $newpassword = generate_password();
  4752. if (!$userauth->user_update_password($user, $newpassword)) {
  4753. print_error("cannotsetpassword");
  4754. }
  4755. $a = new stdClass();
  4756. $a->firstname = $user->firstname;
  4757. $a->lastname = $user->lastname;
  4758. $a->sitename = format_string($site->fullname);
  4759. $a->username = $user->username;
  4760. $a->newpassword = $newpassword;
  4761. $a->link = $CFG->httpswwwroot .'/login/change_password.php';
  4762. $a->signoff = generate_email_signoff();
  4763. $message = get_string('newpasswordtext', '', $a);
  4764. $subject = format_string($site->fullname) .': '. get_string('changedpassword');
  4765. unset_user_preference('create_password', $user); // prevent cron from generating the password
  4766. //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
  4767. return email_to_user($user, $supportuser, $subject, $message);
  4768. }
  4769. /**
  4770. * Send email to specified user with confirmation text and activation link.
  4771. *
  4772. * @global object
  4773. * @param user $user A {@link $USER} object
  4774. * @return bool Returns true if mail was sent OK and false if there was an error.
  4775. */
  4776. function send_confirmation_email($user) {
  4777. global $CFG;
  4778. $site = get_site();
  4779. $supportuser = generate_email_supportuser();
  4780. $data = new stdClass();
  4781. $data->firstname = fullname($user);
  4782. $data->sitename = format_string($site->fullname);
  4783. $data->admin = generate_email_signoff();
  4784. $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
  4785. $username = urlencode($user->username);
  4786. $username = str_replace('.', '%2E', $username); // prevent problems with trailing dots
  4787. $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. $username;
  4788. $message = get_string('emailconfirmation', '', $data);
  4789. $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
  4790. $user->mailformat = 1; // Always send HTML version as well
  4791. //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
  4792. return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
  4793. }
  4794. /**
  4795. * send_password_change_confirmation_email.
  4796. *
  4797. * @global object
  4798. * @param user $user A {@link $USER} object
  4799. * @return bool Returns true if mail was sent OK and false if there was an error.
  4800. */
  4801. function send_password_change_confirmation_email($user) {
  4802. global $CFG;
  4803. $site = get_site();
  4804. $supportuser = generate_email_supportuser();
  4805. $data = new stdClass();
  4806. $data->firstname = $user->firstname;
  4807. $data->lastname = $user->lastname;
  4808. $data->sitename = format_string($site->fullname);
  4809. $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
  4810. $data->admin = generate_email_signoff();
  4811. $message = get_string('emailpasswordconfirmation', '', $data);
  4812. $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
  4813. //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
  4814. return email_to_user($user, $supportuser, $subject, $message);
  4815. }
  4816. /**
  4817. * send_password_change_info.
  4818. *
  4819. * @global object
  4820. * @param user $user A {@link $USER} object
  4821. * @return bool Returns true if mail was sent OK and false if there was an error.
  4822. */
  4823. function send_password_change_info($user) {
  4824. global $CFG;
  4825. $site = get_site();
  4826. $supportuser = generate_email_supportuser();
  4827. $systemcontext = get_context_instance(CONTEXT_SYSTEM);
  4828. $data = new stdClass();
  4829. $data->firstname = $user->firstname;
  4830. $data->lastname = $user->lastname;
  4831. $data->sitename = format_string($site->fullname);
  4832. $data->admin = generate_email_signoff();
  4833. $userauth = get_auth_plugin($user->auth);
  4834. if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
  4835. $message = get_string('emailpasswordchangeinfodisabled', '', $data);
  4836. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  4837. //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
  4838. return email_to_user($user, $supportuser, $subject, $message);
  4839. }
  4840. if ($userauth->can_change_password() and $userauth->change_password_url()) {
  4841. // we have some external url for password changing
  4842. $data->link .= $userauth->change_password_url();
  4843. } else {
  4844. //no way to change password, sorry
  4845. $data->link = '';
  4846. }
  4847. if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
  4848. $message = get_string('emailpasswordchangeinfo', '', $data);
  4849. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  4850. } else {
  4851. $message = get_string('emailpasswordchangeinfofail', '', $data);
  4852. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  4853. }
  4854. //directly email rather than using the messaging system to ensure its not routed to a popup or jabber
  4855. return email_to_user($user, $supportuser, $subject, $message);
  4856. }
  4857. /**
  4858. * Check that an email is allowed. It returns an error message if there
  4859. * was a problem.
  4860. *
  4861. * @global object
  4862. * @param string $email Content of email
  4863. * @return string|false
  4864. */
  4865. function email_is_not_allowed($email) {
  4866. global $CFG;
  4867. if (!empty($CFG->allowemailaddresses)) {
  4868. $allowed = explode(' ', $CFG->allowemailaddresses);
  4869. foreach ($allowed as $allowedpattern) {
  4870. $allowedpattern = trim($allowedpattern);
  4871. if (!$allowedpattern) {
  4872. continue;
  4873. }
  4874. if (strpos($allowedpattern, '.') === 0) {
  4875. if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
  4876. // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
  4877. return false;
  4878. }
  4879. } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
  4880. return false;
  4881. }
  4882. }
  4883. return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
  4884. } else if (!empty($CFG->denyemailaddresses)) {
  4885. $denied = explode(' ', $CFG->denyemailaddresses);
  4886. foreach ($denied as $deniedpattern) {
  4887. $deniedpattern = trim($deniedpattern);
  4888. if (!$deniedpattern) {
  4889. continue;
  4890. }
  4891. if (strpos($deniedpattern, '.') === 0) {
  4892. if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
  4893. // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
  4894. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  4895. }
  4896. } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
  4897. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  4898. }
  4899. }
  4900. }
  4901. return false;
  4902. }
  4903. /// FILE HANDLING /////////////////////////////////////////////
  4904. /**
  4905. * Returns local file storage instance
  4906. *
  4907. * @return file_storage
  4908. */
  4909. function get_file_storage() {
  4910. global $CFG;
  4911. static $fs = null;
  4912. if ($fs) {
  4913. return $fs;
  4914. }
  4915. require_once("$CFG->libdir/filelib.php");
  4916. if (isset($CFG->filedir)) {
  4917. $filedir = $CFG->filedir;
  4918. } else {
  4919. $filedir = $CFG->dataroot.'/filedir';
  4920. }
  4921. if (isset($CFG->trashdir)) {
  4922. $trashdirdir = $CFG->trashdir;
  4923. } else {
  4924. $trashdirdir = $CFG->dataroot.'/trashdir';
  4925. }
  4926. $fs = new file_storage($filedir, $trashdirdir, "$CFG->tempdir/filestorage", $CFG->directorypermissions, $CFG->filepermissions);
  4927. return $fs;
  4928. }
  4929. /**
  4930. * Returns local file storage instance
  4931. *
  4932. * @return file_browser
  4933. */
  4934. function get_file_browser() {
  4935. global $CFG;
  4936. static $fb = null;
  4937. if ($fb) {
  4938. return $fb;
  4939. }
  4940. require_once("$CFG->libdir/filelib.php");
  4941. $fb = new file_browser();
  4942. return $fb;
  4943. }
  4944. /**
  4945. * Returns file packer
  4946. *
  4947. * @param string $mimetype default application/zip
  4948. * @return file_packer
  4949. */
  4950. function get_file_packer($mimetype='application/zip') {
  4951. global $CFG;
  4952. static $fp = array();;
  4953. if (isset($fp[$mimetype])) {
  4954. return $fp[$mimetype];
  4955. }
  4956. switch ($mimetype) {
  4957. case 'application/zip':
  4958. case 'application/vnd.moodle.backup':
  4959. $classname = 'zip_packer';
  4960. break;
  4961. case 'application/x-tar':
  4962. // $classname = 'tar_packer';
  4963. // break;
  4964. default:
  4965. return false;
  4966. }
  4967. require_once("$CFG->libdir/filestorage/$classname.php");
  4968. $fp[$mimetype] = new $classname();
  4969. return $fp[$mimetype];
  4970. }
  4971. /**
  4972. * Returns current name of file on disk if it exists.
  4973. *
  4974. * @param string $newfile File to be verified
  4975. * @return string Current name of file on disk if true
  4976. */
  4977. function valid_uploaded_file($newfile) {
  4978. if (empty($newfile)) {
  4979. return '';
  4980. }
  4981. if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
  4982. return $newfile['tmp_name'];
  4983. } else {
  4984. return '';
  4985. }
  4986. }
  4987. /**
  4988. * Returns the maximum size for uploading files.
  4989. *
  4990. * There are seven possible upload limits:
  4991. * 1. in Apache using LimitRequestBody (no way of checking or changing this)
  4992. * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
  4993. * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
  4994. * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
  4995. * 5. by the Moodle admin in $CFG->maxbytes
  4996. * 6. by the teacher in the current course $course->maxbytes
  4997. * 7. by the teacher for the current module, eg $assignment->maxbytes
  4998. *
  4999. * These last two are passed to this function as arguments (in bytes).
  5000. * Anything defined as 0 is ignored.
  5001. * The smallest of all the non-zero numbers is returned.
  5002. *
  5003. * @todo Finish documenting this function
  5004. *
  5005. * @param int $sizebytes Set maximum size
  5006. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5007. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5008. * @return int The maximum size for uploading files.
  5009. */
  5010. function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
  5011. if (! $filesize = ini_get('upload_max_filesize')) {
  5012. $filesize = '5M';
  5013. }
  5014. $minimumsize = get_real_size($filesize);
  5015. if ($postsize = ini_get('post_max_size')) {
  5016. $postsize = get_real_size($postsize);
  5017. if ($postsize < $minimumsize) {
  5018. $minimumsize = $postsize;
  5019. }
  5020. }
  5021. if ($sitebytes and $sitebytes < $minimumsize) {
  5022. $minimumsize = $sitebytes;
  5023. }
  5024. if ($coursebytes and $coursebytes < $minimumsize) {
  5025. $minimumsize = $coursebytes;
  5026. }
  5027. if ($modulebytes and $modulebytes < $minimumsize) {
  5028. $minimumsize = $modulebytes;
  5029. }
  5030. return $minimumsize;
  5031. }
  5032. /**
  5033. * Returns the maximum size for uploading files for the current user
  5034. *
  5035. * This function takes in account @see:get_max_upload_file_size() the user's capabilities
  5036. *
  5037. * @param context $context The context in which to check user capabilities
  5038. * @param int $sizebytes Set maximum size
  5039. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5040. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5041. * @param stdClass The user
  5042. * @return int The maximum size for uploading files.
  5043. */
  5044. function get_user_max_upload_file_size($context, $sitebytes=0, $coursebytes=0, $modulebytes=0, $user=null) {
  5045. global $USER;
  5046. if (empty($user)) {
  5047. $user = $USER;
  5048. }
  5049. if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
  5050. return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
  5051. }
  5052. return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
  5053. }
  5054. /**
  5055. * Returns an array of possible sizes in local language
  5056. *
  5057. * Related to {@link get_max_upload_file_size()} - this function returns an
  5058. * array of possible sizes in an array, translated to the
  5059. * local language.
  5060. *
  5061. * @todo Finish documenting this function
  5062. *
  5063. * @global object
  5064. * @uses SORT_NUMERIC
  5065. * @param int $sizebytes Set maximum size
  5066. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  5067. * @param int $modulebytes Current module ->maxbytes (in bytes)
  5068. * @return array
  5069. */
  5070. function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
  5071. global $CFG;
  5072. if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
  5073. return array();
  5074. }
  5075. $filesize[intval($maxsize)] = display_size($maxsize);
  5076. $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
  5077. 5242880, 10485760, 20971520, 52428800, 104857600);
  5078. // Allow maxbytes to be selected if it falls outside the above boundaries
  5079. if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
  5080. // note: get_real_size() is used in order to prevent problems with invalid values
  5081. $sizelist[] = get_real_size($CFG->maxbytes);
  5082. }
  5083. foreach ($sizelist as $sizebytes) {
  5084. if ($sizebytes < $maxsize) {
  5085. $filesize[intval($sizebytes)] = display_size($sizebytes);
  5086. }
  5087. }
  5088. krsort($filesize, SORT_NUMERIC);
  5089. return $filesize;
  5090. }
  5091. /**
  5092. * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
  5093. *
  5094. * If excludefiles is defined, then that file/directory is ignored
  5095. * If getdirs is true, then (sub)directories are included in the output
  5096. * If getfiles is true, then files are included in the output
  5097. * (at least one of these must be true!)
  5098. *
  5099. * @todo Finish documenting this function. Add examples of $excludefile usage.
  5100. *
  5101. * @param string $rootdir A given root directory to start from
  5102. * @param string|array $excludefile If defined then the specified file/directory is ignored
  5103. * @param bool $descend If true then subdirectories are recursed as well
  5104. * @param bool $getdirs If true then (sub)directories are included in the output
  5105. * @param bool $getfiles If true then files are included in the output
  5106. * @return array An array with all the filenames in
  5107. * all subdirectories, relative to the given rootdir
  5108. */
  5109. function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
  5110. $dirs = array();
  5111. if (!$getdirs and !$getfiles) { // Nothing to show
  5112. return $dirs;
  5113. }
  5114. if (!is_dir($rootdir)) { // Must be a directory
  5115. return $dirs;
  5116. }
  5117. if (!$dir = opendir($rootdir)) { // Can't open it for some reason
  5118. return $dirs;
  5119. }
  5120. if (!is_array($excludefiles)) {
  5121. $excludefiles = array($excludefiles);
  5122. }
  5123. while (false !== ($file = readdir($dir))) {
  5124. $firstchar = substr($file, 0, 1);
  5125. if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
  5126. continue;
  5127. }
  5128. $fullfile = $rootdir .'/'. $file;
  5129. if (filetype($fullfile) == 'dir') {
  5130. if ($getdirs) {
  5131. $dirs[] = $file;
  5132. }
  5133. if ($descend) {
  5134. $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
  5135. foreach ($subdirs as $subdir) {
  5136. $dirs[] = $file .'/'. $subdir;
  5137. }
  5138. }
  5139. } else if ($getfiles) {
  5140. $dirs[] = $file;
  5141. }
  5142. }
  5143. closedir($dir);
  5144. asort($dirs);
  5145. return $dirs;
  5146. }
  5147. /**
  5148. * Adds up all the files in a directory and works out the size.
  5149. *
  5150. * @todo Finish documenting this function
  5151. *
  5152. * @param string $rootdir The directory to start from
  5153. * @param string $excludefile A file to exclude when summing directory size
  5154. * @return int The summed size of all files and subfiles within the root directory
  5155. */
  5156. function get_directory_size($rootdir, $excludefile='') {
  5157. global $CFG;
  5158. // do it this way if we can, it's much faster
  5159. if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
  5160. $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
  5161. $output = null;
  5162. $return = null;
  5163. exec($command,$output,$return);
  5164. if (is_array($output)) {
  5165. return get_real_size(intval($output[0]).'k'); // we told it to return k.
  5166. }
  5167. }
  5168. if (!is_dir($rootdir)) { // Must be a directory
  5169. return 0;
  5170. }
  5171. if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
  5172. return 0;
  5173. }
  5174. $size = 0;
  5175. while (false !== ($file = readdir($dir))) {
  5176. $firstchar = substr($file, 0, 1);
  5177. if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
  5178. continue;
  5179. }
  5180. $fullfile = $rootdir .'/'. $file;
  5181. if (filetype($fullfile) == 'dir') {
  5182. $size += get_directory_size($fullfile, $excludefile);
  5183. } else {
  5184. $size += filesize($fullfile);
  5185. }
  5186. }
  5187. closedir($dir);
  5188. return $size;
  5189. }
  5190. /**
  5191. * Converts bytes into display form
  5192. *
  5193. * @todo Finish documenting this function. Verify return type.
  5194. *
  5195. * @staticvar string $gb Localized string for size in gigabytes
  5196. * @staticvar string $mb Localized string for size in megabytes
  5197. * @staticvar string $kb Localized string for size in kilobytes
  5198. * @staticvar string $b Localized string for size in bytes
  5199. * @param int $size The size to convert to human readable form
  5200. * @return string
  5201. */
  5202. function display_size($size) {
  5203. static $gb, $mb, $kb, $b;
  5204. if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
  5205. return get_string('unlimited');
  5206. }
  5207. if (empty($gb)) {
  5208. $gb = get_string('sizegb');
  5209. $mb = get_string('sizemb');
  5210. $kb = get_string('sizekb');
  5211. $b = get_string('sizeb');
  5212. }
  5213. if ($size >= 1073741824) {
  5214. $size = round($size / 1073741824 * 10) / 10 . $gb;
  5215. } else if ($size >= 1048576) {
  5216. $size = round($size / 1048576 * 10) / 10 . $mb;
  5217. } else if ($size >= 1024) {
  5218. $size = round($size / 1024 * 10) / 10 . $kb;
  5219. } else {
  5220. $size = intval($size) .' '. $b; // file sizes over 2GB can not work in 32bit PHP anyway
  5221. }
  5222. return $size;
  5223. }
  5224. /**
  5225. * Cleans a given filename by removing suspicious or troublesome characters
  5226. * @see clean_param()
  5227. *
  5228. * @uses PARAM_FILE
  5229. * @param string $string file name
  5230. * @return string cleaned file name
  5231. */
  5232. function clean_filename($string) {
  5233. return clean_param($string, PARAM_FILE);
  5234. }
  5235. /// STRING TRANSLATION ////////////////////////////////////////
  5236. /**
  5237. * Returns the code for the current language
  5238. *
  5239. * @category string
  5240. * @return string
  5241. */
  5242. function current_language() {
  5243. global $CFG, $USER, $SESSION, $COURSE;
  5244. if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
  5245. $return = $COURSE->lang;
  5246. } else if (!empty($SESSION->lang)) { // Session language can override other settings
  5247. $return = $SESSION->lang;
  5248. } else if (!empty($USER->lang)) {
  5249. $return = $USER->lang;
  5250. } else if (isset($CFG->lang)) {
  5251. $return = $CFG->lang;
  5252. } else {
  5253. $return = 'en';
  5254. }
  5255. $return = str_replace('_utf8', '', $return); // Just in case this slipped in from somewhere by accident
  5256. return $return;
  5257. }
  5258. /**
  5259. * Returns parent language of current active language if defined
  5260. *
  5261. * @category string
  5262. * @uses COURSE
  5263. * @uses SESSION
  5264. * @param string $lang null means current language
  5265. * @return string
  5266. */
  5267. function get_parent_language($lang=null) {
  5268. global $COURSE, $SESSION;
  5269. //let's hack around the current language
  5270. if (!empty($lang)) {
  5271. $old_course_lang = empty($COURSE->lang) ? '' : $COURSE->lang;
  5272. $old_session_lang = empty($SESSION->lang) ? '' : $SESSION->lang;
  5273. $COURSE->lang = '';
  5274. $SESSION->lang = $lang;
  5275. }
  5276. $parentlang = get_string('parentlanguage', 'langconfig');
  5277. if ($parentlang === 'en') {
  5278. $parentlang = '';
  5279. }
  5280. //let's hack around the current language
  5281. if (!empty($lang)) {
  5282. $COURSE->lang = $old_course_lang;
  5283. $SESSION->lang = $old_session_lang;
  5284. }
  5285. return $parentlang;
  5286. }
  5287. /**
  5288. * Returns current string_manager instance.
  5289. *
  5290. * The param $forcereload is needed for CLI installer only where the string_manager instance
  5291. * must be replaced during the install.php script life time.
  5292. *
  5293. * @category string
  5294. * @param bool $forcereload shall the singleton be released and new instance created instead?
  5295. * @return string_manager
  5296. */
  5297. function get_string_manager($forcereload=false) {
  5298. global $CFG;
  5299. static $singleton = null;
  5300. if ($forcereload) {
  5301. $singleton = null;
  5302. }
  5303. if ($singleton === null) {
  5304. if (empty($CFG->early_install_lang)) {
  5305. if (empty($CFG->langcacheroot)) {
  5306. $langcacheroot = $CFG->cachedir . '/lang';
  5307. } else {
  5308. $langcacheroot = $CFG->langcacheroot;
  5309. }
  5310. if (empty($CFG->langlist)) {
  5311. $translist = array();
  5312. } else {
  5313. $translist = explode(',', $CFG->langlist);
  5314. }
  5315. if (empty($CFG->langmenucachefile)) {
  5316. $langmenucache = $CFG->cachedir . '/languages';
  5317. } else {
  5318. $langmenucache = $CFG->langmenucachefile;
  5319. }
  5320. $singleton = new core_string_manager($CFG->langotherroot, $CFG->langlocalroot, $langcacheroot,
  5321. !empty($CFG->langstringcache), $translist, $langmenucache);
  5322. } else {
  5323. $singleton = new install_string_manager();
  5324. }
  5325. }
  5326. return $singleton;
  5327. }
  5328. /**
  5329. * Interface for string manager
  5330. *
  5331. * Interface describing class which is responsible for getting
  5332. * of localised strings from language packs.
  5333. *
  5334. * @package core
  5335. * @copyright 2010 Petr Skoda (http://skodak.org)
  5336. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  5337. */
  5338. interface string_manager {
  5339. /**
  5340. * Get String returns a requested string
  5341. *
  5342. * @param string $identifier The identifier of the string to search for
  5343. * @param string $component The module the string is associated with
  5344. * @param string|object|array $a An object, string or number that can be used
  5345. * within translation strings
  5346. * @param string $lang moodle translation language, NULL means use current
  5347. * @return string The String !
  5348. */
  5349. public function get_string($identifier, $component = '', $a = NULL, $lang = NULL);
  5350. /**
  5351. * Does the string actually exist?
  5352. *
  5353. * get_string() is throwing debug warnings, sometimes we do not want them
  5354. * or we want to display better explanation of the problem.
  5355. *
  5356. * Use with care!
  5357. *
  5358. * @param string $identifier The identifier of the string to search for
  5359. * @param string $component The module the string is associated with
  5360. * @return boot true if exists
  5361. */
  5362. public function string_exists($identifier, $component);
  5363. /**
  5364. * Returns a localised list of all country names, sorted by country keys.
  5365. * @param bool $returnall return all or just enabled
  5366. * @param string $lang moodle translation language, NULL means use current
  5367. * @return array two-letter country code => translated name.
  5368. */
  5369. public function get_list_of_countries($returnall = false, $lang = NULL);
  5370. /**
  5371. * Returns a localised list of languages, sorted by code keys.
  5372. *
  5373. * @param string $lang moodle translation language, NULL means use current
  5374. * @param string $standard language list standard
  5375. * iso6392: three-letter language code (ISO 639-2/T) => translated name.
  5376. * @return array language code => translated name
  5377. */
  5378. public function get_list_of_languages($lang = NULL, $standard = 'iso6392');
  5379. /**
  5380. * Checks if the translation exists for the language
  5381. *
  5382. * @param string $lang moodle translation language code
  5383. * @param bool $includeall include also disabled translations
  5384. * @return bool true if exists
  5385. */
  5386. public function translation_exists($lang, $includeall = true);
  5387. /**
  5388. * Returns localised list of installed translations
  5389. * @param bool $returnall return all or just enabled
  5390. * @return array moodle translation code => localised translation name
  5391. */
  5392. public function get_list_of_translations($returnall = false);
  5393. /**
  5394. * Returns localised list of currencies.
  5395. *
  5396. * @param string $lang moodle translation language, NULL means use current
  5397. * @return array currency code => localised currency name
  5398. */
  5399. public function get_list_of_currencies($lang = NULL);
  5400. /**
  5401. * Load all strings for one component
  5402. * @param string $component The module the string is associated with
  5403. * @param string $lang
  5404. * @param bool $disablecache Do not use caches, force fetching the strings from sources
  5405. * @param bool $disablelocal Do not use customized strings in xx_local language packs
  5406. * @return array of all string for given component and lang
  5407. */
  5408. public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false);
  5409. /**
  5410. * Invalidates all caches, should the implementation use any
  5411. */
  5412. public function reset_caches();
  5413. }
  5414. /**
  5415. * Standard string_manager implementation
  5416. *
  5417. * Implements string_manager with getting and printing localised strings
  5418. *
  5419. * @package core
  5420. * @category string
  5421. * @copyright 2010 Petr Skoda (http://skodak.org)
  5422. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  5423. */
  5424. class core_string_manager implements string_manager {
  5425. /** @var string location of all packs except 'en' */
  5426. protected $otherroot;
  5427. /** @var string location of all lang pack local modifications */
  5428. protected $localroot;
  5429. /** @var string location of on-disk cache of merged strings */
  5430. protected $cacheroot;
  5431. /** @var array lang string cache - it will be optimised more later */
  5432. protected $cache = array();
  5433. /** @var int get_string() counter */
  5434. protected $countgetstring = 0;
  5435. /** @var int in-memory cache hits counter */
  5436. protected $countmemcache = 0;
  5437. /** @var int on-disk cache hits counter */
  5438. protected $countdiskcache = 0;
  5439. /** @var bool use disk cache */
  5440. protected $usediskcache;
  5441. /** @var array limit list of translations */
  5442. protected $translist;
  5443. /** @var string location of a file that caches the list of available translations */
  5444. protected $menucache;
  5445. /**
  5446. * Create new instance of string manager
  5447. *
  5448. * @param string $otherroot location of downlaoded lang packs - usually $CFG->dataroot/lang
  5449. * @param string $localroot usually the same as $otherroot
  5450. * @param string $cacheroot usually lang dir in cache folder
  5451. * @param bool $usediskcache use disk cache
  5452. * @param array $translist limit list of visible translations
  5453. * @param string $menucache the location of a file that caches the list of available translations
  5454. */
  5455. public function __construct($otherroot, $localroot, $cacheroot, $usediskcache, $translist, $menucache) {
  5456. $this->otherroot = $otherroot;
  5457. $this->localroot = $localroot;
  5458. $this->cacheroot = $cacheroot;
  5459. $this->usediskcache = $usediskcache;
  5460. $this->translist = $translist;
  5461. $this->menucache = $menucache;
  5462. }
  5463. /**
  5464. * Returns dependencies of current language, en is not included.
  5465. *
  5466. * @param string $lang
  5467. * @return array all parents, the lang itself is last
  5468. */
  5469. public function get_language_dependencies($lang) {
  5470. if ($lang === 'en') {
  5471. return array();
  5472. }
  5473. if (!file_exists("$this->otherroot/$lang/langconfig.php")) {
  5474. return array();
  5475. }
  5476. $string = array();
  5477. include("$this->otherroot/$lang/langconfig.php");
  5478. if (empty($string['parentlanguage'])) {
  5479. return array($lang);
  5480. } else {
  5481. $parentlang = $string['parentlanguage'];
  5482. unset($string);
  5483. return array_merge($this->get_language_dependencies($parentlang), array($lang));
  5484. }
  5485. }
  5486. /**
  5487. * Load all strings for one component
  5488. *
  5489. * @param string $component The module the string is associated with
  5490. * @param string $lang
  5491. * @param bool $disablecache Do not use caches, force fetching the strings from sources
  5492. * @param bool $disablelocal Do not use customized strings in xx_local language packs
  5493. * @return array of all string for given component and lang
  5494. */
  5495. public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false) {
  5496. global $CFG;
  5497. list($plugintype, $pluginname) = normalize_component($component);
  5498. if ($plugintype == 'core' and is_null($pluginname)) {
  5499. $component = 'core';
  5500. } else {
  5501. $component = $plugintype . '_' . $pluginname;
  5502. }
  5503. if (!$disablecache and !$disablelocal) {
  5504. // try in-memory cache first
  5505. if (isset($this->cache[$lang][$component])) {
  5506. $this->countmemcache++;
  5507. return $this->cache[$lang][$component];
  5508. }
  5509. // try on-disk cache then
  5510. if ($this->usediskcache and file_exists($this->cacheroot . "/$lang/$component.php")) {
  5511. $this->countdiskcache++;
  5512. include($this->cacheroot . "/$lang/$component.php");
  5513. return $this->cache[$lang][$component];
  5514. }
  5515. }
  5516. // no cache found - let us merge all possible sources of the strings
  5517. if ($plugintype === 'core') {
  5518. $file = $pluginname;
  5519. if ($file === null) {
  5520. $file = 'moodle';
  5521. }
  5522. $string = array();
  5523. // first load english pack
  5524. if (!file_exists("$CFG->dirroot/lang/en/$file.php")) {
  5525. return array();
  5526. }
  5527. include("$CFG->dirroot/lang/en/$file.php");
  5528. $originalkeys = array_keys($string);
  5529. $originalkeys = array_flip($originalkeys);
  5530. // and then corresponding local if present and allowed
  5531. if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
  5532. include("$this->localroot/en_local/$file.php");
  5533. }
  5534. // now loop through all langs in correct order
  5535. $deps = $this->get_language_dependencies($lang);
  5536. foreach ($deps as $dep) {
  5537. // the main lang string location
  5538. if (file_exists("$this->otherroot/$dep/$file.php")) {
  5539. include("$this->otherroot/$dep/$file.php");
  5540. }
  5541. if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
  5542. include("$this->localroot/{$dep}_local/$file.php");
  5543. }
  5544. }
  5545. } else {
  5546. if (!$location = get_plugin_directory($plugintype, $pluginname) or !is_dir($location)) {
  5547. return array();
  5548. }
  5549. if ($plugintype === 'mod') {
  5550. // bloody mod hack
  5551. $file = $pluginname;
  5552. } else {
  5553. $file = $plugintype . '_' . $pluginname;
  5554. }
  5555. $string = array();
  5556. // first load English pack
  5557. if (!file_exists("$location/lang/en/$file.php")) {
  5558. //English pack does not exist, so do not try to load anything else
  5559. return array();
  5560. }
  5561. include("$location/lang/en/$file.php");
  5562. $originalkeys = array_keys($string);
  5563. $originalkeys = array_flip($originalkeys);
  5564. // and then corresponding local english if present
  5565. if (!$disablelocal and file_exists("$this->localroot/en_local/$file.php")) {
  5566. include("$this->localroot/en_local/$file.php");
  5567. }
  5568. // now loop through all langs in correct order
  5569. $deps = $this->get_language_dependencies($lang);
  5570. foreach ($deps as $dep) {
  5571. // legacy location - used by contrib only
  5572. if (file_exists("$location/lang/$dep/$file.php")) {
  5573. include("$location/lang/$dep/$file.php");
  5574. }
  5575. // the main lang string location
  5576. if (file_exists("$this->otherroot/$dep/$file.php")) {
  5577. include("$this->otherroot/$dep/$file.php");
  5578. }
  5579. // local customisations
  5580. if (!$disablelocal and file_exists("$this->localroot/{$dep}_local/$file.php")) {
  5581. include("$this->localroot/{$dep}_local/$file.php");
  5582. }
  5583. }
  5584. }
  5585. // we do not want any extra strings from other languages - everything must be in en lang pack
  5586. $string = array_intersect_key($string, $originalkeys);
  5587. if (!$disablelocal) {
  5588. // now we have a list of strings from all possible sources. put it into both in-memory and on-disk
  5589. // caches so we do not need to do all this merging and dependencies resolving again
  5590. $this->cache[$lang][$component] = $string;
  5591. if ($this->usediskcache) {
  5592. check_dir_exists("$this->cacheroot/$lang");
  5593. file_put_contents("$this->cacheroot/$lang/$component.php", "<?php \$this->cache['$lang']['$component'] = ".var_export($string, true).";");
  5594. }
  5595. }
  5596. return $string;
  5597. }
  5598. /**
  5599. * Does the string actually exist?
  5600. *
  5601. * get_string() is throwing debug warnings, sometimes we do not want them
  5602. * or we want to display better explanation of the problem.
  5603. * Note: Use with care!
  5604. *
  5605. * @param string $identifier The identifier of the string to search for
  5606. * @param string $component The module the string is associated with
  5607. * @return boot true if exists
  5608. */
  5609. public function string_exists($identifier, $component) {
  5610. $identifier = clean_param($identifier, PARAM_STRINGID);
  5611. if (empty($identifier)) {
  5612. return false;
  5613. }
  5614. $lang = current_language();
  5615. $string = $this->load_component_strings($component, $lang);
  5616. return isset($string[$identifier]);
  5617. }
  5618. /**
  5619. * Get String returns a requested string
  5620. *
  5621. * @param string $identifier The identifier of the string to search for
  5622. * @param string $component The module the string is associated with
  5623. * @param string|object|array $a An object, string or number that can be used
  5624. * within translation strings
  5625. * @param string $lang moodle translation language, NULL means use current
  5626. * @return string The String !
  5627. */
  5628. public function get_string($identifier, $component = '', $a = NULL, $lang = NULL) {
  5629. $this->countgetstring++;
  5630. // there are very many uses of these time formating strings without the 'langconfig' component,
  5631. // it would not be reasonable to expect that all of them would be converted during 2.0 migration
  5632. static $langconfigstrs = array(
  5633. 'strftimedate' => 1,
  5634. 'strftimedatefullshort' => 1,
  5635. 'strftimedateshort' => 1,
  5636. 'strftimedatetime' => 1,
  5637. 'strftimedatetimeshort' => 1,
  5638. 'strftimedaydate' => 1,
  5639. 'strftimedaydatetime' => 1,
  5640. 'strftimedayshort' => 1,
  5641. 'strftimedaytime' => 1,
  5642. 'strftimemonthyear' => 1,
  5643. 'strftimerecent' => 1,
  5644. 'strftimerecentfull' => 1,
  5645. 'strftimetime' => 1);
  5646. if (empty($component)) {
  5647. if (isset($langconfigstrs[$identifier])) {
  5648. $component = 'langconfig';
  5649. } else {
  5650. $component = 'moodle';
  5651. }
  5652. }
  5653. if ($lang === NULL) {
  5654. $lang = current_language();
  5655. }
  5656. $string = $this->load_component_strings($component, $lang);
  5657. if (!isset($string[$identifier])) {
  5658. if ($component === 'pix' or $component === 'core_pix') {
  5659. // this component contains only alt tags for emoticons,
  5660. // not all of them are supposed to be defined
  5661. return '';
  5662. }
  5663. if ($identifier === 'parentlanguage' and ($component === 'langconfig' or $component === 'core_langconfig')) {
  5664. // parentlanguage is a special string, undefined means use English if not defined
  5665. return 'en';
  5666. }
  5667. if ($this->usediskcache) {
  5668. // maybe the on-disk cache is dirty - let the last attempt be to find the string in original sources,
  5669. // do NOT write the results to disk cache because it may end up in race conditions see MDL-31904
  5670. $this->usediskcache = false;
  5671. $string = $this->load_component_strings($component, $lang, true);
  5672. $this->usediskcache = true;
  5673. }
  5674. if (!isset($string[$identifier])) {
  5675. // the string is still missing - should be fixed by developer
  5676. list($plugintype, $pluginname) = normalize_component($component);
  5677. if ($plugintype == 'core') {
  5678. $file = "lang/en/{$component}.php";
  5679. } else if ($plugintype == 'mod') {
  5680. $file = "mod/{$pluginname}/lang/en/{$pluginname}.php";
  5681. } else {
  5682. $path = get_plugin_directory($plugintype, $pluginname);
  5683. $file = "{$path}/lang/en/{$plugintype}_{$pluginname}.php";
  5684. }
  5685. debugging("Invalid get_string() identifier: '{$identifier}' or component '{$component}'. " .
  5686. "Perhaps you are missing \$string['{$identifier}'] = ''; in {$file}?", DEBUG_DEVELOPER);
  5687. return "[[$identifier]]";
  5688. }
  5689. }
  5690. $string = $string[$identifier];
  5691. if ($a !== NULL) {
  5692. // Process array's and objects (except lang_strings)
  5693. if (is_array($a) or (is_object($a) && !($a instanceof lang_string))) {
  5694. $a = (array)$a;
  5695. $search = array();
  5696. $replace = array();
  5697. foreach ($a as $key=>$value) {
  5698. if (is_int($key)) {
  5699. // we do not support numeric keys - sorry!
  5700. continue;
  5701. }
  5702. if (is_array($value) or (is_object($value) && !($value instanceof lang_string))) {
  5703. // we support just string or lang_string as value
  5704. continue;
  5705. }
  5706. $search[] = '{$a->'.$key.'}';
  5707. $replace[] = (string)$value;
  5708. }
  5709. if ($search) {
  5710. $string = str_replace($search, $replace, $string);
  5711. }
  5712. } else {
  5713. $string = str_replace('{$a}', (string)$a, $string);
  5714. }
  5715. }
  5716. return $string;
  5717. }
  5718. /**
  5719. * Returns information about the string_manager performance
  5720. *
  5721. * @return array
  5722. */
  5723. public function get_performance_summary() {
  5724. return array(array(
  5725. 'langcountgetstring' => $this->countgetstring,
  5726. 'langcountmemcache' => $this->countmemcache,
  5727. 'langcountdiskcache' => $this->countdiskcache,
  5728. ), array(
  5729. 'langcountgetstring' => 'get_string calls',
  5730. 'langcountmemcache' => 'strings mem cache hits',
  5731. 'langcountdiskcache' => 'strings disk cache hits',
  5732. ));
  5733. }
  5734. /**
  5735. * Returns a localised list of all country names, sorted by localised name.
  5736. *
  5737. * @param bool $returnall return all or just enabled
  5738. * @param string $lang moodle translation language, NULL means use current
  5739. * @return array two-letter country code => translated name.
  5740. */
  5741. public function get_list_of_countries($returnall = false, $lang = NULL) {
  5742. global $CFG;
  5743. if ($lang === NULL) {
  5744. $lang = current_language();
  5745. }
  5746. $countries = $this->load_component_strings('core_countries', $lang);
  5747. collatorlib::asort($countries);
  5748. if (!$returnall and !empty($CFG->allcountrycodes)) {
  5749. $enabled = explode(',', $CFG->allcountrycodes);
  5750. $return = array();
  5751. foreach ($enabled as $c) {
  5752. if (isset($countries[$c])) {
  5753. $return[$c] = $countries[$c];
  5754. }
  5755. }
  5756. return $return;
  5757. }
  5758. return $countries;
  5759. }
  5760. /**
  5761. * Returns a localised list of languages, sorted by code keys.
  5762. *
  5763. * @param string $lang moodle translation language, NULL means use current
  5764. * @param string $standard language list standard
  5765. * - iso6392: three-letter language code (ISO 639-2/T) => translated name
  5766. * - iso6391: two-letter langauge code (ISO 639-1) => translated name
  5767. * @return array language code => translated name
  5768. */
  5769. public function get_list_of_languages($lang = NULL, $standard = 'iso6391') {
  5770. if ($lang === NULL) {
  5771. $lang = current_language();
  5772. }
  5773. if ($standard === 'iso6392') {
  5774. $langs = $this->load_component_strings('core_iso6392', $lang);
  5775. ksort($langs);
  5776. return $langs;
  5777. } else if ($standard === 'iso6391') {
  5778. $langs2 = $this->load_component_strings('core_iso6392', $lang);
  5779. static $mapping = array('aar' => 'aa', 'abk' => 'ab', 'afr' => 'af', 'aka' => 'ak', 'sqi' => 'sq', 'amh' => 'am', 'ara' => 'ar', 'arg' => 'an', 'hye' => 'hy',
  5780. 'asm' => 'as', 'ava' => 'av', 'ave' => 'ae', 'aym' => 'ay', 'aze' => 'az', 'bak' => 'ba', 'bam' => 'bm', 'eus' => 'eu', 'bel' => 'be', 'ben' => 'bn', 'bih' => 'bh',
  5781. 'bis' => 'bi', 'bos' => 'bs', 'bre' => 'br', 'bul' => 'bg', 'mya' => 'my', 'cat' => 'ca', 'cha' => 'ch', 'che' => 'ce', 'zho' => 'zh', 'chu' => 'cu', 'chv' => 'cv',
  5782. 'cor' => 'kw', 'cos' => 'co', 'cre' => 'cr', 'ces' => 'cs', 'dan' => 'da', 'div' => 'dv', 'nld' => 'nl', 'dzo' => 'dz', 'eng' => 'en', 'epo' => 'eo', 'est' => 'et',
  5783. 'ewe' => 'ee', 'fao' => 'fo', 'fij' => 'fj', 'fin' => 'fi', 'fra' => 'fr', 'fry' => 'fy', 'ful' => 'ff', 'kat' => 'ka', 'deu' => 'de', 'gla' => 'gd', 'gle' => 'ga',
  5784. 'glg' => 'gl', 'glv' => 'gv', 'ell' => 'el', 'grn' => 'gn', 'guj' => 'gu', 'hat' => 'ht', 'hau' => 'ha', 'heb' => 'he', 'her' => 'hz', 'hin' => 'hi', 'hmo' => 'ho',
  5785. 'hrv' => 'hr', 'hun' => 'hu', 'ibo' => 'ig', 'isl' => 'is', 'ido' => 'io', 'iii' => 'ii', 'iku' => 'iu', 'ile' => 'ie', 'ina' => 'ia', 'ind' => 'id', 'ipk' => 'ik',
  5786. 'ita' => 'it', 'jav' => 'jv', 'jpn' => 'ja', 'kal' => 'kl', 'kan' => 'kn', 'kas' => 'ks', 'kau' => 'kr', 'kaz' => 'kk', 'khm' => 'km', 'kik' => 'ki', 'kin' => 'rw',
  5787. 'kir' => 'ky', 'kom' => 'kv', 'kon' => 'kg', 'kor' => 'ko', 'kua' => 'kj', 'kur' => 'ku', 'lao' => 'lo', 'lat' => 'la', 'lav' => 'lv', 'lim' => 'li', 'lin' => 'ln',
  5788. 'lit' => 'lt', 'ltz' => 'lb', 'lub' => 'lu', 'lug' => 'lg', 'mkd' => 'mk', 'mah' => 'mh', 'mal' => 'ml', 'mri' => 'mi', 'mar' => 'mr', 'msa' => 'ms', 'mlg' => 'mg',
  5789. 'mlt' => 'mt', 'mon' => 'mn', 'nau' => 'na', 'nav' => 'nv', 'nbl' => 'nr', 'nde' => 'nd', 'ndo' => 'ng', 'nep' => 'ne', 'nno' => 'nn', 'nob' => 'nb', 'nor' => 'no',
  5790. 'nya' => 'ny', 'oci' => 'oc', 'oji' => 'oj', 'ori' => 'or', 'orm' => 'om', 'oss' => 'os', 'pan' => 'pa', 'fas' => 'fa', 'pli' => 'pi', 'pol' => 'pl', 'por' => 'pt',
  5791. 'pus' => 'ps', 'que' => 'qu', 'roh' => 'rm', 'ron' => 'ro', 'run' => 'rn', 'rus' => 'ru', 'sag' => 'sg', 'san' => 'sa', 'sin' => 'si', 'slk' => 'sk', 'slv' => 'sl',
  5792. 'sme' => 'se', 'smo' => 'sm', 'sna' => 'sn', 'snd' => 'sd', 'som' => 'so', 'sot' => 'st', 'spa' => 'es', 'srd' => 'sc', 'srp' => 'sr', 'ssw' => 'ss', 'sun' => 'su',
  5793. 'swa' => 'sw', 'swe' => 'sv', 'tah' => 'ty', 'tam' => 'ta', 'tat' => 'tt', 'tel' => 'te', 'tgk' => 'tg', 'tgl' => 'tl', 'tha' => 'th', 'bod' => 'bo', 'tir' => 'ti',
  5794. 'ton' => 'to', 'tsn' => 'tn', 'tso' => 'ts', 'tuk' => 'tk', 'tur' => 'tr', 'twi' => 'tw', 'uig' => 'ug', 'ukr' => 'uk', 'urd' => 'ur', 'uzb' => 'uz', 'ven' => 've',
  5795. 'vie' => 'vi', 'vol' => 'vo', 'cym' => 'cy', 'wln' => 'wa', 'wol' => 'wo', 'xho' => 'xh', 'yid' => 'yi', 'yor' => 'yo', 'zha' => 'za', 'zul' => 'zu');
  5796. $langs1 = array();
  5797. foreach ($mapping as $c2=>$c1) {
  5798. $langs1[$c1] = $langs2[$c2];
  5799. }
  5800. ksort($langs1);
  5801. return $langs1;
  5802. } else {
  5803. debugging('Unsupported $standard parameter in get_list_of_languages() method: '.$standard);
  5804. }
  5805. return array();
  5806. }
  5807. /**
  5808. * Checks if the translation exists for the language
  5809. *
  5810. * @param string $lang moodle translation language code
  5811. * @param bool $includeall include also disabled translations
  5812. * @return bool true if exists
  5813. */
  5814. public function translation_exists($lang, $includeall = true) {
  5815. if (strpos($lang, '_local') !== false) {
  5816. // _local packs are not real translations
  5817. return false;
  5818. }
  5819. if (!$includeall and !empty($this->translist)) {
  5820. if (!in_array($lang, $this->translist)) {
  5821. return false;
  5822. }
  5823. }
  5824. if ($lang === 'en') {
  5825. // part of distribution
  5826. return true;
  5827. }
  5828. return file_exists("$this->otherroot/$lang/langconfig.php");
  5829. }
  5830. /**
  5831. * Returns localised list of installed translations
  5832. *
  5833. * @param bool $returnall return all or just enabled
  5834. * @return array moodle translation code => localised translation name
  5835. */
  5836. public function get_list_of_translations($returnall = false) {
  5837. global $CFG;
  5838. $languages = array();
  5839. if (!empty($CFG->langcache) and is_readable($this->menucache)) {
  5840. // try to re-use the cached list of all available languages
  5841. $cachedlist = json_decode(file_get_contents($this->menucache), true);
  5842. if (is_array($cachedlist) and !empty($cachedlist)) {
  5843. // the cache file is restored correctly
  5844. if (!$returnall and !empty($this->translist)) {
  5845. // return just enabled translations
  5846. foreach ($cachedlist as $langcode => $langname) {
  5847. if (in_array($langcode, $this->translist)) {
  5848. $languages[$langcode] = $langname;
  5849. }
  5850. }
  5851. return $languages;
  5852. } else {
  5853. // return all translations
  5854. return $cachedlist;
  5855. }
  5856. }
  5857. }
  5858. // the cached list of languages is not available, let us populate the list
  5859. if (!$returnall and !empty($this->translist)) {
  5860. // return only some translations
  5861. foreach ($this->translist as $lang) {
  5862. $lang = trim($lang); //Just trim spaces to be a bit more permissive
  5863. if (strstr($lang, '_local') !== false) {
  5864. continue;
  5865. }
  5866. if (strstr($lang, '_utf8') !== false) {
  5867. continue;
  5868. }
  5869. if ($lang !== 'en' and !file_exists("$this->otherroot/$lang/langconfig.php")) {
  5870. // some broken or missing lang - can not switch to it anyway
  5871. continue;
  5872. }
  5873. $string = $this->load_component_strings('langconfig', $lang);
  5874. if (!empty($string['thislanguage'])) {
  5875. $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
  5876. }
  5877. unset($string);
  5878. }
  5879. } else {
  5880. // return all languages available in system
  5881. $langdirs = get_list_of_plugins('', '', $this->otherroot);
  5882. $langdirs = array_merge($langdirs, array("$CFG->dirroot/lang/en"=>'en'));
  5883. // Sort all
  5884. // Loop through all langs and get info
  5885. foreach ($langdirs as $lang) {
  5886. if (strstr($lang, '_local') !== false) {
  5887. continue;
  5888. }
  5889. if (strstr($lang, '_utf8') !== false) {
  5890. continue;
  5891. }
  5892. $string = $this->load_component_strings('langconfig', $lang);
  5893. if (!empty($string['thislanguage'])) {
  5894. $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
  5895. }
  5896. unset($string);
  5897. }
  5898. if (!empty($CFG->langcache) and !empty($this->menucache)) {
  5899. // cache the list so that it can be used next time
  5900. collatorlib::asort($languages);
  5901. check_dir_exists(dirname($this->menucache), true, true);
  5902. file_put_contents($this->menucache, json_encode($languages));
  5903. }
  5904. }
  5905. collatorlib::asort($languages);
  5906. return $languages;
  5907. }
  5908. /**
  5909. * Returns localised list of currencies.
  5910. *
  5911. * @param string $lang moodle translation language, NULL means use current
  5912. * @return array currency code => localised currency name
  5913. */
  5914. public function get_list_of_currencies($lang = NULL) {
  5915. if ($lang === NULL) {
  5916. $lang = current_language();
  5917. }
  5918. $currencies = $this->load_component_strings('core_currencies', $lang);
  5919. asort($currencies);
  5920. return $currencies;
  5921. }
  5922. /**
  5923. * Clears both in-memory and on-disk caches
  5924. */
  5925. public function reset_caches() {
  5926. global $CFG;
  5927. require_once("$CFG->libdir/filelib.php");
  5928. // clear the on-disk disk with aggregated string files
  5929. fulldelete($this->cacheroot);
  5930. // clear the in-memory cache of loaded strings
  5931. $this->cache = array();
  5932. // clear the cache containing the list of available translations
  5933. // and re-populate it again
  5934. fulldelete($this->menucache);
  5935. $this->get_list_of_translations(true);
  5936. }
  5937. }
  5938. /**
  5939. * Fetches minimum strings for installation
  5940. *
  5941. * Minimalistic string fetching implementation
  5942. * that is used in installer before we fetch the wanted
  5943. * language pack from moodle.org lang download site.
  5944. *
  5945. * @package core
  5946. * @copyright 2010 Petr Skoda (http://skodak.org)
  5947. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  5948. */
  5949. class install_string_manager implements string_manager {
  5950. /** @var string location of pre-install packs for all langs */
  5951. protected $installroot;
  5952. /**
  5953. * Crate new instance of install string manager
  5954. */
  5955. public function __construct() {
  5956. global $CFG;
  5957. $this->installroot = "$CFG->dirroot/install/lang";
  5958. }
  5959. /**
  5960. * Load all strings for one component
  5961. * @param string $component The module the string is associated with
  5962. * @param string $lang
  5963. * @param bool $disablecache Do not use caches, force fetching the strings from sources
  5964. * @param bool $disablelocal Do not use customized strings in xx_local language packs
  5965. * @return array of all string for given component and lang
  5966. */
  5967. public function load_component_strings($component, $lang, $disablecache=false, $disablelocal=false) {
  5968. // not needed in installer
  5969. return array();
  5970. }
  5971. /**
  5972. * Does the string actually exist?
  5973. *
  5974. * get_string() is throwing debug warnings, sometimes we do not want them
  5975. * or we want to display better explanation of the problem.
  5976. *
  5977. * Use with care!
  5978. *
  5979. * @param string $identifier The identifier of the string to search for
  5980. * @param string $component The module the string is associated with
  5981. * @return boot true if exists
  5982. */
  5983. public function string_exists($identifier, $component) {
  5984. $identifier = clean_param($identifier, PARAM_STRINGID);
  5985. if (empty($identifier)) {
  5986. return false;
  5987. }
  5988. // simple old style hack ;)
  5989. $str = get_string($identifier, $component);
  5990. return (strpos($str, '[[') === false);
  5991. }
  5992. /**
  5993. * Get String returns a requested string
  5994. *
  5995. * @param string $identifier The identifier of the string to search for
  5996. * @param string $component The module the string is associated with
  5997. * @param string|object|array $a An object, string or number that can be used
  5998. * within translation strings
  5999. * @param string $lang moodle translation language, NULL means use current
  6000. * @return string The String !
  6001. */
  6002. public function get_string($identifier, $component = '', $a = NULL, $lang = NULL) {
  6003. if (!$component) {
  6004. $component = 'moodle';
  6005. }
  6006. if ($lang === NULL) {
  6007. $lang = current_language();
  6008. }
  6009. //get parent lang
  6010. $parent = '';
  6011. if ($lang !== 'en' and $identifier !== 'parentlanguage' and $component !== 'langconfig') {
  6012. if (file_exists("$this->installroot/$lang/langconfig.php")) {
  6013. $string = array();
  6014. include("$this->installroot/$lang/langconfig.php");
  6015. if (isset($string['parentlanguage'])) {
  6016. $parent = $string['parentlanguage'];
  6017. }
  6018. unset($string);
  6019. }
  6020. }
  6021. // include en string first
  6022. if (!file_exists("$this->installroot/en/$component.php")) {
  6023. return "[[$identifier]]";
  6024. }
  6025. $string = array();
  6026. include("$this->installroot/en/$component.php");
  6027. // now override en with parent if defined
  6028. if ($parent and $parent !== 'en' and file_exists("$this->installroot/$parent/$component.php")) {
  6029. include("$this->installroot/$parent/$component.php");
  6030. }
  6031. // finally override with requested language
  6032. if ($lang !== 'en' and file_exists("$this->installroot/$lang/$component.php")) {
  6033. include("$this->installroot/$lang/$component.php");
  6034. }
  6035. if (!isset($string[$identifier])) {
  6036. return "[[$identifier]]";
  6037. }
  6038. $string = $string[$identifier];
  6039. if ($a !== NULL) {
  6040. if (is_object($a) or is_array($a)) {
  6041. $a = (array)$a;
  6042. $search = array();
  6043. $replace = array();
  6044. foreach ($a as $key=>$value) {
  6045. if (is_int($key)) {
  6046. // we do not support numeric keys - sorry!
  6047. continue;
  6048. }
  6049. $search[] = '{$a->'.$key.'}';
  6050. $replace[] = (string)$value;
  6051. }
  6052. if ($search) {
  6053. $string = str_replace($search, $replace, $string);
  6054. }
  6055. } else {
  6056. $string = str_replace('{$a}', (string)$a, $string);
  6057. }
  6058. }
  6059. return $string;
  6060. }
  6061. /**
  6062. * Returns a localised list of all country names, sorted by country keys.
  6063. *
  6064. * @param bool $returnall return all or just enabled
  6065. * @param string $lang moodle translation language, NULL means use current
  6066. * @return array two-letter country code => translated name.
  6067. */
  6068. public function get_list_of_countries($returnall = false, $lang = NULL) {
  6069. //not used in installer
  6070. return array();
  6071. }
  6072. /**
  6073. * Returns a localised list of languages, sorted by code keys.
  6074. *
  6075. * @param string $lang moodle translation language, NULL means use current
  6076. * @param string $standard language list standard
  6077. * iso6392: three-letter language code (ISO 639-2/T) => translated name.
  6078. * @return array language code => translated name
  6079. */
  6080. public function get_list_of_languages($lang = NULL, $standard = 'iso6392') {
  6081. //not used in installer
  6082. return array();
  6083. }
  6084. /**
  6085. * Checks if the translation exists for the language
  6086. *
  6087. * @param string $lang moodle translation language code
  6088. * @param bool $includeall include also disabled translations
  6089. * @return bool true if exists
  6090. */
  6091. public function translation_exists($lang, $includeall = true) {
  6092. return file_exists($this->installroot.'/'.$lang.'/langconfig.php');
  6093. }
  6094. /**
  6095. * Returns localised list of installed translations
  6096. * @param bool $returnall return all or just enabled
  6097. * @return array moodle translation code => localised translation name
  6098. */
  6099. public function get_list_of_translations($returnall = false) {
  6100. // return all is ignored here - we need to know all langs in installer
  6101. $languages = array();
  6102. // Get raw list of lang directories
  6103. $langdirs = get_list_of_plugins('install/lang');
  6104. asort($langdirs);
  6105. // Get some info from each lang
  6106. foreach ($langdirs as $lang) {
  6107. if (file_exists($this->installroot.'/'.$lang.'/langconfig.php')) {
  6108. $string = array();
  6109. include($this->installroot.'/'.$lang.'/langconfig.php');
  6110. if (!empty($string['thislanguage'])) {
  6111. $languages[$lang] = $string['thislanguage'].' ('.$lang.')';
  6112. }
  6113. }
  6114. }
  6115. // Return array
  6116. return $languages;
  6117. }
  6118. /**
  6119. * Returns localised list of currencies.
  6120. *
  6121. * @param string $lang moodle translation language, NULL means use current
  6122. * @return array currency code => localised currency name
  6123. */
  6124. public function get_list_of_currencies($lang = NULL) {
  6125. // not used in installer
  6126. return array();
  6127. }
  6128. /**
  6129. * This implementation does not use any caches
  6130. */
  6131. public function reset_caches() {}
  6132. }
  6133. /**
  6134. * Returns a localized string.
  6135. *
  6136. * Returns the translated string specified by $identifier as
  6137. * for $module. Uses the same format files as STphp.
  6138. * $a is an object, string or number that can be used
  6139. * within translation strings
  6140. *
  6141. * eg 'hello {$a->firstname} {$a->lastname}'
  6142. * or 'hello {$a}'
  6143. *
  6144. * If you would like to directly echo the localized string use
  6145. * the function {@link print_string()}
  6146. *
  6147. * Example usage of this function involves finding the string you would
  6148. * like a local equivalent of and using its identifier and module information
  6149. * to retrieve it.<br/>
  6150. * If you open moodle/lang/en/moodle.php and look near line 278
  6151. * you will find a string to prompt a user for their word for 'course'
  6152. * <code>
  6153. * $string['course'] = 'Course';
  6154. * </code>
  6155. * So if you want to display the string 'Course'
  6156. * in any language that supports it on your site
  6157. * you just need to use the identifier 'course'
  6158. * <code>
  6159. * $mystring = '<strong>'. get_string('course') .'</strong>';
  6160. * or
  6161. * </code>
  6162. * If the string you want is in another file you'd take a slightly
  6163. * different approach. Looking in moodle/lang/en/calendar.php you find
  6164. * around line 75:
  6165. * <code>
  6166. * $string['typecourse'] = 'Course event';
  6167. * </code>
  6168. * If you want to display the string "Course event" in any language
  6169. * supported you would use the identifier 'typecourse' and the module 'calendar'
  6170. * (because it is in the file calendar.php):
  6171. * <code>
  6172. * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
  6173. * </code>
  6174. *
  6175. * As a last resort, should the identifier fail to map to a string
  6176. * the returned string will be [[ $identifier ]]
  6177. *
  6178. * In Moodle 2.3 there is a new argument to this function $lazyload.
  6179. * Setting $lazyload to true causes get_string to return a lang_string object
  6180. * rather than the string itself. The fetching of the string is then put off until
  6181. * the string object is first used. The object can be used by calling it's out
  6182. * method or by casting the object to a string, either directly e.g.
  6183. * (string)$stringobject
  6184. * or indirectly by using the string within another string or echoing it out e.g.
  6185. * echo $stringobject
  6186. * return "<p>{$stringobject}</p>";
  6187. * It is worth noting that using $lazyload and attempting to use the string as an
  6188. * array key will cause a fatal error as objects cannot be used as array keys.
  6189. * But you should never do that anyway!
  6190. * For more information {@see lang_string}
  6191. *
  6192. * @category string
  6193. * @param string $identifier The key identifier for the localized string
  6194. * @param string $component The module where the key identifier is stored,
  6195. * usually expressed as the filename in the language pack without the
  6196. * .php on the end but can also be written as mod/forum or grade/export/xls.
  6197. * If none is specified then moodle.php is used.
  6198. * @param string|object|array $a An object, string or number that can be used
  6199. * within translation strings
  6200. * @param bool $lazyload If set to true a string object is returned instead of
  6201. * the string itself. The string then isn't calculated until it is first used.
  6202. * @return string The localized string.
  6203. */
  6204. function get_string($identifier, $component = '', $a = NULL, $lazyload = false) {
  6205. global $CFG;
  6206. // If the lazy load argument has been supplied return a lang_string object
  6207. // instead.
  6208. // We need to make sure it is true (and a bool) as you will see below there
  6209. // used to be a forth argument at one point.
  6210. if ($lazyload === true) {
  6211. return new lang_string($identifier, $component, $a);
  6212. }
  6213. $identifier = clean_param($identifier, PARAM_STRINGID);
  6214. if (empty($identifier)) {
  6215. throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please fix your get_string() call and string definition');
  6216. }
  6217. // There is now a forth argument again, this time it is a boolean however so
  6218. // we can still check for the old extralocations parameter.
  6219. if (!is_bool($lazyload) && !empty($lazyload)) {
  6220. debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
  6221. }
  6222. if (strpos($component, '/') !== false) {
  6223. debugging('The module name you passed to get_string is the deprecated format ' .
  6224. 'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
  6225. $componentpath = explode('/', $component);
  6226. switch ($componentpath[0]) {
  6227. case 'mod':
  6228. $component = $componentpath[1];
  6229. break;
  6230. case 'blocks':
  6231. case 'block':
  6232. $component = 'block_'.$componentpath[1];
  6233. break;
  6234. case 'enrol':
  6235. $component = 'enrol_'.$componentpath[1];
  6236. break;
  6237. case 'format':
  6238. $component = 'format_'.$componentpath[1];
  6239. break;
  6240. case 'grade':
  6241. $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
  6242. break;
  6243. }
  6244. }
  6245. $result = get_string_manager()->get_string($identifier, $component, $a);
  6246. // Debugging feature lets you display string identifier and component
  6247. if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
  6248. $result .= ' {' . $identifier . '/' . $component . '}';
  6249. }
  6250. return $result;
  6251. }
  6252. /**
  6253. * Converts an array of strings to their localized value.
  6254. *
  6255. * @param array $array An array of strings
  6256. * @param string $component The language module that these strings can be found in.
  6257. * @return stdClass translated strings.
  6258. */
  6259. function get_strings($array, $component = '') {
  6260. $string = new stdClass;
  6261. foreach ($array as $item) {
  6262. $string->$item = get_string($item, $component);
  6263. }
  6264. return $string;
  6265. }
  6266. /**
  6267. * Prints out a translated string.
  6268. *
  6269. * Prints out a translated string using the return value from the {@link get_string()} function.
  6270. *
  6271. * Example usage of this function when the string is in the moodle.php file:<br/>
  6272. * <code>
  6273. * echo '<strong>';
  6274. * print_string('course');
  6275. * echo '</strong>';
  6276. * </code>
  6277. *
  6278. * Example usage of this function when the string is not in the moodle.php file:<br/>
  6279. * <code>
  6280. * echo '<h1>';
  6281. * print_string('typecourse', 'calendar');
  6282. * echo '</h1>';
  6283. * </code>
  6284. *
  6285. * @category string
  6286. * @param string $identifier The key identifier for the localized string
  6287. * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
  6288. * @param string|object|array $a An object, string or number that can be used within translation strings
  6289. */
  6290. function print_string($identifier, $component = '', $a = NULL) {
  6291. echo get_string($identifier, $component, $a);
  6292. }
  6293. /**
  6294. * Returns a list of charset codes
  6295. *
  6296. * Returns a list of charset codes. It's hardcoded, so they should be added manually
  6297. * (checking that such charset is supported by the texlib library!)
  6298. *
  6299. * @return array And associative array with contents in the form of charset => charset
  6300. */
  6301. function get_list_of_charsets() {
  6302. $charsets = array(
  6303. 'EUC-JP' => 'EUC-JP',
  6304. 'ISO-2022-JP'=> 'ISO-2022-JP',
  6305. 'ISO-8859-1' => 'ISO-8859-1',
  6306. 'SHIFT-JIS' => 'SHIFT-JIS',
  6307. 'GB2312' => 'GB2312',
  6308. 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
  6309. 'UTF-8' => 'UTF-8');
  6310. asort($charsets);
  6311. return $charsets;
  6312. }
  6313. /**
  6314. * Returns a list of valid and compatible themes
  6315. *
  6316. * @return array
  6317. */
  6318. function get_list_of_themes() {
  6319. global $CFG;
  6320. $themes = array();
  6321. if (!empty($CFG->themelist)) { // use admin's list of themes
  6322. $themelist = explode(',', $CFG->themelist);
  6323. } else {
  6324. $themelist = array_keys(get_plugin_list("theme"));
  6325. }
  6326. foreach ($themelist as $key => $themename) {
  6327. $theme = theme_config::load($themename);
  6328. $themes[$themename] = $theme;
  6329. }
  6330. collatorlib::asort_objects_by_method($themes, 'get_theme_name');
  6331. return $themes;
  6332. }
  6333. /**
  6334. * Returns a list of timezones in the current language
  6335. *
  6336. * @global object
  6337. * @global object
  6338. * @return array
  6339. */
  6340. function get_list_of_timezones() {
  6341. global $CFG, $DB;
  6342. static $timezones;
  6343. if (!empty($timezones)) { // This function has been called recently
  6344. return $timezones;
  6345. }
  6346. $timezones = array();
  6347. if ($rawtimezones = $DB->get_records_sql("SELECT MAX(id), name FROM {timezone} GROUP BY name")) {
  6348. foreach($rawtimezones as $timezone) {
  6349. if (!empty($timezone->name)) {
  6350. if (get_string_manager()->string_exists(strtolower($timezone->name), 'timezones')) {
  6351. $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
  6352. } else {
  6353. $timezones[$timezone->name] = $timezone->name;
  6354. }
  6355. if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
  6356. $timezones[$timezone->name] = $timezone->name;
  6357. }
  6358. }
  6359. }
  6360. }
  6361. asort($timezones);
  6362. for ($i = -13; $i <= 13; $i += .5) {
  6363. $tzstring = 'UTC';
  6364. if ($i < 0) {
  6365. $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
  6366. } else if ($i > 0) {
  6367. $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
  6368. } else {
  6369. $timezones[sprintf("%.1f", $i)] = $tzstring;
  6370. }
  6371. }
  6372. return $timezones;
  6373. }
  6374. /**
  6375. * Factory function for emoticon_manager
  6376. *
  6377. * @return emoticon_manager singleton
  6378. */
  6379. function get_emoticon_manager() {
  6380. static $singleton = null;
  6381. if (is_null($singleton)) {
  6382. $singleton = new emoticon_manager();
  6383. }
  6384. return $singleton;
  6385. }
  6386. /**
  6387. * Provides core support for plugins that have to deal with
  6388. * emoticons (like HTML editor or emoticon filter).
  6389. *
  6390. * Whenever this manager mentiones 'emoticon object', the following data
  6391. * structure is expected: stdClass with properties text, imagename, imagecomponent,
  6392. * altidentifier and altcomponent
  6393. *
  6394. * @see admin_setting_emoticons
  6395. */
  6396. class emoticon_manager {
  6397. /**
  6398. * Returns the currently enabled emoticons
  6399. *
  6400. * @return array of emoticon objects
  6401. */
  6402. public function get_emoticons() {
  6403. global $CFG;
  6404. if (empty($CFG->emoticons)) {
  6405. return array();
  6406. }
  6407. $emoticons = $this->decode_stored_config($CFG->emoticons);
  6408. if (!is_array($emoticons)) {
  6409. // something is wrong with the format of stored setting
  6410. debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
  6411. return array();
  6412. }
  6413. return $emoticons;
  6414. }
  6415. /**
  6416. * Converts emoticon object into renderable pix_emoticon object
  6417. *
  6418. * @param stdClass $emoticon emoticon object
  6419. * @param array $attributes explicit HTML attributes to set
  6420. * @return pix_emoticon
  6421. */
  6422. public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
  6423. $stringmanager = get_string_manager();
  6424. if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
  6425. $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
  6426. } else {
  6427. $alt = s($emoticon->text);
  6428. }
  6429. return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
  6430. }
  6431. /**
  6432. * Encodes the array of emoticon objects into a string storable in config table
  6433. *
  6434. * @see self::decode_stored_config()
  6435. * @param array $emoticons array of emtocion objects
  6436. * @return string
  6437. */
  6438. public function encode_stored_config(array $emoticons) {
  6439. return json_encode($emoticons);
  6440. }
  6441. /**
  6442. * Decodes the string into an array of emoticon objects
  6443. *
  6444. * @see self::encode_stored_config()
  6445. * @param string $encoded
  6446. * @return string|null
  6447. */
  6448. public function decode_stored_config($encoded) {
  6449. $decoded = json_decode($encoded);
  6450. if (!is_array($decoded)) {
  6451. return null;
  6452. }
  6453. return $decoded;
  6454. }
  6455. /**
  6456. * Returns default set of emoticons supported by Moodle
  6457. *
  6458. * @return array of sdtClasses
  6459. */
  6460. public function default_emoticons() {
  6461. return array(
  6462. $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
  6463. $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
  6464. $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
  6465. $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
  6466. $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
  6467. $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
  6468. $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
  6469. $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
  6470. $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
  6471. $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
  6472. $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
  6473. $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
  6474. $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
  6475. $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
  6476. $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
  6477. $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
  6478. $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
  6479. $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
  6480. $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
  6481. $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
  6482. $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
  6483. $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
  6484. $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
  6485. $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
  6486. $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
  6487. $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
  6488. $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
  6489. $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
  6490. $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
  6491. $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
  6492. );
  6493. }
  6494. /**
  6495. * Helper method preparing the stdClass with the emoticon properties
  6496. *
  6497. * @param string|array $text or array of strings
  6498. * @param string $imagename to be used by {@see pix_emoticon}
  6499. * @param string $altidentifier alternative string identifier, null for no alt
  6500. * @param array $altcomponent where the alternative string is defined
  6501. * @param string $imagecomponent to be used by {@see pix_emoticon}
  6502. * @return stdClass
  6503. */
  6504. protected function prepare_emoticon_object($text, $imagename, $altidentifier = null, $altcomponent = 'core_pix', $imagecomponent = 'core') {
  6505. return (object)array(
  6506. 'text' => $text,
  6507. 'imagename' => $imagename,
  6508. 'imagecomponent' => $imagecomponent,
  6509. 'altidentifier' => $altidentifier,
  6510. 'altcomponent' => $altcomponent,
  6511. );
  6512. }
  6513. }
  6514. /// ENCRYPTION ////////////////////////////////////////////////
  6515. /**
  6516. * rc4encrypt
  6517. *
  6518. * Please note that in this version of moodle that the default for rc4encryption is
  6519. * using the slightly more secure password key. There may be an issue when upgrading
  6520. * from an older version of moodle.
  6521. *
  6522. * @todo MDL-31836 Remove the old password key in version 2.4
  6523. * Code also needs to be changed in sessionlib.php
  6524. * @see get_moodle_cookie()
  6525. * @see set_moodle_cookie()
  6526. *
  6527. * @param string $data Data to encrypt.
  6528. * @param bool $usesecurekey Lets us know if we are using the old or new secure password key.
  6529. * @return string The now encrypted data.
  6530. */
  6531. function rc4encrypt($data, $usesecurekey = true) {
  6532. if (!$usesecurekey) {
  6533. $passwordkey = 'nfgjeingjk';
  6534. } else {
  6535. $passwordkey = get_site_identifier();
  6536. }
  6537. return endecrypt($passwordkey, $data, '');
  6538. }
  6539. /**
  6540. * rc4decrypt
  6541. *
  6542. * Please note that in this version of moodle that the default for rc4encryption is
  6543. * using the slightly more secure password key. There may be an issue when upgrading
  6544. * from an older version of moodle.
  6545. *
  6546. * @todo MDL-31836 Remove the old password key in version 2.4
  6547. * Code also needs to be changed in sessionlib.php
  6548. * @see get_moodle_cookie()
  6549. * @see set_moodle_cookie()
  6550. *
  6551. * @param string $data Data to decrypt.
  6552. * @param bool $usesecurekey Lets us know if we are using the old or new secure password key.
  6553. * @return string The now decrypted data.
  6554. */
  6555. function rc4decrypt($data, $usesecurekey = true) {
  6556. if (!$usesecurekey) {
  6557. $passwordkey = 'nfgjeingjk';
  6558. } else {
  6559. $passwordkey = get_site_identifier();
  6560. }
  6561. return endecrypt($passwordkey, $data, 'de');
  6562. }
  6563. /**
  6564. * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
  6565. *
  6566. * @todo Finish documenting this function
  6567. *
  6568. * @param string $pwd The password to use when encrypting or decrypting
  6569. * @param string $data The data to be decrypted/encrypted
  6570. * @param string $case Either 'de' for decrypt or '' for encrypt
  6571. * @return string
  6572. */
  6573. function endecrypt ($pwd, $data, $case) {
  6574. if ($case == 'de') {
  6575. $data = urldecode($data);
  6576. }
  6577. $key[] = '';
  6578. $box[] = '';
  6579. $temp_swap = '';
  6580. $pwd_length = 0;
  6581. $pwd_length = strlen($pwd);
  6582. for ($i = 0; $i <= 255; $i++) {
  6583. $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
  6584. $box[$i] = $i;
  6585. }
  6586. $x = 0;
  6587. for ($i = 0; $i <= 255; $i++) {
  6588. $x = ($x + $box[$i] + $key[$i]) % 256;
  6589. $temp_swap = $box[$i];
  6590. $box[$i] = $box[$x];
  6591. $box[$x] = $temp_swap;
  6592. }
  6593. $temp = '';
  6594. $k = '';
  6595. $cipherby = '';
  6596. $cipher = '';
  6597. $a = 0;
  6598. $j = 0;
  6599. for ($i = 0; $i < strlen($data); $i++) {
  6600. $a = ($a + 1) % 256;
  6601. $j = ($j + $box[$a]) % 256;
  6602. $temp = $box[$a];
  6603. $box[$a] = $box[$j];
  6604. $box[$j] = $temp;
  6605. $k = $box[(($box[$a] + $box[$j]) % 256)];
  6606. $cipherby = ord(substr($data, $i, 1)) ^ $k;
  6607. $cipher .= chr($cipherby);
  6608. }
  6609. if ($case == 'de') {
  6610. $cipher = urldecode(urlencode($cipher));
  6611. } else {
  6612. $cipher = urlencode($cipher);
  6613. }
  6614. return $cipher;
  6615. }
  6616. /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
  6617. /**
  6618. * Returns the exact absolute path to plugin directory.
  6619. *
  6620. * @param string $plugintype type of plugin
  6621. * @param string $name name of the plugin
  6622. * @return string full path to plugin directory; NULL if not found
  6623. */
  6624. function get_plugin_directory($plugintype, $name) {
  6625. global $CFG;
  6626. if ($plugintype === '') {
  6627. $plugintype = 'mod';
  6628. }
  6629. $types = get_plugin_types(true);
  6630. if (!array_key_exists($plugintype, $types)) {
  6631. return NULL;
  6632. }
  6633. $name = clean_param($name, PARAM_SAFEDIR); // just in case ;-)
  6634. if (!empty($CFG->themedir) and $plugintype === 'theme') {
  6635. if (!is_dir($types['theme'] . '/' . $name)) {
  6636. // ok, so the theme is supposed to be in the $CFG->themedir
  6637. return $CFG->themedir . '/' . $name;
  6638. }
  6639. }
  6640. return $types[$plugintype].'/'.$name;
  6641. }
  6642. /**
  6643. * Return exact absolute path to a plugin directory.
  6644. *
  6645. * @param string $component name such as 'moodle', 'mod_forum'
  6646. * @return string full path to component directory; NULL if not found
  6647. */
  6648. function get_component_directory($component) {
  6649. global $CFG;
  6650. list($type, $plugin) = normalize_component($component);
  6651. if ($type === 'core') {
  6652. if ($plugin === NULL ) {
  6653. $path = $CFG->libdir;
  6654. } else {
  6655. $subsystems = get_core_subsystems();
  6656. if (isset($subsystems[$plugin])) {
  6657. $path = $CFG->dirroot.'/'.$subsystems[$plugin];
  6658. } else {
  6659. $path = NULL;
  6660. }
  6661. }
  6662. } else {
  6663. $path = get_plugin_directory($type, $plugin);
  6664. }
  6665. return $path;
  6666. }
  6667. /**
  6668. * Normalize the component name using the "frankenstyle" names.
  6669. * @param string $component
  6670. * @return array $type+$plugin elements
  6671. */
  6672. function normalize_component($component) {
  6673. if ($component === 'moodle' or $component === 'core') {
  6674. $type = 'core';
  6675. $plugin = NULL;
  6676. } else if (strpos($component, '_') === false) {
  6677. $subsystems = get_core_subsystems();
  6678. if (array_key_exists($component, $subsystems)) {
  6679. $type = 'core';
  6680. $plugin = $component;
  6681. } else {
  6682. // everything else is a module
  6683. $type = 'mod';
  6684. $plugin = $component;
  6685. }
  6686. } else {
  6687. list($type, $plugin) = explode('_', $component, 2);
  6688. $plugintypes = get_plugin_types(false);
  6689. if ($type !== 'core' and !array_key_exists($type, $plugintypes)) {
  6690. $type = 'mod';
  6691. $plugin = $component;
  6692. }
  6693. }
  6694. return array($type, $plugin);
  6695. }
  6696. /**
  6697. * List all core subsystems and their location
  6698. *
  6699. * This is a whitelist of components that are part of the core and their
  6700. * language strings are defined in /lang/en/<<subsystem>>.php. If a given
  6701. * plugin is not listed here and it does not have proper plugintype prefix,
  6702. * then it is considered as course activity module.
  6703. *
  6704. * The location is dirroot relative path. NULL means there is no special
  6705. * directory for this subsystem. If the location is set, the subsystem's
  6706. * renderer.php is expected to be there.
  6707. *
  6708. * @return array of (string)name => (string|null)location
  6709. */
  6710. function get_core_subsystems() {
  6711. global $CFG;
  6712. static $info = null;
  6713. if (!$info) {
  6714. $info = array(
  6715. 'access' => NULL,
  6716. 'admin' => $CFG->admin,
  6717. 'auth' => 'auth',
  6718. 'backup' => 'backup/util/ui',
  6719. 'block' => 'blocks',
  6720. 'blog' => 'blog',
  6721. 'bulkusers' => NULL,
  6722. 'calendar' => 'calendar',
  6723. 'cohort' => 'cohort',
  6724. 'condition' => NULL,
  6725. 'completion' => NULL,
  6726. 'countries' => NULL,
  6727. 'course' => 'course',
  6728. 'currencies' => NULL,
  6729. 'dbtransfer' => NULL,
  6730. 'debug' => NULL,
  6731. 'dock' => NULL,
  6732. 'editor' => 'lib/editor',
  6733. 'edufields' => NULL,
  6734. 'enrol' => 'enrol',
  6735. 'error' => NULL,
  6736. 'filepicker' => NULL,
  6737. 'files' => 'files',
  6738. 'filters' => NULL,
  6739. 'fonts' => NULL,
  6740. 'form' => 'lib/form',
  6741. 'grades' => 'grade',
  6742. 'grading' => 'grade/grading',
  6743. 'group' => 'group',
  6744. 'help' => NULL,
  6745. 'hub' => NULL,
  6746. 'imscc' => NULL,
  6747. 'install' => NULL,
  6748. 'iso6392' => NULL,
  6749. 'langconfig' => NULL,
  6750. 'license' => NULL,
  6751. 'mathslib' => NULL,
  6752. 'media' => 'media',
  6753. 'message' => 'message',
  6754. 'mimetypes' => NULL,
  6755. 'mnet' => 'mnet',
  6756. 'moodle.org' => NULL, // the dot is nasty, watch out! should be renamed to moodleorg
  6757. 'my' => 'my',
  6758. 'notes' => 'notes',
  6759. 'pagetype' => NULL,
  6760. 'pix' => NULL,
  6761. 'plagiarism' => 'plagiarism',
  6762. 'plugin' => NULL,
  6763. 'portfolio' => 'portfolio',
  6764. 'publish' => 'course/publish',
  6765. 'question' => 'question',
  6766. 'rating' => 'rating',
  6767. 'register' => 'admin/registration', //TODO: this is wrong, unfortunately we would need to modify hub code to pass around the correct url
  6768. 'repository' => 'repository',
  6769. 'rss' => 'rss',
  6770. 'role' => $CFG->admin.'/role',
  6771. 'search' => 'search',
  6772. 'table' => NULL,
  6773. 'tag' => 'tag',
  6774. 'timezones' => NULL,
  6775. 'user' => 'user',
  6776. 'userkey' => NULL,
  6777. 'webservice' => 'webservice',
  6778. );
  6779. }
  6780. return $info;
  6781. }
  6782. /**
  6783. * Lists all plugin types
  6784. * @param bool $fullpaths false means relative paths from dirroot
  6785. * @return array Array of strings - name=>location
  6786. */
  6787. function get_plugin_types($fullpaths=true) {
  6788. global $CFG;
  6789. static $info = null;
  6790. static $fullinfo = null;
  6791. if (!$info) {
  6792. $info = array('qtype' => 'question/type',
  6793. 'mod' => 'mod',
  6794. 'auth' => 'auth',
  6795. 'enrol' => 'enrol',
  6796. 'message' => 'message/output',
  6797. 'block' => 'blocks',
  6798. 'filter' => 'filter',
  6799. 'editor' => 'lib/editor',
  6800. 'format' => 'course/format',
  6801. 'profilefield' => 'user/profile/field',
  6802. 'report' => 'report',
  6803. 'coursereport' => 'course/report', // must be after system reports
  6804. 'gradeexport' => 'grade/export',
  6805. 'gradeimport' => 'grade/import',
  6806. 'gradereport' => 'grade/report',
  6807. 'gradingform' => 'grade/grading/form',
  6808. 'mnetservice' => 'mnet/service',
  6809. 'webservice' => 'webservice',
  6810. 'repository' => 'repository',
  6811. 'portfolio' => 'portfolio',
  6812. 'qbehaviour' => 'question/behaviour',
  6813. 'qformat' => 'question/format',
  6814. 'plagiarism' => 'plagiarism',
  6815. 'tool' => $CFG->admin.'/tool',
  6816. 'theme' => 'theme', // this is a bit hacky, themes may be in $CFG->themedir too
  6817. );
  6818. $mods = get_plugin_list('mod');
  6819. foreach ($mods as $mod => $moddir) {
  6820. if (file_exists("$moddir/db/subplugins.php")) {
  6821. $subplugins = array();
  6822. include("$moddir/db/subplugins.php");
  6823. foreach ($subplugins as $subtype=>$dir) {
  6824. $info[$subtype] = $dir;
  6825. }
  6826. }
  6827. }
  6828. // local is always last!
  6829. $info['local'] = 'local';
  6830. $fullinfo = array();
  6831. foreach ($info as $type => $dir) {
  6832. $fullinfo[$type] = $CFG->dirroot.'/'.$dir;
  6833. }
  6834. }
  6835. return ($fullpaths ? $fullinfo : $info);
  6836. }
  6837. /**
  6838. * Simplified version of get_list_of_plugins()
  6839. * @param string $plugintype type of plugin
  6840. * @return array name=>fulllocation pairs of plugins of given type
  6841. */
  6842. function get_plugin_list($plugintype) {
  6843. global $CFG;
  6844. $ignored = array('CVS', '_vti_cnf', 'simpletest', 'db', 'yui', 'tests');
  6845. if ($plugintype == 'auth') {
  6846. // Historically we have had an auth plugin called 'db', so allow a special case.
  6847. $key = array_search('db', $ignored);
  6848. if ($key !== false) {
  6849. unset($ignored[$key]);
  6850. }
  6851. }
  6852. if ($plugintype === '') {
  6853. $plugintype = 'mod';
  6854. }
  6855. $fulldirs = array();
  6856. if ($plugintype === 'mod') {
  6857. // mod is an exception because we have to call this function from get_plugin_types()
  6858. $fulldirs[] = $CFG->dirroot.'/mod';
  6859. } else if ($plugintype === 'theme') {
  6860. $fulldirs[] = $CFG->dirroot.'/theme';
  6861. // themes are special because they may be stored also in separate directory
  6862. if (!empty($CFG->themedir) and file_exists($CFG->themedir) and is_dir($CFG->themedir) ) {
  6863. $fulldirs[] = $CFG->themedir;
  6864. }
  6865. } else {
  6866. $types = get_plugin_types(true);
  6867. if (!array_key_exists($plugintype, $types)) {
  6868. return array();
  6869. }
  6870. $fulldir = $types[$plugintype];
  6871. if (!file_exists($fulldir)) {
  6872. return array();
  6873. }
  6874. $fulldirs[] = $fulldir;
  6875. }
  6876. $result = array();
  6877. foreach ($fulldirs as $fulldir) {
  6878. if (!is_dir($fulldir)) {
  6879. continue;
  6880. }
  6881. $items = new DirectoryIterator($fulldir);
  6882. foreach ($items as $item) {
  6883. if ($item->isDot() or !$item->isDir()) {
  6884. continue;
  6885. }
  6886. $pluginname = $item->getFilename();
  6887. if (in_array($pluginname, $ignored)) {
  6888. continue;
  6889. }
  6890. $pluginname = clean_param($pluginname, PARAM_PLUGIN);
  6891. if (empty($pluginname)) {
  6892. // better ignore plugins with problematic names here
  6893. continue;
  6894. }
  6895. $result[$pluginname] = $fulldir.'/'.$pluginname;
  6896. unset($item);
  6897. }
  6898. unset($items);
  6899. }
  6900. //TODO: implement better sorting once we migrated all plugin names to 'pluginname', ksort does not work for unicode, that is why we have to sort by the dir name, not the strings!
  6901. ksort($result);
  6902. return $result;
  6903. }
  6904. /**
  6905. * Get a list of all the plugins of a given type that contain a particular file.
  6906. * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
  6907. * @param string $file the name of file that must be present in the plugin.
  6908. * (e.g. 'view.php', 'db/install.xml').
  6909. * @param bool $include if true (default false), the file will be include_once-ed if found.
  6910. * @return array with plugin name as keys (e.g. 'forum', 'courselist') and the path
  6911. * to the file relative to dirroot as value (e.g. "$CFG->dirroot/mod/forum/view.php").
  6912. */
  6913. function get_plugin_list_with_file($plugintype, $file, $include = false) {
  6914. global $CFG; // Necessary in case it is referenced by include()d PHP scripts.
  6915. $plugins = array();
  6916. foreach(get_plugin_list($plugintype) as $plugin => $dir) {
  6917. $path = $dir . '/' . $file;
  6918. if (file_exists($path)) {
  6919. if ($include) {
  6920. include_once($path);
  6921. }
  6922. $plugins[$plugin] = $path;
  6923. }
  6924. }
  6925. return $plugins;
  6926. }
  6927. /**
  6928. * Get a list of all the plugins of a given type that define a certain API function
  6929. * in a certain file. The plugin component names and function names are returned.
  6930. *
  6931. * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
  6932. * @param string $function the part of the name of the function after the
  6933. * frankenstyle prefix. e.g 'hook' if you are looking for functions with
  6934. * names like report_courselist_hook.
  6935. * @param string $file the name of file within the plugin that defines the
  6936. * function. Defaults to lib.php.
  6937. * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
  6938. * and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
  6939. */
  6940. function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
  6941. $pluginfunctions = array();
  6942. foreach (get_plugin_list_with_file($plugintype, $file, true) as $plugin => $notused) {
  6943. $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
  6944. if (function_exists($fullfunction)) {
  6945. // Function exists with standard name. Store, indexed by
  6946. // frankenstyle name of plugin
  6947. $pluginfunctions[$plugintype . '_' . $plugin] = $fullfunction;
  6948. } else if ($plugintype === 'mod') {
  6949. // For modules, we also allow plugin without full frankenstyle
  6950. // but just starting with the module name
  6951. $shortfunction = $plugin . '_' . $function;
  6952. if (function_exists($shortfunction)) {
  6953. $pluginfunctions[$plugintype . '_' . $plugin] = $shortfunction;
  6954. }
  6955. }
  6956. }
  6957. return $pluginfunctions;
  6958. }
  6959. /**
  6960. * Get a list of all the plugins of a given type that define a certain class
  6961. * in a certain file. The plugin component names and class names are returned.
  6962. *
  6963. * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
  6964. * @param string $class the part of the name of the class after the
  6965. * frankenstyle prefix. e.g 'thing' if you are looking for classes with
  6966. * names like report_courselist_thing. If you are looking for classes with
  6967. * the same name as the plugin name (e.g. qtype_multichoice) then pass ''.
  6968. * @param string $file the name of file within the plugin that defines the class.
  6969. * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
  6970. * and the class names as values (e.g. 'report_courselist_thing', 'qtype_multichoice').
  6971. */
  6972. function get_plugin_list_with_class($plugintype, $class, $file) {
  6973. if ($class) {
  6974. $suffix = '_' . $class;
  6975. } else {
  6976. $suffix = '';
  6977. }
  6978. $pluginclasses = array();
  6979. foreach (get_plugin_list_with_file($plugintype, $file, true) as $plugin => $notused) {
  6980. $classname = $plugintype . '_' . $plugin . $suffix;
  6981. if (class_exists($classname)) {
  6982. $pluginclasses[$plugintype . '_' . $plugin] = $classname;
  6983. }
  6984. }
  6985. return $pluginclasses;
  6986. }
  6987. /**
  6988. * Lists plugin-like directories within specified directory
  6989. *
  6990. * This function was originally used for standard Moodle plugins, please use
  6991. * new get_plugin_list() now.
  6992. *
  6993. * This function is used for general directory listing and backwards compatility.
  6994. *
  6995. * @param string $directory relative directory from root
  6996. * @param string $exclude dir name to exclude from the list (defaults to none)
  6997. * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
  6998. * @return array Sorted array of directory names found under the requested parameters
  6999. */
  7000. function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
  7001. global $CFG;
  7002. $plugins = array();
  7003. if (empty($basedir)) {
  7004. $basedir = $CFG->dirroot .'/'. $directory;
  7005. } else {
  7006. $basedir = $basedir .'/'. $directory;
  7007. }
  7008. if (file_exists($basedir) && filetype($basedir) == 'dir') {
  7009. if (!$dirhandle = opendir($basedir)) {
  7010. debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
  7011. return array();
  7012. }
  7013. while (false !== ($dir = readdir($dirhandle))) {
  7014. $firstchar = substr($dir, 0, 1);
  7015. if ($firstchar === '.' or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or $dir === 'phpunit' or $dir === $exclude) {
  7016. continue;
  7017. }
  7018. if (filetype($basedir .'/'. $dir) != 'dir') {
  7019. continue;
  7020. }
  7021. $plugins[] = $dir;
  7022. }
  7023. closedir($dirhandle);
  7024. }
  7025. if ($plugins) {
  7026. asort($plugins);
  7027. }
  7028. return $plugins;
  7029. }
  7030. /**
  7031. * Invoke plugin's callback functions
  7032. *
  7033. * @param string $type plugin type e.g. 'mod'
  7034. * @param string $name plugin name
  7035. * @param string $feature feature name
  7036. * @param string $action feature's action
  7037. * @param array $params parameters of callback function, should be an array
  7038. * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
  7039. * @return mixed
  7040. *
  7041. * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
  7042. */
  7043. function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
  7044. return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
  7045. }
  7046. /**
  7047. * Invoke component's callback functions
  7048. *
  7049. * @param string $component frankenstyle component name, e.g. 'mod_quiz'
  7050. * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
  7051. * @param array $params parameters of callback function
  7052. * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
  7053. * @return mixed
  7054. */
  7055. function component_callback($component, $function, array $params = array(), $default = null) {
  7056. global $CFG; // this is needed for require_once() below
  7057. $cleancomponent = clean_param($component, PARAM_COMPONENT);
  7058. if (empty($cleancomponent)) {
  7059. throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
  7060. }
  7061. $component = $cleancomponent;
  7062. list($type, $name) = normalize_component($component);
  7063. $component = $type . '_' . $name;
  7064. $oldfunction = $name.'_'.$function;
  7065. $function = $component.'_'.$function;
  7066. $dir = get_component_directory($component);
  7067. if (empty($dir)) {
  7068. throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
  7069. }
  7070. // Load library and look for function
  7071. if (file_exists($dir.'/lib.php')) {
  7072. require_once($dir.'/lib.php');
  7073. }
  7074. if (!function_exists($function) and function_exists($oldfunction)) {
  7075. if ($type !== 'mod' and $type !== 'core') {
  7076. debugging("Please use new function name $function instead of legacy $oldfunction");
  7077. }
  7078. $function = $oldfunction;
  7079. }
  7080. if (function_exists($function)) {
  7081. // Function exists, so just return function result
  7082. $ret = call_user_func_array($function, $params);
  7083. if (is_null($ret)) {
  7084. return $default;
  7085. } else {
  7086. return $ret;
  7087. }
  7088. }
  7089. return $default;
  7090. }
  7091. /**
  7092. * Checks whether a plugin supports a specified feature.
  7093. *
  7094. * @param string $type Plugin type e.g. 'mod'
  7095. * @param string $name Plugin name e.g. 'forum'
  7096. * @param string $feature Feature code (FEATURE_xx constant)
  7097. * @param mixed $default default value if feature support unknown
  7098. * @return mixed Feature result (false if not supported, null if feature is unknown,
  7099. * otherwise usually true but may have other feature-specific value such as array)
  7100. */
  7101. function plugin_supports($type, $name, $feature, $default = NULL) {
  7102. global $CFG;
  7103. if ($type === 'mod' and $name === 'NEWMODULE') {
  7104. //somebody forgot to rename the module template
  7105. return false;
  7106. }
  7107. $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
  7108. if (empty($component)) {
  7109. throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
  7110. }
  7111. $function = null;
  7112. if ($type === 'mod') {
  7113. // we need this special case because we support subplugins in modules,
  7114. // otherwise it would end up in infinite loop
  7115. if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
  7116. include_once("$CFG->dirroot/mod/$name/lib.php");
  7117. $function = $component.'_supports';
  7118. if (!function_exists($function)) {
  7119. // legacy non-frankenstyle function name
  7120. $function = $name.'_supports';
  7121. }
  7122. } else {
  7123. // invalid module
  7124. }
  7125. } else {
  7126. if (!$path = get_plugin_directory($type, $name)) {
  7127. // non existent plugin type
  7128. return false;
  7129. }
  7130. if (file_exists("$path/lib.php")) {
  7131. include_once("$path/lib.php");
  7132. $function = $component.'_supports';
  7133. }
  7134. }
  7135. if ($function and function_exists($function)) {
  7136. $supports = $function($feature);
  7137. if (is_null($supports)) {
  7138. // plugin does not know - use default
  7139. return $default;
  7140. } else {
  7141. return $supports;
  7142. }
  7143. }
  7144. //plugin does not care, so use default
  7145. return $default;
  7146. }
  7147. /**
  7148. * Returns true if the current version of PHP is greater that the specified one.
  7149. *
  7150. * @todo Check PHP version being required here is it too low?
  7151. *
  7152. * @param string $version The version of php being tested.
  7153. * @return bool
  7154. */
  7155. function check_php_version($version='5.2.4') {
  7156. return (version_compare(phpversion(), $version) >= 0);
  7157. }
  7158. /**
  7159. * Checks to see if is the browser operating system matches the specified
  7160. * brand.
  7161. *
  7162. * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
  7163. *
  7164. * @uses $_SERVER
  7165. * @param string $brand The operating system identifier being tested
  7166. * @return bool true if the given brand below to the detected operating system
  7167. */
  7168. function check_browser_operating_system($brand) {
  7169. if (empty($_SERVER['HTTP_USER_AGENT'])) {
  7170. return false;
  7171. }
  7172. if (preg_match("/$brand/i", $_SERVER['HTTP_USER_AGENT'])) {
  7173. return true;
  7174. }
  7175. return false;
  7176. }
  7177. /**
  7178. * Checks to see if is a browser matches the specified
  7179. * brand and is equal or better version.
  7180. *
  7181. * @uses $_SERVER
  7182. * @param string $brand The browser identifier being tested
  7183. * @param int $version The version of the browser, if not specified any version (except 5.5 for IE for BC reasons)
  7184. * @return bool true if the given version is below that of the detected browser
  7185. */
  7186. function check_browser_version($brand, $version = null) {
  7187. if (empty($_SERVER['HTTP_USER_AGENT'])) {
  7188. return false;
  7189. }
  7190. $agent = $_SERVER['HTTP_USER_AGENT'];
  7191. switch ($brand) {
  7192. case 'Camino': /// OSX browser using Gecke engine
  7193. if (strpos($agent, 'Camino') === false) {
  7194. return false;
  7195. }
  7196. if (empty($version)) {
  7197. return true; // no version specified
  7198. }
  7199. if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
  7200. if (version_compare($match[1], $version) >= 0) {
  7201. return true;
  7202. }
  7203. }
  7204. break;
  7205. case 'Firefox': /// Mozilla Firefox browsers
  7206. if (strpos($agent, 'Iceweasel') === false and strpos($agent, 'Firefox') === false) {
  7207. return false;
  7208. }
  7209. if (empty($version)) {
  7210. return true; // no version specified
  7211. }
  7212. if (preg_match("/(Iceweasel|Firefox)\/([0-9\.]+)/i", $agent, $match)) {
  7213. if (version_compare($match[2], $version) >= 0) {
  7214. return true;
  7215. }
  7216. }
  7217. break;
  7218. case 'Gecko': /// Gecko based browsers
  7219. if (empty($version) and substr_count($agent, 'Camino')) {
  7220. // MacOS X Camino support
  7221. $version = 20041110;
  7222. }
  7223. // the proper string - Gecko/CCYYMMDD Vendor/Version
  7224. // Faster version and work-a-round No IDN problem.
  7225. if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
  7226. if ($match[1] > $version) {
  7227. return true;
  7228. }
  7229. }
  7230. break;
  7231. case 'MSIE': /// Internet Explorer
  7232. if (strpos($agent, 'Opera') !== false) { // Reject Opera
  7233. return false;
  7234. }
  7235. // in case of IE we have to deal with BC of the version parameter
  7236. if (is_null($version)) {
  7237. $version = 5.5; // anything older is not considered a browser at all!
  7238. }
  7239. //see: http://www.useragentstring.com/pages/Internet%20Explorer/
  7240. if (preg_match("/MSIE ([0-9\.]+)/", $agent, $match)) {
  7241. if (version_compare($match[1], $version) >= 0) {
  7242. return true;
  7243. }
  7244. }
  7245. break;
  7246. case 'Opera': /// Opera
  7247. if (strpos($agent, 'Opera') === false) {
  7248. return false;
  7249. }
  7250. if (empty($version)) {
  7251. return true; // no version specified
  7252. }
  7253. if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
  7254. if (version_compare($match[1], $version) >= 0) {
  7255. return true;
  7256. }
  7257. }
  7258. break;
  7259. case 'WebKit': /// WebKit based browser - everything derived from it (Safari, Chrome, iOS, Android and other mobiles)
  7260. if (strpos($agent, 'AppleWebKit') === false) {
  7261. return false;
  7262. }
  7263. if (empty($version)) {
  7264. return true; // no version specified
  7265. }
  7266. if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
  7267. if (version_compare($match[1], $version) >= 0) {
  7268. return true;
  7269. }
  7270. }
  7271. break;
  7272. case 'Safari': /// Desktop version of Apple Safari browser - no mobile or touch devices
  7273. if (strpos($agent, 'AppleWebKit') === false) {
  7274. return false;
  7275. }
  7276. // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SymbianOS and any other mobile devices
  7277. if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
  7278. return false;
  7279. }
  7280. if (strpos($agent, 'Shiira')) { // Reject Shiira
  7281. return false;
  7282. }
  7283. if (strpos($agent, 'SymbianOS')) { // Reject SymbianOS
  7284. return false;
  7285. }
  7286. if (strpos($agent, 'Android')) { // Reject Androids too
  7287. return false;
  7288. }
  7289. if (strpos($agent, 'iPhone') or strpos($agent, 'iPad') or strpos($agent, 'iPod')) {
  7290. // No Apple mobile devices here - editor does not work, course ajax is not touch compatible, etc.
  7291. return false;
  7292. }
  7293. if (strpos($agent, 'Chrome')) { // Reject chrome browsers - it needs to be tested explicitly
  7294. return false;
  7295. }
  7296. if (empty($version)) {
  7297. return true; // no version specified
  7298. }
  7299. if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
  7300. if (version_compare($match[1], $version) >= 0) {
  7301. return true;
  7302. }
  7303. }
  7304. break;
  7305. case 'Chrome':
  7306. if (strpos($agent, 'Chrome') === false) {
  7307. return false;
  7308. }
  7309. if (empty($version)) {
  7310. return true; // no version specified
  7311. }
  7312. if (preg_match("/Chrome\/(.*)[ ]+/i", $agent, $match)) {
  7313. if (version_compare($match[1], $version) >= 0) {
  7314. return true;
  7315. }
  7316. }
  7317. break;
  7318. case 'Safari iOS': /// Safari on iPhone, iPad and iPod touch
  7319. if (strpos($agent, 'AppleWebKit') === false or strpos($agent, 'Safari') === false) {
  7320. return false;
  7321. }
  7322. if (!strpos($agent, 'iPhone') and !strpos($agent, 'iPad') and !strpos($agent, 'iPod')) {
  7323. return false;
  7324. }
  7325. if (empty($version)) {
  7326. return true; // no version specified
  7327. }
  7328. if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
  7329. if (version_compare($match[1], $version) >= 0) {
  7330. return true;
  7331. }
  7332. }
  7333. break;
  7334. case 'WebKit Android': /// WebKit browser on Android
  7335. if (strpos($agent, 'Linux; U; Android') === false) {
  7336. return false;
  7337. }
  7338. if (empty($version)) {
  7339. return true; // no version specified
  7340. }
  7341. if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
  7342. if (version_compare($match[1], $version) >= 0) {
  7343. return true;
  7344. }
  7345. }
  7346. break;
  7347. }
  7348. return false;
  7349. }
  7350. /**
  7351. * Returns whether a device/browser combination is mobile, tablet, legacy, default or the result of
  7352. * an optional admin specified regular expression. If enabledevicedetection is set to no or not set
  7353. * it returns default
  7354. *
  7355. * @return string device type
  7356. */
  7357. function get_device_type() {
  7358. global $CFG;
  7359. if (empty($CFG->enabledevicedetection) || empty($_SERVER['HTTP_USER_AGENT'])) {
  7360. return 'default';
  7361. }
  7362. $useragent = $_SERVER['HTTP_USER_AGENT'];
  7363. if (!empty($CFG->devicedetectregex)) {
  7364. $regexes = json_decode($CFG->devicedetectregex);
  7365. foreach ($regexes as $value=>$regex) {
  7366. if (preg_match($regex, $useragent)) {
  7367. return $value;
  7368. }
  7369. }
  7370. }
  7371. //mobile detection PHP direct copy from open source detectmobilebrowser.com
  7372. $phonesregex = '/android .+ mobile|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i';
  7373. $modelsregex = '/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-/i';
  7374. if (preg_match($phonesregex,$useragent) || preg_match($modelsregex,substr($useragent, 0, 4))){
  7375. return 'mobile';
  7376. }
  7377. $tabletregex = '/Tablet browser|android|iPad|iProd|GT-P1000|GT-I9000|SHW-M180S|SGH-T849|SCH-I800|Build\/ERE27|sholest/i';
  7378. if (preg_match($tabletregex, $useragent)) {
  7379. return 'tablet';
  7380. }
  7381. // Safe way to check for IE6 and not get false positives for some IE 7/8 users
  7382. if (substr($_SERVER['HTTP_USER_AGENT'], 0, 34) === 'Mozilla/4.0 (compatible; MSIE 6.0;') {
  7383. return 'legacy';
  7384. }
  7385. return 'default';
  7386. }
  7387. /**
  7388. * Returns a list of the device types supporting by Moodle
  7389. *
  7390. * @param boolean $incusertypes includes types specified using the devicedetectregex admin setting
  7391. * @return array $types
  7392. */
  7393. function get_device_type_list($incusertypes = true) {
  7394. global $CFG;
  7395. $types = array('default', 'legacy', 'mobile', 'tablet');
  7396. if ($incusertypes && !empty($CFG->devicedetectregex)) {
  7397. $regexes = json_decode($CFG->devicedetectregex);
  7398. foreach ($regexes as $value => $regex) {
  7399. $types[] = $value;
  7400. }
  7401. }
  7402. return $types;
  7403. }
  7404. /**
  7405. * Returns the theme selected for a particular device or false if none selected.
  7406. *
  7407. * @param string $devicetype
  7408. * @return string|false The name of the theme to use for the device or the false if not set
  7409. */
  7410. function get_selected_theme_for_device_type($devicetype = null) {
  7411. global $CFG;
  7412. if (empty($devicetype)) {
  7413. $devicetype = get_user_device_type();
  7414. }
  7415. $themevarname = get_device_cfg_var_name($devicetype);
  7416. if (empty($CFG->$themevarname)) {
  7417. return false;
  7418. }
  7419. return $CFG->$themevarname;
  7420. }
  7421. /**
  7422. * Returns the name of the device type theme var in $CFG (because there is not a standard convention to allow backwards compatability
  7423. *
  7424. * @param string $devicetype
  7425. * @return string The config variable to use to determine the theme
  7426. */
  7427. function get_device_cfg_var_name($devicetype = null) {
  7428. if ($devicetype == 'default' || empty($devicetype)) {
  7429. return 'theme';
  7430. }
  7431. return 'theme' . $devicetype;
  7432. }
  7433. /**
  7434. * Allows the user to switch the device they are seeing the theme for.
  7435. * This allows mobile users to switch back to the default theme, or theme for any other device.
  7436. *
  7437. * @param string $newdevice The device the user is currently using.
  7438. * @return string The device the user has switched to
  7439. */
  7440. function set_user_device_type($newdevice) {
  7441. global $USER;
  7442. $devicetype = get_device_type();
  7443. $devicetypes = get_device_type_list();
  7444. if ($newdevice == $devicetype) {
  7445. unset_user_preference('switchdevice'.$devicetype);
  7446. } else if (in_array($newdevice, $devicetypes)) {
  7447. set_user_preference('switchdevice'.$devicetype, $newdevice);
  7448. }
  7449. }
  7450. /**
  7451. * Returns the device the user is currently using, or if the user has chosen to switch devices
  7452. * for the current device type the type they have switched to.
  7453. *
  7454. * @return string The device the user is currently using or wishes to use
  7455. */
  7456. function get_user_device_type() {
  7457. $device = get_device_type();
  7458. $switched = get_user_preferences('switchdevice'.$device, false);
  7459. if ($switched != false) {
  7460. return $switched;
  7461. }
  7462. return $device;
  7463. }
  7464. /**
  7465. * Returns one or several CSS class names that match the user's browser. These can be put
  7466. * in the body tag of the page to apply browser-specific rules without relying on CSS hacks
  7467. *
  7468. * @return array An array of browser version classes
  7469. */
  7470. function get_browser_version_classes() {
  7471. $classes = array();
  7472. if (check_browser_version("MSIE", "0")) {
  7473. $classes[] = 'ie';
  7474. if (check_browser_version("MSIE", 9)) {
  7475. $classes[] = 'ie9';
  7476. } else if (check_browser_version("MSIE", 8)) {
  7477. $classes[] = 'ie8';
  7478. } elseif (check_browser_version("MSIE", 7)) {
  7479. $classes[] = 'ie7';
  7480. } elseif (check_browser_version("MSIE", 6)) {
  7481. $classes[] = 'ie6';
  7482. }
  7483. } else if (check_browser_version("Firefox") || check_browser_version("Gecko") || check_browser_version("Camino")) {
  7484. $classes[] = 'gecko';
  7485. if (preg_match('/rv\:([1-2])\.([0-9])/', $_SERVER['HTTP_USER_AGENT'], $matches)) {
  7486. $classes[] = "gecko{$matches[1]}{$matches[2]}";
  7487. }
  7488. } else if (check_browser_version("WebKit")) {
  7489. $classes[] = 'safari';
  7490. if (check_browser_version("Safari iOS")) {
  7491. $classes[] = 'ios';
  7492. } else if (check_browser_version("WebKit Android")) {
  7493. $classes[] = 'android';
  7494. }
  7495. } else if (check_browser_version("Opera")) {
  7496. $classes[] = 'opera';
  7497. }
  7498. return $classes;
  7499. }
  7500. /**
  7501. * Can handle rotated text. Whether it is safe to use the trickery in textrotate.js.
  7502. *
  7503. * @return bool True for yes, false for no
  7504. */
  7505. function can_use_rotated_text() {
  7506. global $USER;
  7507. return ajaxenabled(array('Firefox' => 2.0)) && !$USER->screenreader;;
  7508. }
  7509. /**
  7510. * Hack to find out the GD version by parsing phpinfo output
  7511. *
  7512. * @return int GD version (1, 2, or 0)
  7513. */
  7514. function check_gd_version() {
  7515. $gdversion = 0;
  7516. if (function_exists('gd_info')){
  7517. $gd_info = gd_info();
  7518. if (substr_count($gd_info['GD Version'], '2.')) {
  7519. $gdversion = 2;
  7520. } else if (substr_count($gd_info['GD Version'], '1.')) {
  7521. $gdversion = 1;
  7522. }
  7523. } else {
  7524. ob_start();
  7525. phpinfo(INFO_MODULES);
  7526. $phpinfo = ob_get_contents();
  7527. ob_end_clean();
  7528. $phpinfo = explode("\n", $phpinfo);
  7529. foreach ($phpinfo as $text) {
  7530. $parts = explode('</td>', $text);
  7531. foreach ($parts as $key => $val) {
  7532. $parts[$key] = trim(strip_tags($val));
  7533. }
  7534. if ($parts[0] == 'GD Version') {
  7535. if (substr_count($parts[1], '2.0')) {
  7536. $parts[1] = '2.0';
  7537. }
  7538. $gdversion = intval($parts[1]);
  7539. }
  7540. }
  7541. }
  7542. return $gdversion; // 1, 2 or 0
  7543. }
  7544. /**
  7545. * Determine if moodle installation requires update
  7546. *
  7547. * Checks version numbers of main code and all modules to see
  7548. * if there are any mismatches
  7549. *
  7550. * @global moodle_database $DB
  7551. * @return bool
  7552. */
  7553. function moodle_needs_upgrading() {
  7554. global $CFG, $DB, $OUTPUT;
  7555. if (empty($CFG->version)) {
  7556. return true;
  7557. }
  7558. // main versio nfirst
  7559. $version = null;
  7560. include($CFG->dirroot.'/version.php'); // defines $version and upgrades
  7561. if ($version > $CFG->version) {
  7562. return true;
  7563. }
  7564. // modules
  7565. $mods = get_plugin_list('mod');
  7566. $installed = $DB->get_records('modules', array(), '', 'name, version');
  7567. foreach ($mods as $mod => $fullmod) {
  7568. if ($mod === 'NEWMODULE') { // Someone has unzipped the template, ignore it
  7569. continue;
  7570. }
  7571. $module = new stdClass();
  7572. if (!is_readable($fullmod.'/version.php')) {
  7573. continue;
  7574. }
  7575. include($fullmod.'/version.php'); // defines $module with version etc
  7576. if (empty($installed[$mod])) {
  7577. return true;
  7578. } else if ($module->version > $installed[$mod]->version) {
  7579. return true;
  7580. }
  7581. }
  7582. unset($installed);
  7583. // blocks
  7584. $blocks = get_plugin_list('block');
  7585. $installed = $DB->get_records('block', array(), '', 'name, version');
  7586. require_once($CFG->dirroot.'/blocks/moodleblock.class.php');
  7587. foreach ($blocks as $blockname=>$fullblock) {
  7588. if ($blockname === 'NEWBLOCK') { // Someone has unzipped the template, ignore it
  7589. continue;
  7590. }
  7591. if (!is_readable($fullblock.'/version.php')) {
  7592. continue;
  7593. }
  7594. $plugin = new stdClass();
  7595. $plugin->version = NULL;
  7596. include($fullblock.'/version.php');
  7597. if (empty($installed[$blockname])) {
  7598. return true;
  7599. } else if ($plugin->version > $installed[$blockname]->version) {
  7600. return true;
  7601. }
  7602. }
  7603. unset($installed);
  7604. // now the rest of plugins
  7605. $plugintypes = get_plugin_types();
  7606. unset($plugintypes['mod']);
  7607. unset($plugintypes['block']);
  7608. $versions = $DB->get_records_menu('config_plugins', array('name' => 'version'), 'plugin', 'plugin, value');
  7609. foreach ($plugintypes as $type=>$unused) {
  7610. $plugs = get_plugin_list($type);
  7611. foreach ($plugs as $plug=>$fullplug) {
  7612. $component = $type.'_'.$plug;
  7613. if (!is_readable($fullplug.'/version.php')) {
  7614. continue;
  7615. }
  7616. $plugin = new stdClass();
  7617. include($fullplug.'/version.php'); // defines $plugin with version etc
  7618. if (array_key_exists($component, $versions)) {
  7619. $installedversion = $versions[$component];
  7620. } else {
  7621. $installedversion = get_config($component, 'version');
  7622. }
  7623. if (empty($installedversion)) { // new installation
  7624. return true;
  7625. } else if ($installedversion < $plugin->version) { // upgrade
  7626. return true;
  7627. }
  7628. }
  7629. }
  7630. return false;
  7631. }
  7632. /**
  7633. * Returns the major version of this site
  7634. *
  7635. * Moodle version numbers consist of three numbers separated by a dot, for
  7636. * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
  7637. * called major version. This function extracts the major version from either
  7638. * $CFG->release (default) or eventually from the $release variable defined in
  7639. * the main version.php.
  7640. *
  7641. * @param bool $fromdisk should the version if source code files be used
  7642. * @return string|false the major version like '2.3', false if could not be determined
  7643. */
  7644. function moodle_major_version($fromdisk = false) {
  7645. global $CFG;
  7646. if ($fromdisk) {
  7647. $release = null;
  7648. require($CFG->dirroot.'/version.php');
  7649. if (empty($release)) {
  7650. return false;
  7651. }
  7652. } else {
  7653. if (empty($CFG->release)) {
  7654. return false;
  7655. }
  7656. $release = $CFG->release;
  7657. }
  7658. if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
  7659. return $matches[0];
  7660. } else {
  7661. return false;
  7662. }
  7663. }
  7664. /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
  7665. /**
  7666. * Sets the system locale
  7667. *
  7668. * @category string
  7669. * @param string $locale Can be used to force a locale
  7670. */
  7671. function moodle_setlocale($locale='') {
  7672. global $CFG;
  7673. static $currentlocale = ''; // last locale caching
  7674. $oldlocale = $currentlocale;
  7675. /// Fetch the correct locale based on ostype
  7676. if ($CFG->ostype == 'WINDOWS') {
  7677. $stringtofetch = 'localewin';
  7678. } else {
  7679. $stringtofetch = 'locale';
  7680. }
  7681. /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
  7682. if (!empty($locale)) {
  7683. $currentlocale = $locale;
  7684. } else if (!empty($CFG->locale)) { // override locale for all language packs
  7685. $currentlocale = $CFG->locale;
  7686. } else {
  7687. $currentlocale = get_string($stringtofetch, 'langconfig');
  7688. }
  7689. /// do nothing if locale already set up
  7690. if ($oldlocale == $currentlocale) {
  7691. return;
  7692. }
  7693. /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
  7694. /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
  7695. /// Some day, numeric, monetary and other categories should be set too, I think. :-/
  7696. /// Get current values
  7697. $monetary= setlocale (LC_MONETARY, 0);
  7698. $numeric = setlocale (LC_NUMERIC, 0);
  7699. $ctype = setlocale (LC_CTYPE, 0);
  7700. if ($CFG->ostype != 'WINDOWS') {
  7701. $messages= setlocale (LC_MESSAGES, 0);
  7702. }
  7703. /// Set locale to all
  7704. setlocale (LC_ALL, $currentlocale);
  7705. /// Set old values
  7706. setlocale (LC_MONETARY, $monetary);
  7707. setlocale (LC_NUMERIC, $numeric);
  7708. if ($CFG->ostype != 'WINDOWS') {
  7709. setlocale (LC_MESSAGES, $messages);
  7710. }
  7711. if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
  7712. setlocale (LC_CTYPE, $ctype);
  7713. }
  7714. }
  7715. /**
  7716. * Count words in a string.
  7717. *
  7718. * Words are defined as things between whitespace.
  7719. *
  7720. * @category string
  7721. * @param string $string The text to be searched for words.
  7722. * @return int The count of words in the specified string
  7723. */
  7724. function count_words($string) {
  7725. $string = strip_tags($string);
  7726. return count(preg_split("/\w\b/", $string)) - 1;
  7727. }
  7728. /** Count letters in a string.
  7729. *
  7730. * Letters are defined as chars not in tags and different from whitespace.
  7731. *
  7732. * @category string
  7733. * @param string $string The text to be searched for letters.
  7734. * @return int The count of letters in the specified text.
  7735. */
  7736. function count_letters($string) {
  7737. /// Loading the textlib singleton instance. We are going to need it.
  7738. $string = strip_tags($string); // Tags are out now
  7739. $string = preg_replace('/[[:space:]]*/','',$string); //Whitespace are out now
  7740. return textlib::strlen($string);
  7741. }
  7742. /**
  7743. * Generate and return a random string of the specified length.
  7744. *
  7745. * @param int $length The length of the string to be created.
  7746. * @return string
  7747. */
  7748. function random_string ($length=15) {
  7749. $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  7750. $pool .= 'abcdefghijklmnopqrstuvwxyz';
  7751. $pool .= '0123456789';
  7752. $poollen = strlen($pool);
  7753. mt_srand ((double) microtime() * 1000000);
  7754. $string = '';
  7755. for ($i = 0; $i < $length; $i++) {
  7756. $string .= substr($pool, (mt_rand()%($poollen)), 1);
  7757. }
  7758. return $string;
  7759. }
  7760. /**
  7761. * Generate a complex random string (useful for md5 salts)
  7762. *
  7763. * This function is based on the above {@link random_string()} however it uses a
  7764. * larger pool of characters and generates a string between 24 and 32 characters
  7765. *
  7766. * @param int $length Optional if set generates a string to exactly this length
  7767. * @return string
  7768. */
  7769. function complex_random_string($length=null) {
  7770. $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  7771. $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
  7772. $poollen = strlen($pool);
  7773. mt_srand ((double) microtime() * 1000000);
  7774. if ($length===null) {
  7775. $length = floor(rand(24,32));
  7776. }
  7777. $string = '';
  7778. for ($i = 0; $i < $length; $i++) {
  7779. $string .= $pool[(mt_rand()%$poollen)];
  7780. }
  7781. return $string;
  7782. }
  7783. /**
  7784. * Given some text (which may contain HTML) and an ideal length,
  7785. * this function truncates the text neatly on a word boundary if possible
  7786. *
  7787. * @category string
  7788. * @global stdClass $CFG
  7789. * @param string $text text to be shortened
  7790. * @param int $ideal ideal string length
  7791. * @param boolean $exact if false, $text will not be cut mid-word
  7792. * @param string $ending The string to append if the passed string is truncated
  7793. * @return string $truncate shortened string
  7794. */
  7795. function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
  7796. global $CFG;
  7797. // if the plain text is shorter than the maximum length, return the whole text
  7798. if (textlib::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
  7799. return $text;
  7800. }
  7801. // Splits on HTML tags. Each open/close/empty tag will be the first thing
  7802. // and only tag in its 'line'
  7803. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  7804. $total_length = textlib::strlen($ending);
  7805. $truncate = '';
  7806. // This array stores information about open and close tags and their position
  7807. // in the truncated string. Each item in the array is an object with fields
  7808. // ->open (true if open), ->tag (tag name in lower case), and ->pos
  7809. // (byte position in truncated text)
  7810. $tagdetails = array();
  7811. foreach ($lines as $line_matchings) {
  7812. // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  7813. if (!empty($line_matchings[1])) {
  7814. // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
  7815. if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  7816. // do nothing
  7817. // if tag is a closing tag (f.e. </b>)
  7818. } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  7819. // record closing tag
  7820. $tagdetails[] = (object)array('open'=>false,
  7821. 'tag'=>textlib::strtolower($tag_matchings[1]), 'pos'=>textlib::strlen($truncate));
  7822. // if tag is an opening tag (f.e. <b>)
  7823. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  7824. // record opening tag
  7825. $tagdetails[] = (object)array('open'=>true,
  7826. 'tag'=>textlib::strtolower($tag_matchings[1]), 'pos'=>textlib::strlen($truncate));
  7827. }
  7828. // add html-tag to $truncate'd text
  7829. $truncate .= $line_matchings[1];
  7830. }
  7831. // calculate the length of the plain text part of the line; handle entities as one character
  7832. $content_length = textlib::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  7833. if ($total_length+$content_length > $ideal) {
  7834. // the number of characters which are left
  7835. $left = $ideal - $total_length;
  7836. $entities_length = 0;
  7837. // search for html entities
  7838. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
  7839. // calculate the real length of all entities in the legal range
  7840. foreach ($entities[0] as $entity) {
  7841. if ($entity[1]+1-$entities_length <= $left) {
  7842. $left--;
  7843. $entities_length += textlib::strlen($entity[0]);
  7844. } else {
  7845. // no more characters left
  7846. break;
  7847. }
  7848. }
  7849. }
  7850. $truncate .= textlib::substr($line_matchings[2], 0, $left+$entities_length);
  7851. // maximum length is reached, so get off the loop
  7852. break;
  7853. } else {
  7854. $truncate .= $line_matchings[2];
  7855. $total_length += $content_length;
  7856. }
  7857. // if the maximum length is reached, get off the loop
  7858. if($total_length >= $ideal) {
  7859. break;
  7860. }
  7861. }
  7862. // if the words shouldn't be cut in the middle...
  7863. if (!$exact) {
  7864. // ...search the last occurence of a space...
  7865. for ($k=textlib::strlen($truncate);$k>0;$k--) {
  7866. if ($char = textlib::substr($truncate, $k, 1)) {
  7867. if ($char === '.' or $char === ' ') {
  7868. $breakpos = $k+1;
  7869. break;
  7870. } else if (strlen($char) > 2) { // Chinese/Japanese/Korean text
  7871. $breakpos = $k+1; // can be truncated at any UTF-8
  7872. break; // character boundary.
  7873. }
  7874. }
  7875. }
  7876. if (isset($breakpos)) {
  7877. // ...and cut the text in this position
  7878. $truncate = textlib::substr($truncate, 0, $breakpos);
  7879. }
  7880. }
  7881. // add the defined ending to the text
  7882. $truncate .= $ending;
  7883. // Now calculate the list of open html tags based on the truncate position
  7884. $open_tags = array();
  7885. foreach ($tagdetails as $taginfo) {
  7886. if(isset($breakpos) && $taginfo->pos >= $breakpos) {
  7887. // Don't include tags after we made the break!
  7888. break;
  7889. }
  7890. if($taginfo->open) {
  7891. // add tag to the beginning of $open_tags list
  7892. array_unshift($open_tags, $taginfo->tag);
  7893. } else {
  7894. $pos = array_search($taginfo->tag, array_reverse($open_tags, true)); // can have multiple exact same open tags, close the last one
  7895. if ($pos !== false) {
  7896. unset($open_tags[$pos]);
  7897. }
  7898. }
  7899. }
  7900. // close all unclosed html-tags
  7901. foreach ($open_tags as $tag) {
  7902. $truncate .= '</' . $tag . '>';
  7903. }
  7904. return $truncate;
  7905. }
  7906. /**
  7907. * Given dates in seconds, how many weeks is the date from startdate
  7908. * The first week is 1, the second 2 etc ...
  7909. *
  7910. * @todo Finish documenting this function
  7911. *
  7912. * @uses WEEKSECS
  7913. * @param int $startdate Timestamp for the start date
  7914. * @param int $thedate Timestamp for the end date
  7915. * @return string
  7916. */
  7917. function getweek ($startdate, $thedate) {
  7918. if ($thedate < $startdate) { // error
  7919. return 0;
  7920. }
  7921. return floor(($thedate - $startdate) / WEEKSECS) + 1;
  7922. }
  7923. /**
  7924. * returns a randomly generated password of length $maxlen. inspired by
  7925. *
  7926. * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
  7927. * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
  7928. *
  7929. * @global stdClass $CFG
  7930. * @param int $maxlen The maximum size of the password being generated.
  7931. * @return string
  7932. */
  7933. function generate_password($maxlen=10) {
  7934. global $CFG;
  7935. if (empty($CFG->passwordpolicy)) {
  7936. $fillers = PASSWORD_DIGITS;
  7937. $wordlist = file($CFG->wordlist);
  7938. $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  7939. $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  7940. $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
  7941. $password = $word1 . $filler1 . $word2;
  7942. } else {
  7943. $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
  7944. $digits = $CFG->minpassworddigits;
  7945. $lower = $CFG->minpasswordlower;
  7946. $upper = $CFG->minpasswordupper;
  7947. $nonalphanum = $CFG->minpasswordnonalphanum;
  7948. $total = $lower + $upper + $digits + $nonalphanum;
  7949. // minlength should be the greater one of the two ( $minlen and $total )
  7950. $minlen = $minlen < $total ? $total : $minlen;
  7951. // maxlen can never be smaller than minlen
  7952. $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
  7953. $additional = $maxlen - $total;
  7954. // Make sure we have enough characters to fulfill
  7955. // complexity requirements
  7956. $passworddigits = PASSWORD_DIGITS;
  7957. while ($digits > strlen($passworddigits)) {
  7958. $passworddigits .= PASSWORD_DIGITS;
  7959. }
  7960. $passwordlower = PASSWORD_LOWER;
  7961. while ($lower > strlen($passwordlower)) {
  7962. $passwordlower .= PASSWORD_LOWER;
  7963. }
  7964. $passwordupper = PASSWORD_UPPER;
  7965. while ($upper > strlen($passwordupper)) {
  7966. $passwordupper .= PASSWORD_UPPER;
  7967. }
  7968. $passwordnonalphanum = PASSWORD_NONALPHANUM;
  7969. while ($nonalphanum > strlen($passwordnonalphanum)) {
  7970. $passwordnonalphanum .= PASSWORD_NONALPHANUM;
  7971. }
  7972. // Now mix and shuffle it all
  7973. $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
  7974. substr(str_shuffle ($passwordupper), 0, $upper) .
  7975. substr(str_shuffle ($passworddigits), 0, $digits) .
  7976. substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
  7977. substr(str_shuffle ($passwordlower .
  7978. $passwordupper .
  7979. $passworddigits .
  7980. $passwordnonalphanum), 0 , $additional));
  7981. }
  7982. return substr ($password, 0, $maxlen);
  7983. }
  7984. /**
  7985. * Given a float, prints it nicely.
  7986. * Localized floats must not be used in calculations!
  7987. *
  7988. * The stripzeros feature is intended for making numbers look nicer in small
  7989. * areas where it is not necessary to indicate the degree of accuracy by showing
  7990. * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
  7991. * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
  7992. *
  7993. * @param float $float The float to print
  7994. * @param int $decimalpoints The number of decimal places to print.
  7995. * @param bool $localized use localized decimal separator
  7996. * @param bool $stripzeros If true, removes final zeros after decimal point
  7997. * @return string locale float
  7998. */
  7999. function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
  8000. if (is_null($float)) {
  8001. return '';
  8002. }
  8003. if ($localized) {
  8004. $separator = get_string('decsep', 'langconfig');
  8005. } else {
  8006. $separator = '.';
  8007. }
  8008. $result = number_format($float, $decimalpoints, $separator, '');
  8009. if ($stripzeros) {
  8010. // Remove zeros and final dot if not needed
  8011. $result = preg_replace('~(' . preg_quote($separator) . ')?0+$~', '', $result);
  8012. }
  8013. return $result;
  8014. }
  8015. /**
  8016. * Converts locale specific floating point/comma number back to standard PHP float value
  8017. * Do NOT try to do any math operations before this conversion on any user submitted floats!
  8018. *
  8019. * @param string $locale_float locale aware float representation
  8020. * @return float
  8021. */
  8022. function unformat_float($locale_float) {
  8023. $locale_float = trim($locale_float);
  8024. if ($locale_float == '') {
  8025. return null;
  8026. }
  8027. $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
  8028. return (float)str_replace(get_string('decsep', 'langconfig'), '.', $locale_float);
  8029. }
  8030. /**
  8031. * Given a simple array, this shuffles it up just like shuffle()
  8032. * Unlike PHP's shuffle() this function works on any machine.
  8033. *
  8034. * @param array $array The array to be rearranged
  8035. * @return array
  8036. */
  8037. function swapshuffle($array) {
  8038. srand ((double) microtime() * 10000000);
  8039. $last = count($array) - 1;
  8040. for ($i=0;$i<=$last;$i++) {
  8041. $from = rand(0,$last);
  8042. $curr = $array[$i];
  8043. $array[$i] = $array[$from];
  8044. $array[$from] = $curr;
  8045. }
  8046. return $array;
  8047. }
  8048. /**
  8049. * Like {@link swapshuffle()}, but works on associative arrays
  8050. *
  8051. * @param array $array The associative array to be rearranged
  8052. * @return array
  8053. */
  8054. function swapshuffle_assoc($array) {
  8055. $newarray = array();
  8056. $newkeys = swapshuffle(array_keys($array));
  8057. foreach ($newkeys as $newkey) {
  8058. $newarray[$newkey] = $array[$newkey];
  8059. }
  8060. return $newarray;
  8061. }
  8062. /**
  8063. * Given an arbitrary array, and a number of draws,
  8064. * this function returns an array with that amount
  8065. * of items. The indexes are retained.
  8066. *
  8067. * @todo Finish documenting this function
  8068. *
  8069. * @param array $array
  8070. * @param int $draws
  8071. * @return array
  8072. */
  8073. function draw_rand_array($array, $draws) {
  8074. srand ((double) microtime() * 10000000);
  8075. $return = array();
  8076. $last = count($array);
  8077. if ($draws > $last) {
  8078. $draws = $last;
  8079. }
  8080. while ($draws > 0) {
  8081. $last--;
  8082. $keys = array_keys($array);
  8083. $rand = rand(0, $last);
  8084. $return[$keys[$rand]] = $array[$keys[$rand]];
  8085. unset($array[$keys[$rand]]);
  8086. $draws--;
  8087. }
  8088. return $return;
  8089. }
  8090. /**
  8091. * Calculate the difference between two microtimes
  8092. *
  8093. * @param string $a The first Microtime
  8094. * @param string $b The second Microtime
  8095. * @return string
  8096. */
  8097. function microtime_diff($a, $b) {
  8098. list($a_dec, $a_sec) = explode(' ', $a);
  8099. list($b_dec, $b_sec) = explode(' ', $b);
  8100. return $b_sec - $a_sec + $b_dec - $a_dec;
  8101. }
  8102. /**
  8103. * Given a list (eg a,b,c,d,e) this function returns
  8104. * an array of 1->a, 2->b, 3->c etc
  8105. *
  8106. * @param string $list The string to explode into array bits
  8107. * @param string $separator The separator used within the list string
  8108. * @return array The now assembled array
  8109. */
  8110. function make_menu_from_list($list, $separator=',') {
  8111. $array = array_reverse(explode($separator, $list), true);
  8112. foreach ($array as $key => $item) {
  8113. $outarray[$key+1] = trim($item);
  8114. }
  8115. return $outarray;
  8116. }
  8117. /**
  8118. * Creates an array that represents all the current grades that
  8119. * can be chosen using the given grading type.
  8120. *
  8121. * Negative numbers
  8122. * are scales, zero is no grade, and positive numbers are maximum
  8123. * grades.
  8124. *
  8125. * @todo Finish documenting this function or better deprecated this completely!
  8126. *
  8127. * @param int $gradingtype
  8128. * @return array
  8129. */
  8130. function make_grades_menu($gradingtype) {
  8131. global $DB;
  8132. $grades = array();
  8133. if ($gradingtype < 0) {
  8134. if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
  8135. return make_menu_from_list($scale->scale);
  8136. }
  8137. } else if ($gradingtype > 0) {
  8138. for ($i=$gradingtype; $i>=0; $i--) {
  8139. $grades[$i] = $i .' / '. $gradingtype;
  8140. }
  8141. return $grades;
  8142. }
  8143. return $grades;
  8144. }
  8145. /**
  8146. * This function returns the number of activities
  8147. * using scaleid in a courseid
  8148. *
  8149. * @todo Finish documenting this function
  8150. *
  8151. * @global object
  8152. * @global object
  8153. * @param int $courseid ?
  8154. * @param int $scaleid ?
  8155. * @return int
  8156. */
  8157. function course_scale_used($courseid, $scaleid) {
  8158. global $CFG, $DB;
  8159. $return = 0;
  8160. if (!empty($scaleid)) {
  8161. if ($cms = get_course_mods($courseid)) {
  8162. foreach ($cms as $cm) {
  8163. //Check cm->name/lib.php exists
  8164. if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
  8165. include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
  8166. $function_name = $cm->modname.'_scale_used';
  8167. if (function_exists($function_name)) {
  8168. if ($function_name($cm->instance,$scaleid)) {
  8169. $return++;
  8170. }
  8171. }
  8172. }
  8173. }
  8174. }
  8175. // check if any course grade item makes use of the scale
  8176. $return += $DB->count_records('grade_items', array('courseid'=>$courseid, 'scaleid'=>$scaleid));
  8177. // check if any outcome in the course makes use of the scale
  8178. $return += $DB->count_records_sql("SELECT COUNT('x')
  8179. FROM {grade_outcomes_courses} goc,
  8180. {grade_outcomes} go
  8181. WHERE go.id = goc.outcomeid
  8182. AND go.scaleid = ? AND goc.courseid = ?",
  8183. array($scaleid, $courseid));
  8184. }
  8185. return $return;
  8186. }
  8187. /**
  8188. * This function returns the number of activities
  8189. * using scaleid in the entire site
  8190. *
  8191. * @param int $scaleid
  8192. * @param array $courses
  8193. * @return int
  8194. */
  8195. function site_scale_used($scaleid, &$courses) {
  8196. $return = 0;
  8197. if (!is_array($courses) || count($courses) == 0) {
  8198. $courses = get_courses("all",false,"c.id,c.shortname");
  8199. }
  8200. if (!empty($scaleid)) {
  8201. if (is_array($courses) && count($courses) > 0) {
  8202. foreach ($courses as $course) {
  8203. $return += course_scale_used($course->id,$scaleid);
  8204. }
  8205. }
  8206. }
  8207. return $return;
  8208. }
  8209. /**
  8210. * make_unique_id_code
  8211. *
  8212. * @todo Finish documenting this function
  8213. *
  8214. * @uses $_SERVER
  8215. * @param string $extra Extra string to append to the end of the code
  8216. * @return string
  8217. */
  8218. function make_unique_id_code($extra='') {
  8219. $hostname = 'unknownhost';
  8220. if (!empty($_SERVER['HTTP_HOST'])) {
  8221. $hostname = $_SERVER['HTTP_HOST'];
  8222. } else if (!empty($_ENV['HTTP_HOST'])) {
  8223. $hostname = $_ENV['HTTP_HOST'];
  8224. } else if (!empty($_SERVER['SERVER_NAME'])) {
  8225. $hostname = $_SERVER['SERVER_NAME'];
  8226. } else if (!empty($_ENV['SERVER_NAME'])) {
  8227. $hostname = $_ENV['SERVER_NAME'];
  8228. }
  8229. $date = gmdate("ymdHis");
  8230. $random = random_string(6);
  8231. if ($extra) {
  8232. return $hostname .'+'. $date .'+'. $random .'+'. $extra;
  8233. } else {
  8234. return $hostname .'+'. $date .'+'. $random;
  8235. }
  8236. }
  8237. /**
  8238. * Function to check the passed address is within the passed subnet
  8239. *
  8240. * The parameter is a comma separated string of subnet definitions.
  8241. * Subnet strings can be in one of three formats:
  8242. * 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask)
  8243. * 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)
  8244. * 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-)
  8245. * Code for type 1 modified from user posted comments by mediator at
  8246. * {@link http://au.php.net/manual/en/function.ip2long.php}
  8247. *
  8248. * @param string $addr The address you are checking
  8249. * @param string $subnetstr The string of subnet addresses
  8250. * @return bool
  8251. */
  8252. function address_in_subnet($addr, $subnetstr) {
  8253. if ($addr == '0.0.0.0') {
  8254. return false;
  8255. }
  8256. $subnets = explode(',', $subnetstr);
  8257. $found = false;
  8258. $addr = trim($addr);
  8259. $addr = cleanremoteaddr($addr, false); // normalise
  8260. if ($addr === null) {
  8261. return false;
  8262. }
  8263. $addrparts = explode(':', $addr);
  8264. $ipv6 = strpos($addr, ':');
  8265. foreach ($subnets as $subnet) {
  8266. $subnet = trim($subnet);
  8267. if ($subnet === '') {
  8268. continue;
  8269. }
  8270. if (strpos($subnet, '/') !== false) {
  8271. ///1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn
  8272. list($ip, $mask) = explode('/', $subnet);
  8273. $mask = trim($mask);
  8274. if (!is_number($mask)) {
  8275. continue; // incorect mask number, eh?
  8276. }
  8277. $ip = cleanremoteaddr($ip, false); // normalise
  8278. if ($ip === null) {
  8279. continue;
  8280. }
  8281. if (strpos($ip, ':') !== false) {
  8282. // IPv6
  8283. if (!$ipv6) {
  8284. continue;
  8285. }
  8286. if ($mask > 128 or $mask < 0) {
  8287. continue; // nonsense
  8288. }
  8289. if ($mask == 0) {
  8290. return true; // any address
  8291. }
  8292. if ($mask == 128) {
  8293. if ($ip === $addr) {
  8294. return true;
  8295. }
  8296. continue;
  8297. }
  8298. $ipparts = explode(':', $ip);
  8299. $modulo = $mask % 16;
  8300. $ipnet = array_slice($ipparts, 0, ($mask-$modulo)/16);
  8301. $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
  8302. if (implode(':', $ipnet) === implode(':', $addrnet)) {
  8303. if ($modulo == 0) {
  8304. return true;
  8305. }
  8306. $pos = ($mask-$modulo)/16;
  8307. $ipnet = hexdec($ipparts[$pos]);
  8308. $addrnet = hexdec($addrparts[$pos]);
  8309. $mask = 0xffff << (16 - $modulo);
  8310. if (($addrnet & $mask) == ($ipnet & $mask)) {
  8311. return true;
  8312. }
  8313. }
  8314. } else {
  8315. // IPv4
  8316. if ($ipv6) {
  8317. continue;
  8318. }
  8319. if ($mask > 32 or $mask < 0) {
  8320. continue; // nonsense
  8321. }
  8322. if ($mask == 0) {
  8323. return true;
  8324. }
  8325. if ($mask == 32) {
  8326. if ($ip === $addr) {
  8327. return true;
  8328. }
  8329. continue;
  8330. }
  8331. $mask = 0xffffffff << (32 - $mask);
  8332. if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
  8333. return true;
  8334. }
  8335. }
  8336. } else if (strpos($subnet, '-') !== false) {
  8337. /// 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.
  8338. $parts = explode('-', $subnet);
  8339. if (count($parts) != 2) {
  8340. continue;
  8341. }
  8342. if (strpos($subnet, ':') !== false) {
  8343. // IPv6
  8344. if (!$ipv6) {
  8345. continue;
  8346. }
  8347. $ipstart = cleanremoteaddr(trim($parts[0]), false); // normalise
  8348. if ($ipstart === null) {
  8349. continue;
  8350. }
  8351. $ipparts = explode(':', $ipstart);
  8352. $start = hexdec(array_pop($ipparts));
  8353. $ipparts[] = trim($parts[1]);
  8354. $ipend = cleanremoteaddr(implode(':', $ipparts), false); // normalise
  8355. if ($ipend === null) {
  8356. continue;
  8357. }
  8358. $ipparts[7] = '';
  8359. $ipnet = implode(':', $ipparts);
  8360. if (strpos($addr, $ipnet) !== 0) {
  8361. continue;
  8362. }
  8363. $ipparts = explode(':', $ipend);
  8364. $end = hexdec($ipparts[7]);
  8365. $addrend = hexdec($addrparts[7]);
  8366. if (($addrend >= $start) and ($addrend <= $end)) {
  8367. return true;
  8368. }
  8369. } else {
  8370. // IPv4
  8371. if ($ipv6) {
  8372. continue;
  8373. }
  8374. $ipstart = cleanremoteaddr(trim($parts[0]), false); // normalise
  8375. if ($ipstart === null) {
  8376. continue;
  8377. }
  8378. $ipparts = explode('.', $ipstart);
  8379. $ipparts[3] = trim($parts[1]);
  8380. $ipend = cleanremoteaddr(implode('.', $ipparts), false); // normalise
  8381. if ($ipend === null) {
  8382. continue;
  8383. }
  8384. if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
  8385. return true;
  8386. }
  8387. }
  8388. } else {
  8389. /// 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
  8390. if (strpos($subnet, ':') !== false) {
  8391. // IPv6
  8392. if (!$ipv6) {
  8393. continue;
  8394. }
  8395. $parts = explode(':', $subnet);
  8396. $count = count($parts);
  8397. if ($parts[$count-1] === '') {
  8398. unset($parts[$count-1]); // trim trailing :
  8399. $count--;
  8400. $subnet = implode('.', $parts);
  8401. }
  8402. $isip = cleanremoteaddr($subnet, false); // normalise
  8403. if ($isip !== null) {
  8404. if ($isip === $addr) {
  8405. return true;
  8406. }
  8407. continue;
  8408. } else if ($count > 8) {
  8409. continue;
  8410. }
  8411. $zeros = array_fill(0, 8-$count, '0');
  8412. $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
  8413. if (address_in_subnet($addr, $subnet)) {
  8414. return true;
  8415. }
  8416. } else {
  8417. // IPv4
  8418. if ($ipv6) {
  8419. continue;
  8420. }
  8421. $parts = explode('.', $subnet);
  8422. $count = count($parts);
  8423. if ($parts[$count-1] === '') {
  8424. unset($parts[$count-1]); // trim trailing .
  8425. $count--;
  8426. $subnet = implode('.', $parts);
  8427. }
  8428. if ($count == 4) {
  8429. $subnet = cleanremoteaddr($subnet, false); // normalise
  8430. if ($subnet === $addr) {
  8431. return true;
  8432. }
  8433. continue;
  8434. } else if ($count > 4) {
  8435. continue;
  8436. }
  8437. $zeros = array_fill(0, 4-$count, '0');
  8438. $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
  8439. if (address_in_subnet($addr, $subnet)) {
  8440. return true;
  8441. }
  8442. }
  8443. }
  8444. }
  8445. return false;
  8446. }
  8447. /**
  8448. * For outputting debugging info
  8449. *
  8450. * @uses STDOUT
  8451. * @param string $string The string to write
  8452. * @param string $eol The end of line char(s) to use
  8453. * @param string $sleep Period to make the application sleep
  8454. * This ensures any messages have time to display before redirect
  8455. */
  8456. function mtrace($string, $eol="\n", $sleep=0) {
  8457. if (defined('STDOUT') and !PHPUNIT_TEST) {
  8458. fwrite(STDOUT, $string.$eol);
  8459. } else {
  8460. echo $string . $eol;
  8461. }
  8462. flush();
  8463. //delay to keep message on user's screen in case of subsequent redirect
  8464. if ($sleep) {
  8465. sleep($sleep);
  8466. }
  8467. }
  8468. /**
  8469. * Replace 1 or more slashes or backslashes to 1 slash
  8470. *
  8471. * @param string $path The path to strip
  8472. * @return string the path with double slashes removed
  8473. */
  8474. function cleardoubleslashes ($path) {
  8475. return preg_replace('/(\/|\\\){1,}/','/',$path);
  8476. }
  8477. /**
  8478. * Is current ip in give list?
  8479. *
  8480. * @param string $list
  8481. * @return bool
  8482. */
  8483. function remoteip_in_list($list){
  8484. $inlist = false;
  8485. $client_ip = getremoteaddr(null);
  8486. if(!$client_ip){
  8487. // ensure access on cli
  8488. return true;
  8489. }
  8490. $list = explode("\n", $list);
  8491. foreach($list as $subnet) {
  8492. $subnet = trim($subnet);
  8493. if (address_in_subnet($client_ip, $subnet)) {
  8494. $inlist = true;
  8495. break;
  8496. }
  8497. }
  8498. return $inlist;
  8499. }
  8500. /**
  8501. * Returns most reliable client address
  8502. *
  8503. * @global object
  8504. * @param string $default If an address can't be determined, then return this
  8505. * @return string The remote IP address
  8506. */
  8507. function getremoteaddr($default='0.0.0.0') {
  8508. global $CFG;
  8509. if (empty($CFG->getremoteaddrconf)) {
  8510. // This will happen, for example, before just after the upgrade, as the
  8511. // user is redirected to the admin screen.
  8512. $variablestoskip = 0;
  8513. } else {
  8514. $variablestoskip = $CFG->getremoteaddrconf;
  8515. }
  8516. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
  8517. if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  8518. $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
  8519. return $address ? $address : $default;
  8520. }
  8521. }
  8522. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
  8523. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  8524. $address = cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
  8525. return $address ? $address : $default;
  8526. }
  8527. }
  8528. if (!empty($_SERVER['REMOTE_ADDR'])) {
  8529. $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
  8530. return $address ? $address : $default;
  8531. } else {
  8532. return $default;
  8533. }
  8534. }
  8535. /**
  8536. * Cleans an ip address. Internal addresses are now allowed.
  8537. * (Originally local addresses were not allowed.)
  8538. *
  8539. * @param string $addr IPv4 or IPv6 address
  8540. * @param bool $compress use IPv6 address compression
  8541. * @return string normalised ip address string, null if error
  8542. */
  8543. function cleanremoteaddr($addr, $compress=false) {
  8544. $addr = trim($addr);
  8545. //TODO: maybe add a separate function is_addr_public() or something like this
  8546. if (strpos($addr, ':') !== false) {
  8547. // can be only IPv6
  8548. $parts = explode(':', $addr);
  8549. $count = count($parts);
  8550. if (strpos($parts[$count-1], '.') !== false) {
  8551. //legacy ipv4 notation
  8552. $last = array_pop($parts);
  8553. $ipv4 = cleanremoteaddr($last, true);
  8554. if ($ipv4 === null) {
  8555. return null;
  8556. }
  8557. $bits = explode('.', $ipv4);
  8558. $parts[] = dechex($bits[0]).dechex($bits[1]);
  8559. $parts[] = dechex($bits[2]).dechex($bits[3]);
  8560. $count = count($parts);
  8561. $addr = implode(':', $parts);
  8562. }
  8563. if ($count < 3 or $count > 8) {
  8564. return null; // severly malformed
  8565. }
  8566. if ($count != 8) {
  8567. if (strpos($addr, '::') === false) {
  8568. return null; // malformed
  8569. }
  8570. // uncompress ::
  8571. $insertat = array_search('', $parts, true);
  8572. $missing = array_fill(0, 1 + 8 - $count, '0');
  8573. array_splice($parts, $insertat, 1, $missing);
  8574. foreach ($parts as $key=>$part) {
  8575. if ($part === '') {
  8576. $parts[$key] = '0';
  8577. }
  8578. }
  8579. }
  8580. $adr = implode(':', $parts);
  8581. if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
  8582. return null; // incorrect format - sorry
  8583. }
  8584. // normalise 0s and case
  8585. $parts = array_map('hexdec', $parts);
  8586. $parts = array_map('dechex', $parts);
  8587. $result = implode(':', $parts);
  8588. if (!$compress) {
  8589. return $result;
  8590. }
  8591. if ($result === '0:0:0:0:0:0:0:0') {
  8592. return '::'; // all addresses
  8593. }
  8594. $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
  8595. if ($compressed !== $result) {
  8596. return $compressed;
  8597. }
  8598. $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
  8599. if ($compressed !== $result) {
  8600. return $compressed;
  8601. }
  8602. $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
  8603. if ($compressed !== $result) {
  8604. return $compressed;
  8605. }
  8606. return $result;
  8607. }
  8608. // first get all things that look like IPv4 addresses
  8609. $parts = array();
  8610. if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
  8611. return null;
  8612. }
  8613. unset($parts[0]);
  8614. foreach ($parts as $key=>$match) {
  8615. if ($match > 255) {
  8616. return null;
  8617. }
  8618. $parts[$key] = (int)$match; // normalise 0s
  8619. }
  8620. return implode('.', $parts);
  8621. }
  8622. /**
  8623. * This function will make a complete copy of anything it's given,
  8624. * regardless of whether it's an object or not.
  8625. *
  8626. * @param mixed $thing Something you want cloned
  8627. * @return mixed What ever it is you passed it
  8628. */
  8629. function fullclone($thing) {
  8630. return unserialize(serialize($thing));
  8631. }
  8632. /**
  8633. * This function expects to called during shutdown
  8634. * should be set via register_shutdown_function()
  8635. * in lib/setup.php .
  8636. *
  8637. * @return void
  8638. */
  8639. function moodle_request_shutdown() {
  8640. global $CFG;
  8641. // help apache server if possible
  8642. $apachereleasemem = false;
  8643. if (function_exists('apache_child_terminate') && function_exists('memory_get_usage')
  8644. && ini_get_bool('child_terminate')) {
  8645. $limit = (empty($CFG->apachemaxmem) ? 64*1024*1024 : $CFG->apachemaxmem); //64MB default
  8646. if (memory_get_usage() > get_real_size($limit)) {
  8647. $apachereleasemem = $limit;
  8648. @apache_child_terminate();
  8649. }
  8650. }
  8651. // deal with perf logging
  8652. if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
  8653. if ($apachereleasemem) {
  8654. error_log('Mem usage over '.$apachereleasemem.': marking Apache child for reaping.');
  8655. }
  8656. if (defined('MDL_PERFTOLOG')) {
  8657. $perf = get_performance_info();
  8658. error_log("PERF: " . $perf['txt']);
  8659. }
  8660. if (defined('MDL_PERFINC')) {
  8661. $inc = get_included_files();
  8662. $ts = 0;
  8663. foreach($inc as $f) {
  8664. if (preg_match(':^/:', $f)) {
  8665. $fs = filesize($f);
  8666. $ts += $fs;
  8667. $hfs = display_size($fs);
  8668. error_log(substr($f,strlen($CFG->dirroot)) . " size: $fs ($hfs)"
  8669. , NULL, NULL, 0);
  8670. } else {
  8671. error_log($f , NULL, NULL, 0);
  8672. }
  8673. }
  8674. if ($ts > 0 ) {
  8675. $hts = display_size($ts);
  8676. error_log("Total size of files included: $ts ($hts)");
  8677. }
  8678. }
  8679. }
  8680. }
  8681. /**
  8682. * If new messages are waiting for the current user, then insert
  8683. * JavaScript to pop up the messaging window into the page
  8684. *
  8685. * @global moodle_page $PAGE
  8686. * @return void
  8687. */
  8688. function message_popup_window() {
  8689. global $USER, $DB, $PAGE, $CFG, $SITE;
  8690. if (!$PAGE->get_popup_notification_allowed() || empty($CFG->messaging)) {
  8691. return;
  8692. }
  8693. if (!isloggedin() || isguestuser()) {
  8694. return;
  8695. }
  8696. if (!isset($USER->message_lastpopup)) {
  8697. $USER->message_lastpopup = 0;
  8698. } else if ($USER->message_lastpopup > (time()-120)) {
  8699. //dont run the query to check whether to display a popup if its been run in the last 2 minutes
  8700. return;
  8701. }
  8702. //a quick query to check whether the user has new messages
  8703. $messagecount = $DB->count_records('message', array('useridto' => $USER->id));
  8704. if ($messagecount<1) {
  8705. return;
  8706. }
  8707. //got unread messages so now do another query that joins with the user table
  8708. $messagesql = "SELECT m.id, m.smallmessage, m.fullmessageformat, m.notification, u.firstname, u.lastname
  8709. FROM {message} m
  8710. JOIN {message_working} mw ON m.id=mw.unreadmessageid
  8711. JOIN {message_processors} p ON mw.processorid=p.id
  8712. JOIN {user} u ON m.useridfrom=u.id
  8713. WHERE m.useridto = :userid
  8714. AND p.name='popup'";
  8715. //if the user was last notified over an hour ago we can renotify them of old messages
  8716. //so don't worry about when the new message was sent
  8717. $lastnotifiedlongago = $USER->message_lastpopup < (time()-3600);
  8718. if (!$lastnotifiedlongago) {
  8719. $messagesql .= 'AND m.timecreated > :lastpopuptime';
  8720. }
  8721. $message_users = $DB->get_records_sql($messagesql, array('userid'=>$USER->id, 'lastpopuptime'=>$USER->message_lastpopup));
  8722. //if we have new messages to notify the user about
  8723. if (!empty($message_users)) {
  8724. $strmessages = '';
  8725. if (count($message_users)>1) {
  8726. $strmessages = get_string('unreadnewmessages', 'message', count($message_users));
  8727. } else {
  8728. $message_users = reset($message_users);
  8729. //show who the message is from if its not a notification
  8730. if (!$message_users->notification) {
  8731. $strmessages = get_string('unreadnewmessage', 'message', fullname($message_users) );
  8732. }
  8733. //try to display the small version of the message
  8734. $smallmessage = null;
  8735. if (!empty($message_users->smallmessage)) {
  8736. //display the first 200 chars of the message in the popup
  8737. $smallmessage = null;
  8738. if (textlib::strlen($message_users->smallmessage) > 200) {
  8739. $smallmessage = textlib::substr($message_users->smallmessage,0,200).'...';
  8740. } else {
  8741. $smallmessage = $message_users->smallmessage;
  8742. }
  8743. //prevent html symbols being displayed
  8744. if ($message_users->fullmessageformat == FORMAT_HTML) {
  8745. $smallmessage = html_to_text($smallmessage);
  8746. } else {
  8747. $smallmessage = s($smallmessage);
  8748. }
  8749. } else if ($message_users->notification) {
  8750. //its a notification with no smallmessage so just say they have a notification
  8751. $smallmessage = get_string('unreadnewnotification', 'message');
  8752. }
  8753. if (!empty($smallmessage)) {
  8754. $strmessages .= '<div id="usermessage">'.s($smallmessage).'</div>';
  8755. }
  8756. }
  8757. $strgomessage = get_string('gotomessages', 'message');
  8758. $strstaymessage = get_string('ignore','admin');
  8759. $url = $CFG->wwwroot.'/message/index.php';
  8760. $content = html_writer::start_tag('div', array('id'=>'newmessageoverlay','class'=>'mdl-align')).
  8761. html_writer::start_tag('div', array('id'=>'newmessagetext')).
  8762. $strmessages.
  8763. html_writer::end_tag('div').
  8764. html_writer::start_tag('div', array('id'=>'newmessagelinks')).
  8765. html_writer::link($url, $strgomessage, array('id'=>'notificationyes')).'&nbsp;&nbsp;&nbsp;'.
  8766. html_writer::link('', $strstaymessage, array('id'=>'notificationno')).
  8767. html_writer::end_tag('div');
  8768. html_writer::end_tag('div');
  8769. $PAGE->requires->js_init_call('M.core_message.init_notification', array('', $content, $url));
  8770. $USER->message_lastpopup = time();
  8771. }
  8772. }
  8773. /**
  8774. * Used to make sure that $min <= $value <= $max
  8775. *
  8776. * Make sure that value is between min, and max
  8777. *
  8778. * @param int $min The minimum value
  8779. * @param int $value The value to check
  8780. * @param int $max The maximum value
  8781. */
  8782. function bounded_number($min, $value, $max) {
  8783. if($value < $min) {
  8784. return $min;
  8785. }
  8786. if($value > $max) {
  8787. return $max;
  8788. }
  8789. return $value;
  8790. }
  8791. /**
  8792. * Check if there is a nested array within the passed array
  8793. *
  8794. * @param array $array
  8795. * @return bool true if there is a nested array false otherwise
  8796. */
  8797. function array_is_nested($array) {
  8798. foreach ($array as $value) {
  8799. if (is_array($value)) {
  8800. return true;
  8801. }
  8802. }
  8803. return false;
  8804. }
  8805. /**
  8806. * get_performance_info() pairs up with init_performance_info()
  8807. * loaded in setup.php. Returns an array with 'html' and 'txt'
  8808. * values ready for use, and each of the individual stats provided
  8809. * separately as well.
  8810. *
  8811. * @global object
  8812. * @global object
  8813. * @global object
  8814. * @return array
  8815. */
  8816. function get_performance_info() {
  8817. global $CFG, $PERF, $DB, $PAGE;
  8818. $info = array();
  8819. $info['html'] = ''; // holds userfriendly HTML representation
  8820. $info['txt'] = me() . ' '; // holds log-friendly representation
  8821. $info['realtime'] = microtime_diff($PERF->starttime, microtime());
  8822. $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
  8823. $info['txt'] .= 'time: '.$info['realtime'].'s ';
  8824. if (function_exists('memory_get_usage')) {
  8825. $info['memory_total'] = memory_get_usage();
  8826. $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
  8827. $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
  8828. $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
  8829. }
  8830. if (function_exists('memory_get_peak_usage')) {
  8831. $info['memory_peak'] = memory_get_peak_usage();
  8832. $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
  8833. $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
  8834. }
  8835. $inc = get_included_files();
  8836. //error_log(print_r($inc,1));
  8837. $info['includecount'] = count($inc);
  8838. $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
  8839. $info['txt'] .= 'includecount: '.$info['includecount'].' ';
  8840. $filtermanager = filter_manager::instance();
  8841. if (method_exists($filtermanager, 'get_performance_summary')) {
  8842. list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
  8843. $info = array_merge($filterinfo, $info);
  8844. foreach ($filterinfo as $key => $value) {
  8845. $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
  8846. $info['txt'] .= "$key: $value ";
  8847. }
  8848. }
  8849. $stringmanager = get_string_manager();
  8850. if (method_exists($stringmanager, 'get_performance_summary')) {
  8851. list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
  8852. $info = array_merge($filterinfo, $info);
  8853. foreach ($filterinfo as $key => $value) {
  8854. $info['html'] .= "<span class='$key'>$nicenames[$key]: $value </span> ";
  8855. $info['txt'] .= "$key: $value ";
  8856. }
  8857. }
  8858. $jsmodules = $PAGE->requires->get_loaded_modules();
  8859. if ($jsmodules) {
  8860. $yuicount = 0;
  8861. $othercount = 0;
  8862. $details = '';
  8863. foreach ($jsmodules as $module => $backtraces) {
  8864. if (strpos($module, 'yui') === 0) {
  8865. $yuicount += 1;
  8866. } else {
  8867. $othercount += 1;
  8868. }
  8869. if (!empty($CFG->yuimoduledebug)) {
  8870. // hidden feature for developers working on YUI module infrastructure
  8871. $details .= "<div class='yui-module'><p>$module</p>";
  8872. foreach ($backtraces as $backtrace) {
  8873. $details .= "<div class='backtrace'>$backtrace</div>";
  8874. }
  8875. $details .= '</div>';
  8876. }
  8877. }
  8878. $info['html'] .= "<span class='includedyuimodules'>Included YUI modules: $yuicount</span> ";
  8879. $info['txt'] .= "includedyuimodules: $yuicount ";
  8880. $info['html'] .= "<span class='includedjsmodules'>Other JavaScript modules: $othercount</span> ";
  8881. $info['txt'] .= "includedjsmodules: $othercount ";
  8882. if ($details) {
  8883. $info['html'] .= '<div id="yui-module-debug" class="notifytiny">'.$details.'</div>';
  8884. }
  8885. }
  8886. if (!empty($PERF->logwrites)) {
  8887. $info['logwrites'] = $PERF->logwrites;
  8888. $info['html'] .= '<span class="logwrites">Log DB writes '.$info['logwrites'].'</span> ';
  8889. $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
  8890. }
  8891. $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
  8892. $info['html'] .= '<span class="dbqueries">DB reads/writes: '.$info['dbqueries'].'</span> ';
  8893. $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
  8894. if (function_exists('posix_times')) {
  8895. $ptimes = posix_times();
  8896. if (is_array($ptimes)) {
  8897. foreach ($ptimes as $key => $val) {
  8898. $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
  8899. }
  8900. $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
  8901. $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
  8902. }
  8903. }
  8904. // Grab the load average for the last minute
  8905. // /proc will only work under some linux configurations
  8906. // while uptime is there under MacOSX/Darwin and other unices
  8907. if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
  8908. list($server_load) = explode(' ', $loadavg[0]);
  8909. unset($loadavg);
  8910. } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
  8911. if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
  8912. $server_load = $matches[1];
  8913. } else {
  8914. trigger_error('Could not parse uptime output!');
  8915. }
  8916. }
  8917. if (!empty($server_load)) {
  8918. $info['serverload'] = $server_load;
  8919. $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
  8920. $info['txt'] .= "serverload: {$info['serverload']} ";
  8921. }
  8922. // Display size of session if session started
  8923. if (session_id()) {
  8924. $info['sessionsize'] = display_size(strlen(session_encode()));
  8925. $info['html'] .= '<span class="sessionsize">Session: ' . $info['sessionsize'] . '</span> ';
  8926. $info['txt'] .= "Session: {$info['sessionsize']} ";
  8927. }
  8928. /* if (isset($rcache->hits) && isset($rcache->misses)) {
  8929. $info['rcachehits'] = $rcache->hits;
  8930. $info['rcachemisses'] = $rcache->misses;
  8931. $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
  8932. "{$rcache->hits}/{$rcache->misses}</span> ";
  8933. $info['txt'] .= 'rcache: '.
  8934. "{$rcache->hits}/{$rcache->misses} ";
  8935. }*/
  8936. $info['html'] = '<div class="performanceinfo siteinfo">'.$info['html'].'</div>';
  8937. return $info;
  8938. }
  8939. /**
  8940. * @todo Document this function linux people
  8941. */
  8942. function apd_get_profiling() {
  8943. return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
  8944. }
  8945. /**
  8946. * Delete directory or only its content
  8947. *
  8948. * @param string $dir directory path
  8949. * @param bool $content_only
  8950. * @return bool success, true also if dir does not exist
  8951. */
  8952. function remove_dir($dir, $content_only=false) {
  8953. if (!file_exists($dir)) {
  8954. // nothing to do
  8955. return true;
  8956. }
  8957. if (!$handle = opendir($dir)) {
  8958. return false;
  8959. }
  8960. $result = true;
  8961. while (false!==($item = readdir($handle))) {
  8962. if($item != '.' && $item != '..') {
  8963. if(is_dir($dir.'/'.$item)) {
  8964. $result = remove_dir($dir.'/'.$item) && $result;
  8965. }else{
  8966. $result = unlink($dir.'/'.$item) && $result;
  8967. }
  8968. }
  8969. }
  8970. closedir($handle);
  8971. if ($content_only) {
  8972. clearstatcache(); // make sure file stat cache is properly invalidated
  8973. return $result;
  8974. }
  8975. $result = rmdir($dir); // if anything left the result will be false, no need for && $result
  8976. clearstatcache(); // make sure file stat cache is properly invalidated
  8977. return $result;
  8978. }
  8979. /**
  8980. * Detect if an object or a class contains a given property
  8981. * will take an actual object or the name of a class
  8982. *
  8983. * @param mix $obj Name of class or real object to test
  8984. * @param string $property name of property to find
  8985. * @return bool true if property exists
  8986. */
  8987. function object_property_exists( $obj, $property ) {
  8988. if (is_string( $obj )) {
  8989. $properties = get_class_vars( $obj );
  8990. }
  8991. else {
  8992. $properties = get_object_vars( $obj );
  8993. }
  8994. return array_key_exists( $property, $properties );
  8995. }
  8996. /**
  8997. * Converts an object into an associative array
  8998. *
  8999. * This function converts an object into an associative array by iterating
  9000. * over its public properties. Because this function uses the foreach
  9001. * construct, Iterators are respected. It works recursively on arrays of objects.
  9002. * Arrays and simple values are returned as is.
  9003. *
  9004. * If class has magic properties, it can implement IteratorAggregate
  9005. * and return all available properties in getIterator()
  9006. *
  9007. * @param mixed $var
  9008. * @return array
  9009. */
  9010. function convert_to_array($var) {
  9011. $result = array();
  9012. $references = array();
  9013. // loop over elements/properties
  9014. foreach ($var as $key => $value) {
  9015. // recursively convert objects
  9016. if (is_object($value) || is_array($value)) {
  9017. // but prevent cycles
  9018. if (!in_array($value, $references)) {
  9019. $result[$key] = convert_to_array($value);
  9020. $references[] = $value;
  9021. }
  9022. } else {
  9023. // simple values are untouched
  9024. $result[$key] = $value;
  9025. }
  9026. }
  9027. return $result;
  9028. }
  9029. /**
  9030. * Detect a custom script replacement in the data directory that will
  9031. * replace an existing moodle script
  9032. *
  9033. * @return string|bool full path name if a custom script exists, false if no custom script exists
  9034. */
  9035. function custom_script_path() {
  9036. global $CFG, $SCRIPT;
  9037. if ($SCRIPT === null) {
  9038. // Probably some weird external script
  9039. return false;
  9040. }
  9041. $scriptpath = $CFG->customscripts . $SCRIPT;
  9042. // check the custom script exists
  9043. if (file_exists($scriptpath) and is_file($scriptpath)) {
  9044. return $scriptpath;
  9045. } else {
  9046. return false;
  9047. }
  9048. }
  9049. /**
  9050. * Returns whether or not the user object is a remote MNET user. This function
  9051. * is in moodlelib because it does not rely on loading any of the MNET code.
  9052. *
  9053. * @global object
  9054. * @param object $user A valid user object
  9055. * @return bool True if the user is from a remote Moodle.
  9056. */
  9057. function is_mnet_remote_user($user) {
  9058. global $CFG;
  9059. if (!isset($CFG->mnet_localhost_id)) {
  9060. include_once $CFG->dirroot . '/mnet/lib.php';
  9061. $env = new mnet_environment();
  9062. $env->init();
  9063. unset($env);
  9064. }
  9065. return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
  9066. }
  9067. /**
  9068. * This function will search for browser prefereed languages, setting Moodle
  9069. * to use the best one available if $SESSION->lang is undefined
  9070. *
  9071. * @global object
  9072. * @global object
  9073. * @global object
  9074. */
  9075. function setup_lang_from_browser() {
  9076. global $CFG, $SESSION, $USER;
  9077. if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
  9078. // Lang is defined in session or user profile, nothing to do
  9079. return;
  9080. }
  9081. if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
  9082. return;
  9083. }
  9084. /// Extract and clean langs from headers
  9085. $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  9086. $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
  9087. $rawlangs = explode(',', $rawlangs); // Convert to array
  9088. $langs = array();
  9089. $order = 1.0;
  9090. foreach ($rawlangs as $lang) {
  9091. if (strpos($lang, ';') === false) {
  9092. $langs[(string)$order] = $lang;
  9093. $order = $order-0.01;
  9094. } else {
  9095. $parts = explode(';', $lang);
  9096. $pos = strpos($parts[1], '=');
  9097. $langs[substr($parts[1], $pos+1)] = $parts[0];
  9098. }
  9099. }
  9100. krsort($langs, SORT_NUMERIC);
  9101. /// Look for such langs under standard locations
  9102. foreach ($langs as $lang) {
  9103. $lang = strtolower(clean_param($lang, PARAM_SAFEDIR)); // clean it properly for include
  9104. if (get_string_manager()->translation_exists($lang, false)) {
  9105. $SESSION->lang = $lang; /// Lang exists, set it in session
  9106. break; /// We have finished. Go out
  9107. }
  9108. }
  9109. return;
  9110. }
  9111. /**
  9112. * check if $url matches anything in proxybypass list
  9113. *
  9114. * any errors just result in the proxy being used (least bad)
  9115. *
  9116. * @global object
  9117. * @param string $url url to check
  9118. * @return boolean true if we should bypass the proxy
  9119. */
  9120. function is_proxybypass( $url ) {
  9121. global $CFG;
  9122. // sanity check
  9123. if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
  9124. return false;
  9125. }
  9126. // get the host part out of the url
  9127. if (!$host = parse_url( $url, PHP_URL_HOST )) {
  9128. return false;
  9129. }
  9130. // get the possible bypass hosts into an array
  9131. $matches = explode( ',', $CFG->proxybypass );
  9132. // check for a match
  9133. // (IPs need to match the left hand side and hosts the right of the url,
  9134. // but we can recklessly check both as there can't be a false +ve)
  9135. $bypass = false;
  9136. foreach ($matches as $match) {
  9137. $match = trim($match);
  9138. // try for IP match (Left side)
  9139. $lhs = substr($host,0,strlen($match));
  9140. if (strcasecmp($match,$lhs)==0) {
  9141. return true;
  9142. }
  9143. // try for host match (Right side)
  9144. $rhs = substr($host,-strlen($match));
  9145. if (strcasecmp($match,$rhs)==0) {
  9146. return true;
  9147. }
  9148. }
  9149. // nothing matched.
  9150. return false;
  9151. }
  9152. ////////////////////////////////////////////////////////////////////////////////
  9153. /**
  9154. * Check if the passed navigation is of the new style
  9155. *
  9156. * @param mixed $navigation
  9157. * @return bool true for yes false for no
  9158. */
  9159. function is_newnav($navigation) {
  9160. if (is_array($navigation) && !empty($navigation['newnav'])) {
  9161. return true;
  9162. } else {
  9163. return false;
  9164. }
  9165. }
  9166. /**
  9167. * Checks whether the given variable name is defined as a variable within the given object.
  9168. *
  9169. * This will NOT work with stdClass objects, which have no class variables.
  9170. *
  9171. * @param string $var The variable name
  9172. * @param object $object The object to check
  9173. * @return boolean
  9174. */
  9175. function in_object_vars($var, $object) {
  9176. $class_vars = get_class_vars(get_class($object));
  9177. $class_vars = array_keys($class_vars);
  9178. return in_array($var, $class_vars);
  9179. }
  9180. /**
  9181. * Returns an array without repeated objects.
  9182. * This function is similar to array_unique, but for arrays that have objects as values
  9183. *
  9184. * @param array $array
  9185. * @param bool $keep_key_assoc
  9186. * @return array
  9187. */
  9188. function object_array_unique($array, $keep_key_assoc = true) {
  9189. $duplicate_keys = array();
  9190. $tmp = array();
  9191. foreach ($array as $key=>$val) {
  9192. // convert objects to arrays, in_array() does not support objects
  9193. if (is_object($val)) {
  9194. $val = (array)$val;
  9195. }
  9196. if (!in_array($val, $tmp)) {
  9197. $tmp[] = $val;
  9198. } else {
  9199. $duplicate_keys[] = $key;
  9200. }
  9201. }
  9202. foreach ($duplicate_keys as $key) {
  9203. unset($array[$key]);
  9204. }
  9205. return $keep_key_assoc ? $array : array_values($array);
  9206. }
  9207. /**
  9208. * Is a userid the primary administrator?
  9209. *
  9210. * @param int $userid int id of user to check
  9211. * @return boolean
  9212. */
  9213. function is_primary_admin($userid){
  9214. $primaryadmin = get_admin();
  9215. if($userid == $primaryadmin->id){
  9216. return true;
  9217. }else{
  9218. return false;
  9219. }
  9220. }
  9221. /**
  9222. * Returns the site identifier
  9223. *
  9224. * @global object
  9225. * @return string $CFG->siteidentifier, first making sure it is properly initialised.
  9226. */
  9227. function get_site_identifier() {
  9228. global $CFG;
  9229. // Check to see if it is missing. If so, initialise it.
  9230. if (empty($CFG->siteidentifier)) {
  9231. set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
  9232. }
  9233. // Return it.
  9234. return $CFG->siteidentifier;
  9235. }
  9236. /**
  9237. * Check whether the given password has no more than the specified
  9238. * number of consecutive identical characters.
  9239. *
  9240. * @param string $password password to be checked against the password policy
  9241. * @param integer $maxchars maximum number of consecutive identical characters
  9242. */
  9243. function check_consecutive_identical_characters($password, $maxchars) {
  9244. if ($maxchars < 1) {
  9245. return true; // 0 is to disable this check
  9246. }
  9247. if (strlen($password) <= $maxchars) {
  9248. return true; // too short to fail this test
  9249. }
  9250. $previouschar = '';
  9251. $consecutivecount = 1;
  9252. foreach (str_split($password) as $char) {
  9253. if ($char != $previouschar) {
  9254. $consecutivecount = 1;
  9255. }
  9256. else {
  9257. $consecutivecount++;
  9258. if ($consecutivecount > $maxchars) {
  9259. return false; // check failed already
  9260. }
  9261. }
  9262. $previouschar = $char;
  9263. }
  9264. return true;
  9265. }
  9266. /**
  9267. * helper function to do partial function binding
  9268. * so we can use it for preg_replace_callback, for example
  9269. * this works with php functions, user functions, static methods and class methods
  9270. * it returns you a callback that you can pass on like so:
  9271. *
  9272. * $callback = partial('somefunction', $arg1, $arg2);
  9273. * or
  9274. * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
  9275. * or even
  9276. * $obj = new someclass();
  9277. * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
  9278. *
  9279. * and then the arguments that are passed through at calltime are appended to the argument list.
  9280. *
  9281. * @param mixed $function a php callback
  9282. * $param mixed $arg1.. $argv arguments to partially bind with
  9283. *
  9284. * @return callback
  9285. */
  9286. function partial() {
  9287. if (!class_exists('partial')) {
  9288. class partial{
  9289. var $values = array();
  9290. var $func;
  9291. function __construct($func, $args) {
  9292. $this->values = $args;
  9293. $this->func = $func;
  9294. }
  9295. function method() {
  9296. $args = func_get_args();
  9297. return call_user_func_array($this->func, array_merge($this->values, $args));
  9298. }
  9299. }
  9300. }
  9301. $args = func_get_args();
  9302. $func = array_shift($args);
  9303. $p = new partial($func, $args);
  9304. return array($p, 'method');
  9305. }
  9306. /**
  9307. * helper function to load up and initialise the mnet environment
  9308. * this must be called before you use mnet functions.
  9309. *
  9310. * @return mnet_environment the equivalent of old $MNET global
  9311. */
  9312. function get_mnet_environment() {
  9313. global $CFG;
  9314. require_once($CFG->dirroot . '/mnet/lib.php');
  9315. static $instance = null;
  9316. if (empty($instance)) {
  9317. $instance = new mnet_environment();
  9318. $instance->init();
  9319. }
  9320. return $instance;
  9321. }
  9322. /**
  9323. * during xmlrpc server code execution, any code wishing to access
  9324. * information about the remote peer must use this to get it.
  9325. *
  9326. * @return mnet_remote_client the equivalent of old $MNET_REMOTE_CLIENT global
  9327. */
  9328. function get_mnet_remote_client() {
  9329. if (!defined('MNET_SERVER')) {
  9330. debugging(get_string('notinxmlrpcserver', 'mnet'));
  9331. return false;
  9332. }
  9333. global $MNET_REMOTE_CLIENT;
  9334. if (isset($MNET_REMOTE_CLIENT)) {
  9335. return $MNET_REMOTE_CLIENT;
  9336. }
  9337. return false;
  9338. }
  9339. /**
  9340. * during the xmlrpc server code execution, this will be called
  9341. * to setup the object returned by {@see get_mnet_remote_client}
  9342. *
  9343. * @param mnet_remote_client $client the client to set up
  9344. */
  9345. function set_mnet_remote_client($client) {
  9346. if (!defined('MNET_SERVER')) {
  9347. throw new moodle_exception('notinxmlrpcserver', 'mnet');
  9348. }
  9349. global $MNET_REMOTE_CLIENT;
  9350. $MNET_REMOTE_CLIENT = $client;
  9351. }
  9352. /**
  9353. * return the jump url for a given remote user
  9354. * this is used for rewriting forum post links in emails, etc
  9355. *
  9356. * @param stdclass $user the user to get the idp url for
  9357. */
  9358. function mnet_get_idp_jump_url($user) {
  9359. global $CFG;
  9360. static $mnetjumps = array();
  9361. if (!array_key_exists($user->mnethostid, $mnetjumps)) {
  9362. $idp = mnet_get_peer_host($user->mnethostid);
  9363. $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
  9364. $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
  9365. }
  9366. return $mnetjumps[$user->mnethostid];
  9367. }
  9368. /**
  9369. * Gets the homepage to use for the current user
  9370. *
  9371. * @return int One of HOMEPAGE_*
  9372. */
  9373. function get_home_page() {
  9374. global $CFG;
  9375. if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
  9376. if ($CFG->defaulthomepage == HOMEPAGE_MY) {
  9377. return HOMEPAGE_MY;
  9378. } else {
  9379. return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
  9380. }
  9381. }
  9382. return HOMEPAGE_SITE;
  9383. }
  9384. /**
  9385. * The lang_string class
  9386. *
  9387. * This special class is used to create an object representation of a string request.
  9388. * It is special because processing doesn't occur until the object is first used.
  9389. * The class was created especially to aid performance in areas where strings were
  9390. * required to be generated but were not necessarily used.
  9391. * As an example the admin tree when generated uses over 1500 strings, of which
  9392. * normally only 1/3 are ever actually printed at any time.
  9393. * The performance advantage is achieved by not actually processing strings that
  9394. * arn't being used, as such reducing the processing required for the page.
  9395. *
  9396. * How to use the lang_string class?
  9397. * There are two methods of using the lang_string class, first through the
  9398. * forth argument of the get_string function, and secondly directly.
  9399. * The following are examples of both.
  9400. * 1. Through get_string calls e.g.
  9401. * $string = get_string($identifier, $component, $a, true);
  9402. * $string = get_string('yes', 'moodle', null, true);
  9403. * 2. Direct instantiation
  9404. * $string = new lang_string($identifier, $component, $a, $lang);
  9405. * $string = new lang_string('yes');
  9406. *
  9407. * How do I use a lang_string object?
  9408. * The lang_string object makes use of a magic __toString method so that you
  9409. * are able to use the object exactly as you would use a string in most cases.
  9410. * This means you are able to collect it into a variable and then directly
  9411. * echo it, or concatenate it into another string, or similar.
  9412. * The other thing you can do is manually get the string by calling the
  9413. * lang_strings out method e.g.
  9414. * $string = new lang_string('yes');
  9415. * $string->out();
  9416. * Also worth noting is that the out method can take one argument, $lang which
  9417. * allows the developer to change the language on the fly.
  9418. *
  9419. * When should I use a lang_string object?
  9420. * The lang_string object is designed to be used in any situation where a
  9421. * string may not be needed, but needs to be generated.
  9422. * The admin tree is a good example of where lang_string objects should be
  9423. * used.
  9424. * A more practical example would be any class that requries strings that may
  9425. * not be printed (after all classes get renderer by renderers and who knows
  9426. * what they will do ;))
  9427. *
  9428. * When should I not use a lang_string object?
  9429. * Don't use lang_strings when you are going to use a string immediately.
  9430. * There is no need as it will be processed immediately and there will be no
  9431. * advantage, and in fact perhaps a negative hit as a class has to be
  9432. * instantiated for a lang_string object, however get_string won't require
  9433. * that.
  9434. *
  9435. * Limitations:
  9436. * 1. You cannot use a lang_string object as an array offset. Doing so will
  9437. * result in PHP throwing an error. (You can use it as an object property!)
  9438. *
  9439. * @package core
  9440. * @category string
  9441. * @copyright 2011 Sam Hemelryk
  9442. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  9443. */
  9444. class lang_string {
  9445. /** @var string The strings identifier */
  9446. protected $identifier;
  9447. /** @var string The strings component. Default '' */
  9448. protected $component = '';
  9449. /** @var array|stdClass Any arguments required for the string. Default null */
  9450. protected $a = null;
  9451. /** @var string The language to use when processing the string. Default null */
  9452. protected $lang = null;
  9453. /** @var string The processed string (once processed) */
  9454. protected $string = null;
  9455. /**
  9456. * A special boolean. If set to true then the object has been woken up and
  9457. * cannot be regenerated. If this is set then $this->string MUST be used.
  9458. * @var bool
  9459. */
  9460. protected $forcedstring = false;
  9461. /**
  9462. * Constructs a lang_string object
  9463. *
  9464. * This function should do as little processing as possible to ensure the best
  9465. * performance for strings that won't be used.
  9466. *
  9467. * @param string $identifier The strings identifier
  9468. * @param string $component The strings component
  9469. * @param stdClass|array $a Any arguments the string requires
  9470. * @param string $lang The language to use when processing the string.
  9471. */
  9472. public function __construct($identifier, $component = '', $a = null, $lang = null) {
  9473. if (empty($component)) {
  9474. $component = 'moodle';
  9475. }
  9476. $this->identifier = $identifier;
  9477. $this->component = $component;
  9478. $this->lang = $lang;
  9479. // We MUST duplicate $a to ensure that it if it changes by reference those
  9480. // changes are not carried across.
  9481. // To do this we always ensure $a or its properties/values are strings
  9482. // and that any properties/values that arn't convertable are forgotten.
  9483. if (!empty($a)) {
  9484. if (is_scalar($a)) {
  9485. $this->a = $a;
  9486. } else if ($a instanceof lang_string) {
  9487. $this->a = $a->out();
  9488. } else if (is_object($a) or is_array($a)) {
  9489. $a = (array)$a;
  9490. $this->a = array();
  9491. foreach ($a as $key => $value) {
  9492. // Make sure conversion errors don't get displayed (results in '')
  9493. if (is_array($value)) {
  9494. $this->a[$key] = '';
  9495. } else if (is_object($value)) {
  9496. if (method_exists($value, '__toString')) {
  9497. $this->a[$key] = $value->__toString();
  9498. } else {
  9499. $this->a[$key] = '';
  9500. }
  9501. } else {
  9502. $this->a[$key] = (string)$value;
  9503. }
  9504. }
  9505. }
  9506. }
  9507. if (debugging(false, DEBUG_DEVELOPER)) {
  9508. if (clean_param($this->identifier, PARAM_STRINGID) == '') {
  9509. throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
  9510. }
  9511. if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
  9512. throw new coding_exception('Invalid string compontent. Please check your string definition');
  9513. }
  9514. if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
  9515. debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
  9516. }
  9517. }
  9518. }
  9519. /**
  9520. * Processes the string.
  9521. *
  9522. * This function actually processes the string, stores it in the string property
  9523. * and then returns it.
  9524. * You will notice that this function is VERY similar to the get_string method.
  9525. * That is because it is pretty much doing the same thing.
  9526. * However as this function is an upgrade it isn't as tolerant to backwards
  9527. * compatability.
  9528. *
  9529. * @return string
  9530. */
  9531. protected function get_string() {
  9532. global $CFG;
  9533. // Check if we need to process the string
  9534. if ($this->string === null) {
  9535. // Check the quality of the identifier.
  9536. if (clean_param($this->identifier, PARAM_STRINGID) == '') {
  9537. throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
  9538. }
  9539. // Process the string
  9540. $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
  9541. // Debugging feature lets you display string identifier and component
  9542. if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
  9543. $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
  9544. }
  9545. }
  9546. // Return the string
  9547. return $this->string;
  9548. }
  9549. /**
  9550. * Returns the string
  9551. *
  9552. * @param string $lang The langauge to use when processing the string
  9553. * @return string
  9554. */
  9555. public function out($lang = null) {
  9556. if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
  9557. if ($this->forcedstring) {
  9558. debugging('lang_string objects that have been serialised and unserialised cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
  9559. return $this->get_string();
  9560. }
  9561. $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
  9562. return $translatedstring->out();
  9563. }
  9564. return $this->get_string();
  9565. }
  9566. /**
  9567. * Magic __toString method for printing a string
  9568. *
  9569. * @return string
  9570. */
  9571. public function __toString() {
  9572. return $this->get_string();
  9573. }
  9574. /**
  9575. * Magic __set_state method used for var_export
  9576. *
  9577. * @return string
  9578. */
  9579. public function __set_state() {
  9580. return $this->get_string();
  9581. }
  9582. /**
  9583. * Prepares the lang_string for sleep and stores only the forcedstring and
  9584. * string properties... the string cannot be regenerated so we need to ensure
  9585. * it is generated for this.
  9586. *
  9587. * @return string
  9588. */
  9589. public function __sleep() {
  9590. $this->get_string();
  9591. $this->forcedstring = true;
  9592. return array('forcedstring', 'string', 'lang');
  9593. }
  9594. }