PageRenderTime 105ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 2ms

/moodle/lib/moodlelib.php

https://bitbucket.org/geek745/moodle-db2
PHP | 8514 lines | 5198 code | 1188 blank | 2128 comment | 1245 complexity | 78baf64e4ba00bd69d4399c9fed7842c MD5 | raw file
Possible License(s): GPL-2.0, LGPL-2.1, BSD-3-Clause, LGPL-2.0
  1. <?php // $Id$
  2. ///////////////////////////////////////////////////////////////////////////
  3. // //
  4. // NOTICE OF COPYRIGHT //
  5. // //
  6. // Moodle - Modular Object-Oriented Dynamic Learning Environment //
  7. // http://moodle.org //
  8. // //
  9. // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
  10. // //
  11. // This program is free software; you can redistribute it and/or modify //
  12. // it under the terms of the GNU General Public License as published by //
  13. // the Free Software Foundation; either version 2 of the License, or //
  14. // (at your option) any later version. //
  15. // //
  16. // This program is distributed in the hope that it will be useful, //
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of //
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
  19. // GNU General Public License for more details: //
  20. // //
  21. // http://www.gnu.org/copyleft/gpl.html //
  22. // //
  23. ///////////////////////////////////////////////////////////////////////////
  24. /**
  25. * moodlelib.php - Moodle main library
  26. *
  27. * Main library file of miscellaneous general-purpose Moodle functions.
  28. * Other main libraries:
  29. * - weblib.php - functions that produce web output
  30. * - datalib.php - functions that access the database
  31. * @author Martin Dougiamas
  32. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  33. * @package moodlecore
  34. */
  35. /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
  36. /**
  37. * Used by some scripts to check they are being called by Moodle
  38. */
  39. define('MOODLE_INTERNAL', true);
  40. /// Date and time constants ///
  41. /**
  42. * Time constant - the number of seconds in a year
  43. */
  44. define('YEARSECS', 31536000);
  45. /**
  46. * Time constant - the number of seconds in a week
  47. */
  48. define('WEEKSECS', 604800);
  49. /**
  50. * Time constant - the number of seconds in a day
  51. */
  52. define('DAYSECS', 86400);
  53. /**
  54. * Time constant - the number of seconds in an hour
  55. */
  56. define('HOURSECS', 3600);
  57. /**
  58. * Time constant - the number of seconds in a minute
  59. */
  60. define('MINSECS', 60);
  61. /**
  62. * Time constant - the number of minutes in a day
  63. */
  64. define('DAYMINS', 1440);
  65. /**
  66. * Time constant - the number of minutes in an hour
  67. */
  68. define('HOURMINS', 60);
  69. /// Parameter constants - every call to optional_param(), required_param() ///
  70. /// or clean_param() should have a specified type of parameter. //////////////
  71. /**
  72. * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
  73. * originally was 0, but changed because we need to detect unknown
  74. * parameter types and swiched order in clean_param().
  75. */
  76. define('PARAM_RAW', 666);
  77. /**
  78. * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
  79. * It was one of the first types, that is why it is abused so much ;-)
  80. */
  81. define('PARAM_CLEAN', 0x0001);
  82. /**
  83. * PARAM_INT - integers only, use when expecting only numbers.
  84. */
  85. define('PARAM_INT', 0x0002);
  86. /**
  87. * PARAM_INTEGER - an alias for PARAM_INT
  88. */
  89. define('PARAM_INTEGER', 0x0002);
  90. /**
  91. * PARAM_NUMBER - a real/floating point number.
  92. */
  93. define('PARAM_NUMBER', 0x000a);
  94. /**
  95. * PARAM_ALPHA - contains only english letters.
  96. */
  97. define('PARAM_ALPHA', 0x0004);
  98. /**
  99. * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
  100. * @TODO: should we alias it to PARAM_ALPHANUM ?
  101. */
  102. define('PARAM_ACTION', 0x0004);
  103. /**
  104. * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
  105. * @TODO: should we alias it to PARAM_ALPHANUM ?
  106. */
  107. define('PARAM_FORMAT', 0x0004);
  108. /**
  109. * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
  110. */
  111. define('PARAM_NOTAGS', 0x0008);
  112. /**
  113. * PARAM_MULTILANG - alias of PARAM_TEXT.
  114. */
  115. define('PARAM_MULTILANG', 0x0009);
  116. /**
  117. * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
  118. */
  119. define('PARAM_TEXT', 0x0009);
  120. /**
  121. * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
  122. */
  123. define('PARAM_FILE', 0x0010);
  124. /**
  125. * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international alphanumeric with spaces
  126. */
  127. define('PARAM_TAG', 0x0011);
  128. /**
  129. * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
  130. */
  131. define('PARAM_TAGLIST', 0x0012);
  132. /**
  133. * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
  134. * note: the leading slash is not removed, window drive letter is not allowed
  135. */
  136. define('PARAM_PATH', 0x0020);
  137. /**
  138. * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
  139. */
  140. define('PARAM_HOST', 0x0040);
  141. /**
  142. * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not acceppted but http://localhost.localdomain/ is ok.
  143. */
  144. define('PARAM_URL', 0x0080);
  145. /**
  146. * 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!)
  147. */
  148. define('PARAM_LOCALURL', 0x0180);
  149. /**
  150. * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
  151. * use when you want to store a new file submitted by students
  152. */
  153. define('PARAM_CLEANFILE',0x0200);
  154. /**
  155. * PARAM_ALPHANUM - expected numbers and letters only.
  156. */
  157. define('PARAM_ALPHANUM', 0x0400);
  158. /**
  159. * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
  160. */
  161. define('PARAM_BOOL', 0x0800);
  162. /**
  163. * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
  164. * note: do not forget to addslashes() before storing into database!
  165. */
  166. define('PARAM_CLEANHTML',0x1000);
  167. /**
  168. * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
  169. * suitable for include() and require()
  170. * @TODO: should we rename this function to PARAM_SAFEDIRS??
  171. */
  172. define('PARAM_ALPHAEXT', 0x2000);
  173. /**
  174. * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
  175. */
  176. define('PARAM_SAFEDIR', 0x4000);
  177. /**
  178. * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
  179. */
  180. define('PARAM_SEQUENCE', 0x8000);
  181. /**
  182. * PARAM_PEM - Privacy Enhanced Mail format
  183. */
  184. define('PARAM_PEM', 0x10000);
  185. /**
  186. * PARAM_BASE64 - Base 64 encoded format
  187. */
  188. define('PARAM_BASE64', 0x20000);
  189. /// Page types ///
  190. /**
  191. * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
  192. */
  193. define('PAGE_COURSE_VIEW', 'course-view');
  194. /// Debug levels ///
  195. /** no warnings at all */
  196. define ('DEBUG_NONE', 0);
  197. /** E_ERROR | E_PARSE */
  198. define ('DEBUG_MINIMAL', 5);
  199. /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
  200. define ('DEBUG_NORMAL', 15);
  201. /** E_ALL without E_STRICT for now, do show recoverable fatal errors */
  202. define ('DEBUG_ALL', 6143);
  203. /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
  204. define ('DEBUG_DEVELOPER', 38911);
  205. /**
  206. * Blog access level constant declaration
  207. */
  208. define ('BLOG_USER_LEVEL', 1);
  209. define ('BLOG_GROUP_LEVEL', 2);
  210. define ('BLOG_COURSE_LEVEL', 3);
  211. define ('BLOG_SITE_LEVEL', 4);
  212. define ('BLOG_GLOBAL_LEVEL', 5);
  213. /**
  214. * Tag constanst
  215. */
  216. //To prevent problems with multibytes strings, this should not exceed the
  217. //length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
  218. define('TAG_MAX_LENGTH', 50);
  219. /**
  220. * Password policy constants
  221. */
  222. define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
  223. define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
  224. define ('PASSWORD_DIGITS', '0123456789');
  225. define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
  226. if (!defined('SORT_LOCALE_STRING')) { // PHP < 4.4.0 - TODO: remove in 2.0
  227. define('SORT_LOCALE_STRING', SORT_STRING);
  228. }
  229. /// PARAMETER HANDLING ////////////////////////////////////////////////////
  230. /**
  231. * Returns a particular value for the named variable, taken from
  232. * POST or GET. If the parameter doesn't exist then an error is
  233. * thrown because we require this variable.
  234. *
  235. * This function should be used to initialise all required values
  236. * in a script that are based on parameters. Usually it will be
  237. * used like this:
  238. * $id = required_param('id');
  239. *
  240. * @param string $parname the name of the page parameter we want
  241. * @param int $type expected type of parameter
  242. * @return mixed
  243. */
  244. function required_param($parname, $type=PARAM_CLEAN) {
  245. // detect_unchecked_vars addition
  246. global $CFG;
  247. if (!empty($CFG->detect_unchecked_vars)) {
  248. global $UNCHECKED_VARS;
  249. unset ($UNCHECKED_VARS->vars[$parname]);
  250. }
  251. if (isset($_POST[$parname])) { // POST has precedence
  252. $param = $_POST[$parname];
  253. } else if (isset($_GET[$parname])) {
  254. $param = $_GET[$parname];
  255. } else {
  256. error('A required parameter ('.$parname.') was missing');
  257. }
  258. return clean_param($param, $type);
  259. }
  260. /**
  261. * Returns a particular value for the named variable, taken from
  262. * POST or GET, otherwise returning a given default.
  263. *
  264. * This function should be used to initialise all optional values
  265. * in a script that are based on parameters. Usually it will be
  266. * used like this:
  267. * $name = optional_param('name', 'Fred');
  268. *
  269. * @param string $parname the name of the page parameter we want
  270. * @param mixed $default the default value to return if nothing is found
  271. * @param int $type expected type of parameter
  272. * @return mixed
  273. */
  274. function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
  275. // detect_unchecked_vars addition
  276. global $CFG;
  277. if (!empty($CFG->detect_unchecked_vars)) {
  278. global $UNCHECKED_VARS;
  279. unset ($UNCHECKED_VARS->vars[$parname]);
  280. }
  281. if (isset($_POST[$parname])) { // POST has precedence
  282. $param = $_POST[$parname];
  283. } else if (isset($_GET[$parname])) {
  284. $param = $_GET[$parname];
  285. } else {
  286. return $default;
  287. }
  288. return clean_param($param, $type);
  289. }
  290. /**
  291. * Used by {@link optional_param()} and {@link required_param()} to
  292. * clean the variables and/or cast to specific types, based on
  293. * an options field.
  294. * <code>
  295. * $course->format = clean_param($course->format, PARAM_ALPHA);
  296. * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
  297. * </code>
  298. *
  299. * @uses $CFG
  300. * @uses PARAM_RAW
  301. * @uses PARAM_CLEAN
  302. * @uses PARAM_CLEANHTML
  303. * @uses PARAM_INT
  304. * @uses PARAM_NUMBER
  305. * @uses PARAM_ALPHA
  306. * @uses PARAM_ALPHANUM
  307. * @uses PARAM_ALPHAEXT
  308. * @uses PARAM_SEQUENCE
  309. * @uses PARAM_BOOL
  310. * @uses PARAM_NOTAGS
  311. * @uses PARAM_TEXT
  312. * @uses PARAM_SAFEDIR
  313. * @uses PARAM_CLEANFILE
  314. * @uses PARAM_FILE
  315. * @uses PARAM_PATH
  316. * @uses PARAM_HOST
  317. * @uses PARAM_URL
  318. * @uses PARAM_LOCALURL
  319. * @uses PARAM_PEM
  320. * @uses PARAM_BASE64
  321. * @uses PARAM_TAG
  322. * @uses PARAM_SEQUENCE
  323. * @param mixed $param the variable we are cleaning
  324. * @param int $type expected format of param after cleaning.
  325. * @return mixed
  326. */
  327. function clean_param($param, $type) {
  328. global $CFG;
  329. if (is_array($param)) { // Let's loop
  330. $newparam = array();
  331. foreach ($param as $key => $value) {
  332. $newparam[$key] = clean_param($value, $type);
  333. }
  334. return $newparam;
  335. }
  336. switch ($type) {
  337. case PARAM_RAW: // no cleaning at all
  338. return $param;
  339. case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
  340. if (is_numeric($param)) {
  341. return $param;
  342. }
  343. $param = stripslashes($param); // Needed for kses to work fine
  344. $param = clean_text($param); // Sweep for scripts, etc
  345. return addslashes($param); // Restore original request parameter slashes
  346. case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
  347. $param = stripslashes($param); // Remove any slashes
  348. $param = clean_text($param); // Sweep for scripts, etc
  349. return trim($param);
  350. case PARAM_INT:
  351. return (int)$param; // Convert to integer
  352. case PARAM_NUMBER:
  353. return (float)$param; // Convert to integer
  354. case PARAM_ALPHA: // Remove everything not a-z
  355. return eregi_replace('[^a-zA-Z]', '', $param);
  356. case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
  357. return eregi_replace('[^A-Za-z0-9]', '', $param);
  358. case PARAM_ALPHAEXT: // Remove everything not a-zA-Z/_-
  359. return eregi_replace('[^a-zA-Z/_-]', '', $param);
  360. case PARAM_SEQUENCE: // Remove everything not 0-9,
  361. return eregi_replace('[^0-9,]', '', $param);
  362. case PARAM_BOOL: // Convert to 1 or 0
  363. $tempstr = strtolower($param);
  364. if ($tempstr == 'on' or $tempstr == 'yes' ) {
  365. $param = 1;
  366. } else if ($tempstr == 'off' or $tempstr == 'no') {
  367. $param = 0;
  368. } else {
  369. $param = empty($param) ? 0 : 1;
  370. }
  371. return $param;
  372. case PARAM_NOTAGS: // Strip all tags
  373. return strip_tags($param);
  374. case PARAM_TEXT: // leave only tags needed for multilang
  375. return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
  376. case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
  377. return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
  378. case PARAM_CLEANFILE: // allow only safe characters
  379. return clean_filename($param);
  380. case PARAM_FILE: // Strip all suspicious characters from filename
  381. $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
  382. $param = ereg_replace('\.\.+', '', $param);
  383. if($param == '.') {
  384. $param = '';
  385. }
  386. return $param;
  387. case PARAM_PATH: // Strip all suspicious characters from file path
  388. $param = str_replace('\\\'', '\'', $param);
  389. $param = str_replace('\\"', '"', $param);
  390. $param = str_replace('\\', '/', $param);
  391. $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
  392. $param = ereg_replace('\.\.+', '', $param);
  393. $param = ereg_replace('//+', '/', $param);
  394. return ereg_replace('/(\./)+', '/', $param);
  395. case PARAM_HOST: // allow FQDN or IPv4 dotted quad
  396. $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
  397. // match ipv4 dotted quad
  398. if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
  399. // confirm values are ok
  400. if ( $match[0] > 255
  401. || $match[1] > 255
  402. || $match[3] > 255
  403. || $match[4] > 255 ) {
  404. // hmmm, what kind of dotted quad is this?
  405. $param = '';
  406. }
  407. } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
  408. && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
  409. && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
  410. ) {
  411. // all is ok - $param is respected
  412. } else {
  413. // all is not ok...
  414. $param='';
  415. }
  416. return $param;
  417. case PARAM_URL: // allow safe ftp, http, mailto urls
  418. include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
  419. if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
  420. // all is ok, param is respected
  421. } else {
  422. $param =''; // not really ok
  423. }
  424. return $param;
  425. case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
  426. $param = clean_param($param, PARAM_URL);
  427. if (!empty($param)) {
  428. if (preg_match(':^/:', $param)) {
  429. // root-relative, ok!
  430. } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
  431. // absolute, and matches our wwwroot
  432. } else {
  433. // relative - let's make sure there are no tricks
  434. if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
  435. // looks ok.
  436. } else {
  437. $param = '';
  438. }
  439. }
  440. }
  441. return $param;
  442. case PARAM_PEM:
  443. $param = trim($param);
  444. // PEM formatted strings may contain letters/numbers and the symbols
  445. // forward slash: /
  446. // plus sign: +
  447. // equal sign: =
  448. // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
  449. if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
  450. list($wholething, $body) = $matches;
  451. unset($wholething, $matches);
  452. $b64 = clean_param($body, PARAM_BASE64);
  453. if (!empty($b64)) {
  454. return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
  455. } else {
  456. return '';
  457. }
  458. }
  459. return '';
  460. case PARAM_BASE64:
  461. if (!empty($param)) {
  462. // PEM formatted strings may contain letters/numbers and the symbols
  463. // forward slash: /
  464. // plus sign: +
  465. // equal sign: =
  466. if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
  467. return '';
  468. }
  469. $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
  470. // Each line of base64 encoded data must be 64 characters in
  471. // length, except for the last line which may be less than (or
  472. // equal to) 64 characters long.
  473. for ($i=0, $j=count($lines); $i < $j; $i++) {
  474. if ($i + 1 == $j) {
  475. if (64 < strlen($lines[$i])) {
  476. return '';
  477. }
  478. continue;
  479. }
  480. if (64 != strlen($lines[$i])) {
  481. return '';
  482. }
  483. }
  484. return implode("\n",$lines);
  485. } else {
  486. return '';
  487. }
  488. case PARAM_TAG:
  489. //as long as magic_quotes_gpc is used, a backslash will be a
  490. //problem, so remove *all* backslash.
  491. $param = str_replace('\\', '', $param);
  492. //convert many whitespace chars into one
  493. $param = preg_replace('/\s+/', ' ', $param);
  494. $textlib = textlib_get_instance();
  495. $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
  496. return $param;
  497. case PARAM_TAGLIST:
  498. $tags = explode(',', $param);
  499. $result = array();
  500. foreach ($tags as $tag) {
  501. $res = clean_param($tag, PARAM_TAG);
  502. if ($res != '') {
  503. $result[] = $res;
  504. }
  505. }
  506. if ($result) {
  507. return implode(',', $result);
  508. } else {
  509. return '';
  510. }
  511. default: // throw error, switched parameters in optional_param or another serious problem
  512. error("Unknown parameter type: $type");
  513. }
  514. }
  515. /**
  516. * Return true if given value is integer or string with integer value
  517. *
  518. * @param mixed $value String or Int
  519. * @return bool true if number, false if not
  520. */
  521. function is_number($value) {
  522. if (is_int($value)) {
  523. return true;
  524. } else if (is_string($value)) {
  525. return ((string)(int)$value) === $value;
  526. } else {
  527. return false;
  528. }
  529. }
  530. /**
  531. * This function is useful for testing whether something you got back from
  532. * the HTML editor actually contains anything. Sometimes the HTML editor
  533. * appear to be empty, but actually you get back a <br> tag or something.
  534. *
  535. * @param string $string a string containing HTML.
  536. * @return boolean does the string contain any actual content - that is text,
  537. * images, objcts, etc.
  538. */
  539. function html_is_blank($string) {
  540. return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
  541. }
  542. /**
  543. * Set a key in global configuration
  544. *
  545. * Set a key/value pair in both this session's {@link $CFG} global variable
  546. * and in the 'config' database table for future sessions.
  547. *
  548. * Can also be used to update keys for plugin-scoped configs in config_plugin table.
  549. * In that case it doesn't affect $CFG.
  550. *
  551. * A NULL value will delete the entry.
  552. *
  553. * @param string $name the key to set
  554. * @param string $value the value to set (without magic quotes)
  555. * @param string $plugin (optional) the plugin scope
  556. * @uses $CFG
  557. * @return bool
  558. */
  559. function set_config($name, $value, $plugin=NULL) {
  560. /// No need for get_config because they are usually always available in $CFG
  561. global $CFG;
  562. if (empty($plugin)) {
  563. if (!array_key_exists($name, $CFG->config_php_settings)) {
  564. // So it's defined for this invocation at least
  565. if (is_null($value)) {
  566. unset($CFG->$name);
  567. } else {
  568. $CFG->$name = (string)$value; // settings from db are always strings
  569. }
  570. }
  571. if (get_field('config', 'name', 'name', $name)) {
  572. if ($value===null) {
  573. return delete_records('config', 'name', $name);
  574. } else {
  575. return set_field('config', 'value', addslashes($value), 'name', $name);
  576. }
  577. } else {
  578. if ($value===null) {
  579. return true;
  580. }
  581. $config = new object();
  582. $config->name = $name;
  583. $config->value = addslashes($value);
  584. return insert_record('config', $config);
  585. }
  586. } else { // plugin scope
  587. if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
  588. if ($value===null) {
  589. return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
  590. } else {
  591. return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
  592. }
  593. } else {
  594. if ($value===null) {
  595. return true;
  596. }
  597. $config = new object();
  598. $config->plugin = addslashes($plugin);
  599. $config->name = $name;
  600. $config->value = addslashes($value);
  601. return insert_record('config_plugins', $config);
  602. }
  603. }
  604. }
  605. /**
  606. * Get configuration values from the global config table
  607. * or the config_plugins table.
  608. *
  609. * If called with no parameters it will do the right thing
  610. * generating $CFG safely from the database without overwriting
  611. * existing values.
  612. *
  613. * If called with 2 parameters it will return a $string single
  614. * value or false of the value is not found.
  615. *
  616. * @param string $plugin
  617. * @param string $name
  618. * @uses $CFG
  619. * @return hash-like object or single value
  620. *
  621. */
  622. function get_config($plugin=NULL, $name=NULL) {
  623. global $CFG;
  624. if (!empty($name)) { // the user is asking for a specific value
  625. if (!empty($plugin)) {
  626. return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
  627. } else {
  628. return get_field('config', 'value', 'name', $name);
  629. }
  630. }
  631. // the user is after a recordset
  632. if (!empty($plugin)) {
  633. if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
  634. $configs = (array)$configs;
  635. $localcfg = array();
  636. foreach ($configs as $config) {
  637. $localcfg[$config->name] = $config->value;
  638. }
  639. return (object)$localcfg;
  640. } else {
  641. return false;
  642. }
  643. } else {
  644. // this was originally in setup.php
  645. if ($configs = get_records('config')) {
  646. $localcfg = (array)$CFG;
  647. foreach ($configs as $config) {
  648. if (!isset($localcfg[$config->name])) {
  649. $localcfg[$config->name] = $config->value;
  650. }
  651. // do not complain anymore if config.php overrides settings from db
  652. }
  653. $localcfg = (object)$localcfg;
  654. return $localcfg;
  655. } else {
  656. // preserve $CFG if DB returns nothing or error
  657. return $CFG;
  658. }
  659. }
  660. }
  661. /**
  662. * Removes a key from global configuration
  663. *
  664. * @param string $name the key to set
  665. * @param string $plugin (optional) the plugin scope
  666. * @uses $CFG
  667. * @return bool
  668. */
  669. function unset_config($name, $plugin=NULL) {
  670. global $CFG;
  671. unset($CFG->$name);
  672. if (empty($plugin)) {
  673. return delete_records('config', 'name', $name);
  674. } else {
  675. return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
  676. }
  677. }
  678. /**
  679. * Get volatile flags
  680. *
  681. * @param string $type
  682. * @param int $changedsince
  683. * @return records array
  684. *
  685. */
  686. function get_cache_flags($type, $changedsince=NULL) {
  687. $type = addslashes($type);
  688. $sqlwhere = 'flagtype=\'' . $type . '\' AND expiry >= ' . time();
  689. if ($changedsince !== NULL) {
  690. $changedsince = (int)$changedsince;
  691. $sqlwhere .= ' AND timemodified > ' . $changedsince;
  692. }
  693. $cf = array();
  694. if ($flags=get_records_select('cache_flags', $sqlwhere, '', 'name,value')) {
  695. foreach ($flags as $flag) {
  696. $cf[$flag->name] = $flag->value;
  697. }
  698. }
  699. return $cf;
  700. }
  701. /**
  702. * Use this funciton to get a list of users from a config setting of type admin_setting_users_with_capability.
  703. * @param string $value the value of the config setting.
  704. * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
  705. * @return array of user objects.
  706. */
  707. function get_users_from_config($value, $capability) {
  708. global $CFG;
  709. if ($value == '$@ALL@$') {
  710. $users = get_users_by_capability(get_context_instance(CONTEXT_SYSTEM), $capability);
  711. } else if ($value) {
  712. $usernames = explode(',', $value);
  713. $users = get_records_select('user', "username IN ('" . implode("','", $usernames) . "') AND mnethostid = " . $CFG->mnet_localhost_id);
  714. } else {
  715. $users = array();
  716. }
  717. return $users;
  718. }
  719. /**
  720. * Get volatile flags
  721. *
  722. * @param string $type
  723. * @param string $name
  724. * @param int $changedsince
  725. * @return records array
  726. *
  727. */
  728. function get_cache_flag($type, $name, $changedsince=NULL) {
  729. $type = addslashes($type);
  730. $name = addslashes($name);
  731. $sqlwhere = 'flagtype=\'' . $type . '\' AND name=\'' . $name . '\' AND expiry >= ' . time();
  732. if ($changedsince !== NULL) {
  733. $changedsince = (int)$changedsince;
  734. $sqlwhere .= ' AND timemodified > ' . $changedsince;
  735. }
  736. return get_field_select('cache_flags', 'value', $sqlwhere);
  737. }
  738. /**
  739. * Set a volatile flag
  740. *
  741. * @param string $type the "type" namespace for the key
  742. * @param string $name the key to set
  743. * @param string $value the value to set (without magic quotes) - NULL will remove the flag
  744. * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
  745. * @return bool
  746. */
  747. function set_cache_flag($type, $name, $value, $expiry=NULL) {
  748. $timemodified = time();
  749. if ($expiry===NULL || $expiry < $timemodified) {
  750. $expiry = $timemodified + 24 * 60 * 60;
  751. } else {
  752. $expiry = (int)$expiry;
  753. }
  754. if ($value === NULL) {
  755. return unset_cache_flag($type,$name);
  756. }
  757. $type = addslashes($type);
  758. $name = addslashes($name);
  759. if ($f = get_record('cache_flags', 'name', $name, 'flagtype', $type)) { // this is a potentail problem in DEBUG_DEVELOPER
  760. if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
  761. return true; //no need to update; helps rcache too
  762. }
  763. $f->value = addslashes($value);
  764. $f->expiry = $expiry;
  765. $f->timemodified = $timemodified;
  766. return update_record('cache_flags', $f);
  767. } else {
  768. $f = new object();
  769. $f->flagtype = $type;
  770. $f->name = $name;
  771. $f->value = addslashes($value);
  772. $f->expiry = $expiry;
  773. $f->timemodified = $timemodified;
  774. return (bool)insert_record('cache_flags', $f);
  775. }
  776. }
  777. /**
  778. * Removes a single volatile flag
  779. *
  780. * @param string $type the "type" namespace for the key
  781. * @param string $name the key to set
  782. * @uses $CFG
  783. * @return bool
  784. */
  785. function unset_cache_flag($type, $name) {
  786. return delete_records('cache_flags',
  787. 'name', addslashes($name),
  788. 'flagtype', addslashes($type));
  789. }
  790. /**
  791. * Garbage-collect volatile flags
  792. *
  793. */
  794. function gc_cache_flags() {
  795. return delete_records_select('cache_flags', 'expiry < ' . time());
  796. }
  797. /**
  798. * Refresh current $USER session global variable with all their current preferences.
  799. * @uses $USER
  800. */
  801. function reload_user_preferences() {
  802. global $USER;
  803. //reset preference
  804. $USER->preference = array();
  805. if (!isloggedin() or isguestuser()) {
  806. // no permanent storage for not-logged-in user and guest
  807. } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
  808. foreach ($preferences as $preference) {
  809. $USER->preference[$preference->name] = $preference->value;
  810. }
  811. }
  812. return true;
  813. }
  814. /**
  815. * Sets a preference for the current user
  816. * Optionally, can set a preference for a different user object
  817. * @uses $USER
  818. * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
  819. * @param string $name The key to set as preference for the specified user
  820. * @param string $value The value to set forthe $name key in the specified user's record
  821. * @param int $otheruserid A moodle user ID
  822. * @return bool
  823. */
  824. function set_user_preference($name, $value, $otheruserid=NULL) {
  825. global $USER;
  826. if (!isset($USER->preference)) {
  827. reload_user_preferences();
  828. }
  829. if (empty($name)) {
  830. return false;
  831. }
  832. $nostore = false;
  833. if (empty($otheruserid)){
  834. if (!isloggedin() or isguestuser()) {
  835. $nostore = true;
  836. }
  837. $userid = $USER->id;
  838. } else {
  839. if (isguestuser($otheruserid)) {
  840. $nostore = true;
  841. }
  842. $userid = $otheruserid;
  843. }
  844. $return = true;
  845. if ($nostore) {
  846. // no permanent storage for not-logged-in user and guest
  847. } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
  848. if ($preference->value === $value) {
  849. return true;
  850. }
  851. if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
  852. $return = false;
  853. }
  854. } else {
  855. $preference = new object();
  856. $preference->userid = $userid;
  857. $preference->name = addslashes($name);
  858. $preference->value = addslashes((string)$value);
  859. if (!insert_record('user_preferences', $preference)) {
  860. $return = false;
  861. }
  862. }
  863. // update value in USER session if needed
  864. if ($userid == $USER->id) {
  865. $USER->preference[$name] = (string)$value;
  866. }
  867. return $return;
  868. }
  869. /**
  870. * Unsets a preference completely by deleting it from the database
  871. * Optionally, can set a preference for a different user id
  872. * @uses $USER
  873. * @param string $name The key to unset as preference for the specified user
  874. * @param int $otheruserid A moodle user ID
  875. */
  876. function unset_user_preference($name, $otheruserid=NULL) {
  877. global $USER;
  878. if (!isset($USER->preference)) {
  879. reload_user_preferences();
  880. }
  881. if (empty($otheruserid)){
  882. $userid = $USER->id;
  883. } else {
  884. $userid = $otheruserid;
  885. }
  886. //Delete the preference from $USER if needed
  887. if ($userid == $USER->id) {
  888. unset($USER->preference[$name]);
  889. }
  890. //Then from DB
  891. return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
  892. }
  893. /**
  894. * Sets a whole array of preferences for the current user
  895. * @param array $prefarray An array of key/value pairs to be set
  896. * @param int $otheruserid A moodle user ID
  897. * @return bool
  898. */
  899. function set_user_preferences($prefarray, $otheruserid=NULL) {
  900. if (!is_array($prefarray) or empty($prefarray)) {
  901. return false;
  902. }
  903. $return = true;
  904. foreach ($prefarray as $name => $value) {
  905. // The order is important; test for return is done first
  906. $return = (set_user_preference($name, $value, $otheruserid) && $return);
  907. }
  908. return $return;
  909. }
  910. /**
  911. * If no arguments are supplied this function will return
  912. * all of the current user preferences as an array.
  913. * If a name is specified then this function
  914. * attempts to return that particular preference value. If
  915. * none is found, then the optional value $default is returned,
  916. * otherwise NULL.
  917. * @param string $name Name of the key to use in finding a preference value
  918. * @param string $default Value to be returned if the $name key is not set in the user preferences
  919. * @param int $otheruserid A moodle user ID
  920. * @uses $USER
  921. * @return string
  922. */
  923. function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
  924. global $USER;
  925. if (!isset($USER->preference)) {
  926. reload_user_preferences();
  927. }
  928. if (empty($otheruserid)){
  929. $userid = $USER->id;
  930. } else {
  931. $userid = $otheruserid;
  932. }
  933. if ($userid == $USER->id) {
  934. $preference = $USER->preference;
  935. } else {
  936. $preference = array();
  937. if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
  938. foreach ($prefdata as $pref) {
  939. $preference[$pref->name] = $pref->value;
  940. }
  941. }
  942. }
  943. if (empty($name)) {
  944. return $preference; // All values
  945. } else if (array_key_exists($name, $preference)) {
  946. return $preference[$name]; // The single value
  947. } else {
  948. return $default; // Default value (or NULL)
  949. }
  950. }
  951. /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
  952. /**
  953. * Given date parts in user time produce a GMT timestamp.
  954. *
  955. * @param int $year The year part to create timestamp of
  956. * @param int $month The month part to create timestamp of
  957. * @param int $day The day part to create timestamp of
  958. * @param int $hour The hour part to create timestamp of
  959. * @param int $minute The minute part to create timestamp of
  960. * @param int $second The second part to create timestamp of
  961. * @param float $timezone ?
  962. * @param bool $applydst ?
  963. * @return int timestamp
  964. * @todo Finish documenting this function
  965. */
  966. function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
  967. $strtimezone = NULL;
  968. if (!is_numeric($timezone)) {
  969. $strtimezone = $timezone;
  970. }
  971. $timezone = get_user_timezone_offset($timezone);
  972. if (abs($timezone) > 13) {
  973. $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
  974. } else {
  975. $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
  976. $time = usertime($time, $timezone);
  977. if($applydst) {
  978. $time -= dst_offset_on($time, $strtimezone);
  979. }
  980. }
  981. return $time;
  982. }
  983. /**
  984. * Given an amount of time in seconds, returns string
  985. * formatted nicely as weeks, days, hours etc as needed
  986. *
  987. * @uses MINSECS
  988. * @uses HOURSECS
  989. * @uses DAYSECS
  990. * @uses YEARSECS
  991. * @param int $totalsecs ?
  992. * @param array $str ?
  993. * @return string
  994. */
  995. function format_time($totalsecs, $str=NULL) {
  996. $totalsecs = abs($totalsecs);
  997. if (!$str) { // Create the str structure the slow way
  998. $str->day = get_string('day');
  999. $str->days = get_string('days');
  1000. $str->hour = get_string('hour');
  1001. $str->hours = get_string('hours');
  1002. $str->min = get_string('min');
  1003. $str->mins = get_string('mins');
  1004. $str->sec = get_string('sec');
  1005. $str->secs = get_string('secs');
  1006. $str->year = get_string('year');
  1007. $str->years = get_string('years');
  1008. }
  1009. $years = floor($totalsecs/YEARSECS);
  1010. $remainder = $totalsecs - ($years*YEARSECS);
  1011. $days = floor($remainder/DAYSECS);
  1012. $remainder = $totalsecs - ($days*DAYSECS);
  1013. $hours = floor($remainder/HOURSECS);
  1014. $remainder = $remainder - ($hours*HOURSECS);
  1015. $mins = floor($remainder/MINSECS);
  1016. $secs = $remainder - ($mins*MINSECS);
  1017. $ss = ($secs == 1) ? $str->sec : $str->secs;
  1018. $sm = ($mins == 1) ? $str->min : $str->mins;
  1019. $sh = ($hours == 1) ? $str->hour : $str->hours;
  1020. $sd = ($days == 1) ? $str->day : $str->days;
  1021. $sy = ($years == 1) ? $str->year : $str->years;
  1022. $oyears = '';
  1023. $odays = '';
  1024. $ohours = '';
  1025. $omins = '';
  1026. $osecs = '';
  1027. if ($years) $oyears = $years .' '. $sy;
  1028. if ($days) $odays = $days .' '. $sd;
  1029. if ($hours) $ohours = $hours .' '. $sh;
  1030. if ($mins) $omins = $mins .' '. $sm;
  1031. if ($secs) $osecs = $secs .' '. $ss;
  1032. if ($years) return trim($oyears .' '. $odays);
  1033. if ($days) return trim($odays .' '. $ohours);
  1034. if ($hours) return trim($ohours .' '. $omins);
  1035. if ($mins) return trim($omins .' '. $osecs);
  1036. if ($secs) return $osecs;
  1037. return get_string('now');
  1038. }
  1039. /**
  1040. * Returns a formatted string that represents a date in user time
  1041. * <b>WARNING: note that the format is for strftime(), not date().</b>
  1042. * Because of a bug in most Windows time libraries, we can't use
  1043. * the nicer %e, so we have to use %d which has leading zeroes.
  1044. * A lot of the fuss in the function is just getting rid of these leading
  1045. * zeroes as efficiently as possible.
  1046. *
  1047. * If parameter fixday = true (default), then take off leading
  1048. * zero from %d, else mantain it.
  1049. *
  1050. * @uses HOURSECS
  1051. * @param int $date timestamp in GMT
  1052. * @param string $format strftime format
  1053. * @param float $timezone
  1054. * @param bool $fixday If true (default) then the leading
  1055. * zero from %d is removed. If false then the leading zero is mantained.
  1056. * @return string
  1057. */
  1058. function userdate($date, $format='', $timezone=99, $fixday = true) {
  1059. global $CFG;
  1060. $strtimezone = NULL;
  1061. if (!is_numeric($timezone)) {
  1062. $strtimezone = $timezone;
  1063. }
  1064. if (empty($format)) {
  1065. $format = get_string('strftimedaydatetime');
  1066. }
  1067. if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
  1068. $fixday = false;
  1069. } else if ($fixday) {
  1070. $formatnoday = str_replace('%d', 'DD', $format);
  1071. $fixday = ($formatnoday != $format);
  1072. }
  1073. $date += dst_offset_on($date, $strtimezone);
  1074. $timezone = get_user_timezone_offset($timezone);
  1075. if (abs($timezone) > 13) { /// Server time
  1076. if ($fixday) {
  1077. $datestring = strftime($formatnoday, $date);
  1078. $daystring = str_replace(' 0', '', strftime(' %d', $date));
  1079. $datestring = str_replace('DD', $daystring, $datestring);
  1080. } else {
  1081. $datestring = strftime($format, $date);
  1082. }
  1083. } else {
  1084. $date += (int)($timezone * 3600);
  1085. if ($fixday) {
  1086. $datestring = gmstrftime($formatnoday, $date);
  1087. $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
  1088. $datestring = str_replace('DD', $daystring, $datestring);
  1089. } else {
  1090. $datestring = gmstrftime($format, $date);
  1091. }
  1092. }
  1093. /// If we are running under Windows convert from windows encoding to UTF-8
  1094. /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
  1095. if ($CFG->ostype == 'WINDOWS') {
  1096. if ($localewincharset = get_string('localewincharset')) {
  1097. $textlib = textlib_get_instance();
  1098. $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
  1099. }
  1100. }
  1101. return $datestring;
  1102. }
  1103. /**
  1104. * Given a $time timestamp in GMT (seconds since epoch),
  1105. * returns an array that represents the date in user time
  1106. *
  1107. * @uses HOURSECS
  1108. * @param int $time Timestamp in GMT
  1109. * @param float $timezone ?
  1110. * @return array An array that represents the date in user time
  1111. * @todo Finish documenting this function
  1112. */
  1113. function usergetdate($time, $timezone=99) {
  1114. $strtimezone = NULL;
  1115. if (!is_numeric($timezone)) {
  1116. $strtimezone = $timezone;
  1117. }
  1118. $timezone = get_user_timezone_offset($timezone);
  1119. if (abs($timezone) > 13) { // Server time
  1120. return getdate($time);
  1121. }
  1122. // There is no gmgetdate so we use gmdate instead
  1123. $time += dst_offset_on($time, $strtimezone);
  1124. $time += intval((float)$timezone * HOURSECS);
  1125. $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
  1126. list(
  1127. $getdate['seconds'],
  1128. $getdate['minutes'],
  1129. $getdate['hours'],
  1130. $getdate['mday'],
  1131. $getdate['mon'],
  1132. $getdate['year'],
  1133. $getdate['wday'],
  1134. $getdate['yday'],
  1135. $getdate['weekday'],
  1136. $getdate['month']
  1137. ) = explode('_', $datestring);
  1138. return $getdate;
  1139. }
  1140. /**
  1141. * Given a GMT timestamp (seconds since epoch), offsets it by
  1142. * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
  1143. *
  1144. * @uses HOURSECS
  1145. * @param int $date Timestamp in GMT
  1146. * @param float $timezone
  1147. * @return int
  1148. */
  1149. function usertime($date, $timezone=99) {
  1150. $timezone = get_user_timezone_offset($timezone);
  1151. if (abs($timezone) > 13) {
  1152. return $date;
  1153. }
  1154. return $date - (int)($timezone * HOURSECS);
  1155. }
  1156. /**
  1157. * Given a time, return the GMT timestamp of the most recent midnight
  1158. * for the current user.
  1159. *
  1160. * @param int $date Timestamp in GMT
  1161. * @param float $timezone ?
  1162. * @return ?
  1163. */
  1164. function usergetmidnight($date, $timezone=99) {
  1165. $userdate = usergetdate($date, $timezone);
  1166. // Time of midnight of this user's day, in GMT
  1167. return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
  1168. }
  1169. /**
  1170. * Returns a string that prints the user's timezone
  1171. *
  1172. * @param float $timezone The user's timezone
  1173. * @return string
  1174. */
  1175. function usertimezone($timezone=99) {
  1176. $tz = get_user_timezone($timezone);
  1177. if (!is_float($tz)) {
  1178. return $tz;
  1179. }
  1180. if(abs($tz) > 13) { // Server time
  1181. return get_string('serverlocaltime');
  1182. }
  1183. if($tz == intval($tz)) {
  1184. // Don't show .0 for whole hours
  1185. $tz = intval($tz);
  1186. }
  1187. if($tz == 0) {
  1188. return 'UTC';
  1189. }
  1190. else if($tz > 0) {
  1191. return 'UTC+'.$tz;
  1192. }
  1193. else {
  1194. return 'UTC'.$tz;
  1195. }
  1196. }
  1197. /**
  1198. * Returns a float which represents the user's timezone difference from GMT in hours
  1199. * Checks various settings and picks the most dominant of those which have a value
  1200. *
  1201. * @uses $CFG
  1202. * @uses $USER
  1203. * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
  1204. * @return int
  1205. */
  1206. function get_user_timezone_offset($tz = 99) {
  1207. global $USER, $CFG;
  1208. $tz = get_user_timezone($tz);
  1209. if (is_float($tz)) {
  1210. return $tz;
  1211. } else {
  1212. $tzrecord = get_timezone_record($tz);
  1213. if (empty($tzrecord)) {
  1214. return 99.0;
  1215. }
  1216. return (float)$tzrecord->gmtoff / HOURMINS;
  1217. }
  1218. }
  1219. /**
  1220. * Returns an int which represents the systems's timezone difference from GMT in seconds
  1221. * @param mixed $tz timezone
  1222. * @return int if found, false is timezone 99 or error
  1223. */
  1224. function get_timezone_offset($tz) {
  1225. global $CFG;
  1226. if ($tz == 99) {
  1227. return false;
  1228. }
  1229. if (is_numeric($tz)) {
  1230. return intval($tz * 60*60);
  1231. }
  1232. if (!$tzrecord = get_timezone_record($tz)) {
  1233. return false;
  1234. }
  1235. return intval($tzrecord->gmtoff * 60);
  1236. }
  1237. /**
  1238. * Returns a float or a string which denotes the user's timezone
  1239. * 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)
  1240. * means that for this timezone there are also DST rules to be taken into account
  1241. * Checks various settings and picks the most dominant of those which have a value
  1242. *
  1243. * @uses $USER
  1244. * @uses $CFG
  1245. * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
  1246. * @return mixed
  1247. */
  1248. function get_user_timezone($tz = 99) {
  1249. global $USER, $CFG;
  1250. $timezones = array(
  1251. $tz,
  1252. isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
  1253. isset($USER->timezone) ? $USER->timezone : 99,
  1254. isset($CFG->timezone) ? $CFG->timezone : 99,
  1255. );
  1256. $tz = 99;
  1257. while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
  1258. $tz = $next['value'];
  1259. }
  1260. return is_numeric($tz) ? (float) $tz : $tz;
  1261. }
  1262. /**
  1263. * ?
  1264. *
  1265. * @uses $CFG
  1266. * @uses $db
  1267. * @param string $timezonename ?
  1268. * @return object
  1269. */
  1270. function get_timezone_record($timezonename) {
  1271. global $CFG, $db;
  1272. static $cache = NULL;
  1273. if ($cache === NULL) {
  1274. $cache = array();
  1275. }
  1276. if (isset($cache[$timezonename])) {
  1277. return $cache[$timezonename];
  1278. }
  1279. return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
  1280. WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
  1281. }
  1282. /**
  1283. * ?
  1284. *
  1285. * @uses $CFG
  1286. * @uses $USER
  1287. * @param ? $fromyear ?
  1288. * @param ? $to_year ?
  1289. * @return bool
  1290. */
  1291. function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
  1292. global $CFG, $SESSION;
  1293. $usertz = get_user_timezone($strtimezone);
  1294. if (is_float($usertz)) {
  1295. // Trivial timezone, no DST
  1296. return false;
  1297. }
  1298. if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
  1299. // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
  1300. unset($SESSION->dst_offsets);
  1301. unset($SESSION->dst_range);
  1302. }
  1303. if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
  1304. // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
  1305. // This will be the return path most of the time, pretty light computationally
  1306. return true;
  1307. }
  1308. // Reaching here means we either need to extend our table or create it from scratch
  1309. // Remember which TZ we calculated these changes for
  1310. $SESSION->dst_offsettz = $usertz;
  1311. if(empty($SESSION->dst_offsets)) {
  1312. // If we 're creating from scratch, put the two guard elements in there
  1313. $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
  1314. }
  1315. if(empty($SESSION->dst_range)) {
  1316. // If creating from scratch
  1317. $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
  1318. $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
  1319. // Fill in the array with the extra years we need to process
  1320. $yearstoprocess = array();
  1321. for($i = $from; $i <= $to; ++$i) {
  1322. $yearstoprocess[] = $i;
  1323. }
  1324. // Take note of which years we have processed for future calls
  1325. $SESSION->dst_range = array($from, $to);
  1326. }
  1327. else {
  1328. // If needing to extend the table, do the same
  1329. $yearstoprocess = array();
  1330. $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
  1331. $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
  1332. if($from < $SESSION->dst_range[0]) {
  1333. // Take note of which years we need to process and then note that we have processed them for future calls
  1334. for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
  1335. $yearstoprocess[] = $i;
  1336. }
  1337. $SESSION->dst_range[0] = $from;
  1338. }
  1339. if($to > $SESSION->dst_range[1]) {
  1340. // Take note of which years we need to process and then note that we have processed them for future calls
  1341. for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
  1342. $yearstoprocess[] = $i;
  1343. }
  1344. $SESSION->dst_range[1] = $to;
  1345. }
  1346. }
  1347. if(empty($yearstoprocess)) {
  1348. // This means that there was a call requesting a SMALLER range than we have already calculated
  1349. return true;
  1350. }
  1351. // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
  1352. // Also, the array is sorted in descending timestamp order!
  1353. // Get DB data
  1354. static $presets_cache = array();
  1355. if (!isset($presets_cache[$usertz])) {
  1356. $presets_cache[$usertz] = get_records('timezone', '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');
  1357. }
  1358. if(empty($presets_cache[$usertz])) {
  1359. return false;
  1360. }
  1361. // Remove ending guard (first element of the array)
  1362. reset($SESSION->dst_offsets);
  1363. unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
  1364. // Add all required change timestamps
  1365. foreach($yearstoprocess as $y) {
  1366. // Find the record which is in effect for the year $y
  1367. foreach($presets_cache[$usertz] as $year => $preset) {
  1368. if($year <= $y) {
  1369. break;
  1370. }
  1371. }
  1372. $changes = dst_changes_for_year($y, $preset);
  1373. if($changes === NULL) {
  1374. continue;
  1375. }
  1376. if($changes['dst'] != 0) {
  1377. $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
  1378. }
  1379. if($changes['std'] != 0) {
  1380. $SESSION->dst_offsets[$changes['std']] = 0;
  1381. }
  1382. }
  1383. // Put in a guard element at the top
  1384. $maxtimestamp = max(array_keys($SESSION->dst_offsets));
  1385. $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
  1386. // Sort again
  1387. krsort($SESSION->dst_offsets);
  1388. return true;
  1389. }
  1390. function dst_changes_for_year($year, $timezone) {
  1391. if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
  1392. return NULL;
  1393. }
  1394. $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
  1395. $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
  1396. list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
  1397. list($std_hour, $std_min) = explode(':', $timezone->std_time);
  1398. $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
  1399. $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
  1400. // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
  1401. // This has the advantage of being able to have negative values for hour, i.e. for timezones
  1402. // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
  1403. $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
  1404. $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
  1405. return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
  1406. }
  1407. // $time must NOT be compensated at all, it has to be a pure timestamp
  1408. function dst_offset_on($time, $strtimezone = NULL) {
  1409. global $SESSION;
  1410. if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
  1411. return 0;
  1412. }
  1413. reset($SESSION->dst_offsets);
  1414. while(list($from, $offset) = each($SESSION->dst_offsets)) {
  1415. if($from <= $time) {
  1416. break;
  1417. }
  1418. }
  1419. // This is the normal return path
  1420. if($offset !== NULL) {
  1421. return $offset;
  1422. }
  1423. // Reaching this point means we haven't calculated far enough, do it now:
  1424. // Calculate extra DST changes if needed and recurse. The recursion always
  1425. // moves toward the stopping condition, so will always end.
  1426. if($from == 0) {
  1427. // We need a year smaller than $SESSION->dst_range[0]
  1428. if($SESSION->dst_range[0] == 1971) {
  1429. return 0;
  1430. }
  1431. calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
  1432. return dst_offset_on($time, $strtimezone);
  1433. }
  1434. else {
  1435. // We need a year larger than $SESSION->dst_range[1]
  1436. if($SESSION->dst_range[1] == 2035) {
  1437. return 0;
  1438. }
  1439. calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
  1440. return dst_offset_on($time, $strtimezone);
  1441. }
  1442. }
  1443. function find_day_in_month($startday, $weekday, $month, $year) {
  1444. $daysinmonth = days_in_month($month, $year);
  1445. if($weekday == -1) {
  1446. // Don't care about weekday, so return:
  1447. // abs($startday) if $startday != -1
  1448. // $daysinmonth otherwise
  1449. return ($startday == -1) ? $daysinmonth : abs($startday);
  1450. }
  1451. // From now on we 're looking for a specific weekday
  1452. // Give "end of month" its actual value, since we know it
  1453. if($startday == -1) {
  1454. $startday = -1 * $daysinmonth;
  1455. }
  1456. // Starting from day $startday, the sign is the direction
  1457. if($startday < 1) {
  1458. $startday = abs($startday);
  1459. $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
  1460. // This is the last such weekday of the month
  1461. $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
  1462. if($lastinmonth > $daysinmonth) {
  1463. $lastinmonth -= 7;
  1464. }
  1465. // Find the first such weekday <= $startday
  1466. while($lastinmonth > $startday) {
  1467. $lastinmonth -= 7;
  1468. }
  1469. return $lastinmonth;
  1470. }
  1471. else {
  1472. $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
  1473. $diff = $weekday - $indexweekday;
  1474. if($diff < 0) {
  1475. $diff += 7;
  1476. }
  1477. // This is the first such weekday of the month equal to or after $startday
  1478. $firstfromindex = $startday + $diff;
  1479. return $firstfromindex;
  1480. }
  1481. }
  1482. /**
  1483. * Calculate the number of days in a given month
  1484. *
  1485. * @param int $month The month whose day count is sought
  1486. * @param int $year The year of the month whose day count is sought
  1487. * @return int
  1488. */
  1489. function days_in_month($month, $year) {
  1490. return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
  1491. }
  1492. /**
  1493. * Calculate the position in the week of a specific calendar day
  1494. *
  1495. * @param int $day The day of the date whose position in the week is sought
  1496. * @param int $month The month of the date whose position in the week is sought
  1497. * @param int $year The year of the date whose position in the week is sought
  1498. * @return int
  1499. */
  1500. function dayofweek($day, $month, $year) {
  1501. // I wonder if this is any different from
  1502. // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
  1503. return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
  1504. }
  1505. /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
  1506. /**
  1507. * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
  1508. * if one does not already exist, but does not overwrite existing sesskeys. Returns the
  1509. * sesskey string if $USER exists, or boolean false if not.
  1510. *
  1511. * @uses $USER
  1512. * @return string
  1513. */
  1514. function sesskey() {
  1515. global $USER;
  1516. if(!isset($USER)) {
  1517. return false;
  1518. }
  1519. if (empty($USER->sesskey)) {
  1520. $USER->sesskey = random_string(10);
  1521. }
  1522. return $USER->sesskey;
  1523. }
  1524. /**
  1525. * For security purposes, this function will check that the currently
  1526. * given sesskey (passed as a parameter to the script or this function)
  1527. * matches that of the current user.
  1528. *
  1529. * @param string $sesskey optionally provided sesskey
  1530. * @return bool
  1531. */
  1532. function confirm_sesskey($sesskey=NULL) {
  1533. global $USER;
  1534. if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
  1535. return true;
  1536. }
  1537. if (empty($sesskey)) {
  1538. $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
  1539. }
  1540. if (!isset($USER->sesskey)) {
  1541. return false;
  1542. }
  1543. return ($USER->sesskey === $sesskey);
  1544. }
  1545. /**
  1546. * Setup all global $CFG course variables, set locale and also themes
  1547. * This function can be used on pages that do not require login instead of require_login()
  1548. *
  1549. * @param mixed $courseorid id of the course or course object
  1550. */
  1551. function course_setup($courseorid=0) {
  1552. global $COURSE, $CFG, $SITE;
  1553. /// Redefine global $COURSE if needed
  1554. if (empty($courseorid)) {
  1555. // no change in global $COURSE - for backwards compatibiltiy
  1556. // if require_rogin() used after require_login($courseid);
  1557. } else if (is_object($courseorid)) {
  1558. $COURSE = clone($courseorid);
  1559. } else {
  1560. global $course; // used here only to prevent repeated fetching from DB - may be removed later
  1561. if ($courseorid == SITEID) {
  1562. $COURSE = clone($SITE);
  1563. } else if (!empty($course->id) and $course->id == $courseorid) {
  1564. $COURSE = clone($course);
  1565. } else {
  1566. if (!$COURSE = get_record('course', 'id', $courseorid)) {
  1567. error('Invalid course ID');
  1568. }
  1569. }
  1570. }
  1571. /// set locale and themes
  1572. moodle_setlocale();
  1573. theme_setup();
  1574. }
  1575. /**
  1576. * This function checks that the current user is logged in and has the
  1577. * required privileges
  1578. *
  1579. * This function checks that the current user is logged in, and optionally
  1580. * whether they are allowed to be in a particular course and view a particular
  1581. * course module.
  1582. * If they are not logged in, then it redirects them to the site login unless
  1583. * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
  1584. * case they are automatically logged in as guests.
  1585. * If $courseid is given and the user is not enrolled in that course then the
  1586. * user is redirected to the course enrolment page.
  1587. * If $cm is given and the coursemodule is hidden and the user is not a teacher
  1588. * in the course then the user is redirected to the course home page.
  1589. *
  1590. * @uses $CFG
  1591. * @uses $SESSION
  1592. * @uses $USER
  1593. * @uses $FULLME
  1594. * @uses SITEID
  1595. * @uses $COURSE
  1596. * @param mixed $courseorid id of the course or course object
  1597. * @param bool $autologinguest
  1598. * @param object $cm course module object
  1599. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  1600. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  1601. * in order to keep redirects working properly. MDL-14495
  1602. */
  1603. function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
  1604. global $CFG, $SESSION, $USER, $COURSE, $FULLME;
  1605. /// setup global $COURSE, themes, language and locale
  1606. course_setup($courseorid);
  1607. /// If the user is not even logged in yet then make sure they are
  1608. if (!isloggedin()) {
  1609. //NOTE: $USER->site check was obsoleted by session test cookie,
  1610. // $USER->confirmed test is in login/index.php
  1611. if ($setwantsurltome) {
  1612. $SESSION->wantsurl = $FULLME;
  1613. }
  1614. if (!empty($_SERVER['HTTP_REFERER'])) {
  1615. $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
  1616. }
  1617. if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
  1618. $loginguest = '?loginguest=true';
  1619. } else {
  1620. $loginguest = '';
  1621. }
  1622. if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
  1623. redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
  1624. } else {
  1625. $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
  1626. redirect($wwwroot .'/login/index.php');
  1627. }
  1628. exit;
  1629. }
  1630. /// loginas as redirection if needed
  1631. if ($COURSE->id != SITEID and !empty($USER->realuser)) {
  1632. if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
  1633. if ($USER->loginascontext->instanceid != $COURSE->id) {
  1634. print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
  1635. }
  1636. }
  1637. }
  1638. /// check whether the user should be changing password (but only if it is REALLY them)
  1639. if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
  1640. $userauth = get_auth_plugin($USER->auth);
  1641. if ($userauth->can_change_password()) {
  1642. $SESSION->wantsurl = $FULLME;
  1643. if ($changeurl = $userauth->change_password_url()) {
  1644. //use plugin custom url
  1645. redirect($changeurl);
  1646. } else {
  1647. //use moodle internal method
  1648. if (empty($CFG->loginhttps)) {
  1649. redirect($CFG->wwwroot .'/login/change_password.php');
  1650. } else {
  1651. $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
  1652. redirect($wwwroot .'/login/change_password.php');
  1653. }
  1654. }
  1655. } else {
  1656. print_error('nopasswordchangeforced', 'auth');
  1657. }
  1658. }
  1659. /// Check that the user account is properly set up
  1660. if (user_not_fully_set_up($USER)) {
  1661. $SESSION->wantsurl = $FULLME;
  1662. redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
  1663. }
  1664. /// Make sure current IP matches the one for this session (if required)
  1665. if (!empty($CFG->tracksessionip)) {
  1666. if ($USER->sessionIP != md5(getremoteaddr())) {
  1667. print_error('sessionipnomatch', 'error');
  1668. }
  1669. }
  1670. /// Make sure the USER has a sesskey set up. Used for checking script parameters.
  1671. sesskey();
  1672. // Check that the user has agreed to a site policy if there is one
  1673. if (!empty($CFG->sitepolicy)) {
  1674. if (!$USER->policyagreed) {
  1675. $SESSION->wantsurl = $FULLME;
  1676. redirect($CFG->wwwroot .'/user/policy.php');
  1677. }
  1678. }
  1679. // Fetch the system context, we are going to use it a lot.
  1680. $sysctx = get_context_instance(CONTEXT_SYSTEM);
  1681. /// If the site is currently under maintenance, then print a message
  1682. if (!has_capability('moodle/site:config', $sysctx)) {
  1683. if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
  1684. print_maintenance_message();
  1685. exit;
  1686. }
  1687. }
  1688. /// groupmembersonly access control
  1689. if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
  1690. if (isguestuser() or !groups_has_membership($cm)) {
  1691. print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
  1692. }
  1693. }
  1694. // Fetch the course context, and prefetch its child contexts
  1695. if (!isset($COURSE->context)) {
  1696. if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
  1697. print_error('nocontext');
  1698. }
  1699. }
  1700. if (!empty($cm) && !isset($cm->context)) {
  1701. if ( ! $cm->context = get_context_instance(CONTEXT_MODULE, $cm->id) ) {
  1702. print_error('nocontext');
  1703. }
  1704. }
  1705. if ($COURSE->id == SITEID) {
  1706. /// Eliminate hidden site activities straight away
  1707. if (!empty($cm) && !$cm->visible
  1708. && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
  1709. redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
  1710. }
  1711. user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
  1712. return;
  1713. } else {
  1714. /// Check if the user can be in a particular course
  1715. if (empty($USER->access['rsw'][$COURSE->context->path])) {
  1716. //
  1717. // MDL-13900 - If the course or the parent category are hidden
  1718. // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
  1719. //
  1720. if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
  1721. !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
  1722. print_header_simple();
  1723. notice(get_string('coursehidden'), $CFG->wwwroot .'/');
  1724. }
  1725. }
  1726. /// Non-guests who don't currently have access, check if they can be allowed in as a guest
  1727. if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
  1728. if ($COURSE->guest == 1) {
  1729. // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
  1730. $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
  1731. }
  1732. }
  1733. /// If the user is a guest then treat them according to the course policy about guests
  1734. if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
  1735. if (has_capability('moodle/site:doanything', $sysctx)) {
  1736. // administrators must be able to access any course - even if somebody gives them guest access
  1737. user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
  1738. return;
  1739. }
  1740. switch ($COURSE->guest) { /// Check course policy about guest access
  1741. case 1: /// Guests always allowed
  1742. if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
  1743. print_header_simple();
  1744. notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
  1745. }
  1746. if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
  1747. redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
  1748. get_string('activityiscurrentlyhidden'));
  1749. }
  1750. user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
  1751. return; // User is allowed to see this course
  1752. break;
  1753. case 2: /// Guests allowed with key
  1754. if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
  1755. user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
  1756. return true;
  1757. }
  1758. // otherwise drop through to logic below (--> enrol.php)
  1759. break;
  1760. default: /// Guests not allowed
  1761. $strloggedinasguest = get_string('loggedinasguest');
  1762. print_header_simple('', '',
  1763. build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
  1764. if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
  1765. notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
  1766. } else {
  1767. notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
  1768. echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
  1769. print_footer($COURSE);
  1770. exit;
  1771. }
  1772. break;
  1773. }
  1774. /// For non-guests, check if they have course view access
  1775. } else if (has_capability('moodle/course:view', $COURSE->context)) {
  1776. if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
  1777. if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
  1778. print_header_simple();
  1779. notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
  1780. }
  1781. }
  1782. /// Make sure they can read this activity too, if specified
  1783. if (!empty($cm) && !$cm->visible && !has_capability('moodle/course:viewhiddenactivities', $cm->context)) {
  1784. redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
  1785. }
  1786. user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
  1787. return; // User is allowed to see this course
  1788. }
  1789. /// Currently not enrolled in the course, so see if they want to enrol
  1790. $SESSION->wantsurl = $FULLME;
  1791. redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
  1792. die;
  1793. }
  1794. }
  1795. /**
  1796. * This function just makes sure a user is logged out.
  1797. *
  1798. * @uses $CFG
  1799. * @uses $USER
  1800. */
  1801. function require_logout() {
  1802. global $USER, $CFG, $SESSION;
  1803. if (isloggedin()) {
  1804. add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
  1805. $authsequence = get_enabled_auth_plugins(); // auths, in sequence
  1806. foreach($authsequence as $authname) {
  1807. $authplugin = get_auth_plugin($authname);
  1808. $authplugin->prelogout_hook();
  1809. }
  1810. }
  1811. if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
  1812. // This method is just to try to avoid silly warnings from PHP 4.3.0
  1813. session_unregister("USER");
  1814. session_unregister("SESSION");
  1815. }
  1816. // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
  1817. $file = $line = null;
  1818. if (headers_sent($file, $line)) {
  1819. error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
  1820. error_log('Headers were already sent in file: '.$file.' on line '.$line);
  1821. } else {
  1822. if (check_php_version('5.2.0')) {
  1823. setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
  1824. } else {
  1825. setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
  1826. }
  1827. }
  1828. unset($_SESSION['USER']);
  1829. unset($_SESSION['SESSION']);
  1830. unset($SESSION);
  1831. unset($USER);
  1832. }
  1833. /**
  1834. * This is a weaker version of {@link require_login()} which only requires login
  1835. * when called from within a course rather than the site page, unless
  1836. * the forcelogin option is turned on.
  1837. *
  1838. * @uses $CFG
  1839. * @param mixed $courseorid The course object or id in question
  1840. * @param bool $autologinguest Allow autologin guests if that is wanted
  1841. * @param object $cm Course activity module if known
  1842. * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
  1843. * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
  1844. * in order to keep redirects working properly. MDL-14495
  1845. */
  1846. function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
  1847. global $CFG;
  1848. if (!empty($CFG->forcelogin)) {
  1849. // login required for both SITE and courses
  1850. require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
  1851. } else if (!empty($cm) and !$cm->visible) {
  1852. // always login for hidden activities
  1853. require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
  1854. } else if ((is_object($courseorid) and $courseorid->id == SITEID)
  1855. or (!is_object($courseorid) and $courseorid == SITEID)) {
  1856. //login for SITE not required
  1857. if ($cm and empty($cm->visible)) {
  1858. // hidden activities are not accessible without login
  1859. require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
  1860. } else if ($cm and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
  1861. // not-logged-in users do not have any group membership
  1862. require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
  1863. } else {
  1864. user_accesstime_log(SITEID);
  1865. return;
  1866. }
  1867. } else {
  1868. // course login always required
  1869. require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
  1870. }
  1871. }
  1872. /**
  1873. * Require key login. Function terminates with error if key not found or incorrect.
  1874. * @param string $script unique script identifier
  1875. * @param int $instance optional instance id
  1876. */
  1877. function require_user_key_login($script, $instance=null) {
  1878. global $nomoodlecookie, $USER, $SESSION, $CFG;
  1879. if (empty($nomoodlecookie)) {
  1880. error('Incorrect use of require_key_login() - session cookies must be disabled!');
  1881. }
  1882. /// extra safety
  1883. @session_write_close();
  1884. $keyvalue = required_param('key', PARAM_ALPHANUM);
  1885. if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
  1886. error('Incorrect key');
  1887. }
  1888. if (!empty($key->validuntil) and $key->validuntil < time()) {
  1889. error('Expired key');
  1890. }
  1891. if ($key->iprestriction) {
  1892. $remoteaddr = getremoteaddr();
  1893. if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
  1894. error('Client IP address mismatch');
  1895. }
  1896. }
  1897. if (!$user = get_record('user', 'id', $key->userid)) {
  1898. error('Incorrect user record');
  1899. }
  1900. /// emulate normal session
  1901. $SESSION = new object();
  1902. $USER = $user;
  1903. /// note we are not using normal login
  1904. if (!defined('USER_KEY_LOGIN')) {
  1905. define('USER_KEY_LOGIN', true);
  1906. }
  1907. load_all_capabilities();
  1908. /// return isntance id - it might be empty
  1909. return $key->instance;
  1910. }
  1911. /**
  1912. * Creates a new private user access key.
  1913. * @param string $script unique target identifier
  1914. * @param int $userid
  1915. * @param instance $int optional instance id
  1916. * @param string $iprestriction optional ip restricted access
  1917. * @param timestamp $validuntil key valid only until given data
  1918. * @return string access key value
  1919. */
  1920. function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
  1921. $key = new object();
  1922. $key->script = $script;
  1923. $key->userid = $userid;
  1924. $key->instance = $instance;
  1925. $key->iprestriction = $iprestriction;
  1926. $key->validuntil = $validuntil;
  1927. $key->timecreated = time();
  1928. $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
  1929. while (record_exists('user_private_key', 'value', $key->value)) {
  1930. // must be unique
  1931. $key->value = md5($userid.'_'.time().random_string(40));
  1932. }
  1933. if (!insert_record('user_private_key', $key)) {
  1934. error('Can not insert new key');
  1935. }
  1936. return $key->value;
  1937. }
  1938. /**
  1939. * Modify the user table by setting the currently logged in user's
  1940. * last login to now.
  1941. *
  1942. * @uses $USER
  1943. * @return bool
  1944. */
  1945. function update_user_login_times() {
  1946. global $USER;
  1947. $user = new object();
  1948. $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
  1949. $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
  1950. $user->id = $USER->id;
  1951. return update_record('user', $user);
  1952. }
  1953. /**
  1954. * Determines if a user has completed setting up their account.
  1955. *
  1956. * @param user $user A {@link $USER} object to test for the existance of a valid name and email
  1957. * @return bool
  1958. */
  1959. function user_not_fully_set_up($user) {
  1960. return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
  1961. }
  1962. function over_bounce_threshold($user) {
  1963. global $CFG;
  1964. if (empty($CFG->handlebounces)) {
  1965. return false;
  1966. }
  1967. if (empty($user->id)) { /// No real (DB) user, nothing to do here.
  1968. return false;
  1969. }
  1970. // set sensible defaults
  1971. if (empty($CFG->minbounces)) {
  1972. $CFG->minbounces = 10;
  1973. }
  1974. if (empty($CFG->bounceratio)) {
  1975. $CFG->bounceratio = .20;
  1976. }
  1977. $bouncecount = 0;
  1978. $sendcount = 0;
  1979. if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
  1980. $bouncecount = $bounce->value;
  1981. }
  1982. if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
  1983. $sendcount = $send->value;
  1984. }
  1985. return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
  1986. }
  1987. /**
  1988. * @param $user - object containing an id
  1989. * @param $reset - will reset the count to 0
  1990. */
  1991. function set_send_count($user,$reset=false) {
  1992. if (empty($user->id)) { /// No real (DB) user, nothing to do here.
  1993. return;
  1994. }
  1995. if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
  1996. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  1997. update_record('user_preferences',$pref);
  1998. }
  1999. else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
  2000. // make a new one
  2001. $pref->name = 'email_send_count';
  2002. $pref->value = 1;
  2003. $pref->userid = $user->id;
  2004. insert_record('user_preferences',$pref, false);
  2005. }
  2006. }
  2007. /**
  2008. * @param $user - object containing an id
  2009. * @param $reset - will reset the count to 0
  2010. */
  2011. function set_bounce_count($user,$reset=false) {
  2012. if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
  2013. $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
  2014. update_record('user_preferences',$pref);
  2015. }
  2016. else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
  2017. // make a new one
  2018. $pref->name = 'email_bounce_count';
  2019. $pref->value = 1;
  2020. $pref->userid = $user->id;
  2021. insert_record('user_preferences',$pref, false);
  2022. }
  2023. }
  2024. /**
  2025. * Keeps track of login attempts
  2026. *
  2027. * @uses $SESSION
  2028. */
  2029. function update_login_count() {
  2030. global $SESSION;
  2031. $max_logins = 10;
  2032. if (empty($SESSION->logincount)) {
  2033. $SESSION->logincount = 1;
  2034. } else {
  2035. $SESSION->logincount++;
  2036. }
  2037. if ($SESSION->logincount > $max_logins) {
  2038. unset($SESSION->wantsurl);
  2039. print_error('errortoomanylogins');
  2040. }
  2041. }
  2042. /**
  2043. * Resets login attempts
  2044. *
  2045. * @uses $SESSION
  2046. */
  2047. function reset_login_count() {
  2048. global $SESSION;
  2049. $SESSION->logincount = 0;
  2050. }
  2051. function sync_metacourses() {
  2052. global $CFG;
  2053. if (!$courses = get_records('course', 'metacourse', 1)) {
  2054. return;
  2055. }
  2056. foreach ($courses as $course) {
  2057. sync_metacourse($course);
  2058. }
  2059. }
  2060. /**
  2061. * Goes through all enrolment records for the courses inside the metacourse and sync with them.
  2062. *
  2063. * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
  2064. */
  2065. function sync_metacourse($course) {
  2066. global $CFG;
  2067. // Check the course is valid.
  2068. if (!is_object($course)) {
  2069. if (!$course = get_record('course', 'id', $course)) {
  2070. return false; // invalid course id
  2071. }
  2072. }
  2073. // Check that we actually have a metacourse.
  2074. if (empty($course->metacourse)) {
  2075. return false;
  2076. }
  2077. // Get a list of roles that should not be synced.
  2078. if (!empty($CFG->nonmetacoursesyncroleids)) {
  2079. $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
  2080. } else {
  2081. $roleexclusions = '';
  2082. }
  2083. // Get the context of the metacourse.
  2084. $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
  2085. // We do not ever want to unassign the list of metacourse manager, so get a list of them.
  2086. if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
  2087. $managers = array_keys($users);
  2088. } else {
  2089. $managers = array();
  2090. }
  2091. // Get assignments of a user to a role that exist in a child course, but
  2092. // not in the meta coure. That is, get a list of the assignments that need to be made.
  2093. if (!$assignments = get_records_sql("
  2094. SELECT
  2095. ra.id, ra.roleid, ra.userid
  2096. FROM
  2097. {$CFG->prefix}role_assignments ra,
  2098. {$CFG->prefix}context con,
  2099. {$CFG->prefix}course_meta cm
  2100. WHERE
  2101. ra.contextid = con.id AND
  2102. con.contextlevel = " . CONTEXT_COURSE . " AND
  2103. con.instanceid = cm.child_course AND
  2104. cm.parent_course = {$course->id} AND
  2105. $roleexclusions
  2106. NOT EXISTS (
  2107. SELECT 1 FROM
  2108. {$CFG->prefix}role_assignments ra2
  2109. WHERE
  2110. ra2.userid = ra.userid AND
  2111. ra2.roleid = ra.roleid AND
  2112. ra2.contextid = {$context->id}
  2113. )
  2114. ")) {
  2115. $assignments = array();
  2116. }
  2117. // Get assignments of a user to a role that exist in the meta course, but
  2118. // not in any child courses. That is, get a list of the unassignments that need to be made.
  2119. if (!$unassignments = get_records_sql("
  2120. SELECT
  2121. ra.id, ra.roleid, ra.userid
  2122. FROM
  2123. {$CFG->prefix}role_assignments ra
  2124. WHERE
  2125. ra.contextid = {$context->id} AND
  2126. $roleexclusions
  2127. NOT EXISTS (
  2128. SELECT 1 FROM
  2129. {$CFG->prefix}role_assignments ra2,
  2130. {$CFG->prefix}context con2,
  2131. {$CFG->prefix}course_meta cm
  2132. WHERE
  2133. ra2.userid = ra.userid AND
  2134. ra2.roleid = ra.roleid AND
  2135. ra2.contextid = con2.id AND
  2136. con2.contextlevel = " . CONTEXT_COURSE . " AND
  2137. con2.instanceid = cm.child_course AND
  2138. cm.parent_course = {$course->id}
  2139. )
  2140. ")) {
  2141. $unassignments = array();
  2142. }
  2143. $success = true;
  2144. // Make the unassignments, if they are not managers.
  2145. foreach ($unassignments as $unassignment) {
  2146. if (!in_array($unassignment->userid, $managers)) {
  2147. $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
  2148. }
  2149. }
  2150. // Make the assignments.
  2151. foreach ($assignments as $assignment) {
  2152. $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
  2153. }
  2154. return $success;
  2155. // TODO: finish timeend and timestart
  2156. // maybe we could rely on cron job to do the cleaning from time to time
  2157. }
  2158. /**
  2159. * Adds a record to the metacourse table and calls sync_metacoures
  2160. */
  2161. function add_to_metacourse ($metacourseid, $courseid) {
  2162. if (!$metacourse = get_record("course","id",$metacourseid)) {
  2163. return false;
  2164. }
  2165. if (!$course = get_record("course","id",$courseid)) {
  2166. return false;
  2167. }
  2168. if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
  2169. $rec = new object();
  2170. $rec->parent_course = $metacourseid;
  2171. $rec->child_course = $courseid;
  2172. if (!insert_record('course_meta',$rec)) {
  2173. return false;
  2174. }
  2175. return sync_metacourse($metacourseid);
  2176. }
  2177. return true;
  2178. }
  2179. /**
  2180. * Removes the record from the metacourse table and calls sync_metacourse
  2181. */
  2182. function remove_from_metacourse($metacourseid, $courseid) {
  2183. if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
  2184. return sync_metacourse($metacourseid);
  2185. }
  2186. return false;
  2187. }
  2188. /**
  2189. * Determines if a user is currently logged in
  2190. *
  2191. * @uses $USER
  2192. * @return bool
  2193. */
  2194. function isloggedin() {
  2195. global $USER;
  2196. return (!empty($USER->id));
  2197. }
  2198. /**
  2199. * Determines if a user is logged in as real guest user with username 'guest'.
  2200. * This function is similar to original isguest() in 1.6 and earlier.
  2201. * Current isguest() is deprecated - do not use it anymore.
  2202. *
  2203. * @param $user mixed user object or id, $USER if not specified
  2204. * @return bool true if user is the real guest user, false if not logged in or other user
  2205. */
  2206. function isguestuser($user=NULL) {
  2207. global $USER;
  2208. if ($user === NULL) {
  2209. $user = $USER;
  2210. } else if (is_numeric($user)) {
  2211. $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
  2212. }
  2213. if (empty($user->id)) {
  2214. return false; // not logged in, can not be guest
  2215. }
  2216. return ($user->username == 'guest');
  2217. }
  2218. /**
  2219. * Determines if the currently logged in user is in editing mode.
  2220. * Note: originally this function had $userid parameter - it was not usable anyway
  2221. *
  2222. * @uses $USER, $PAGE
  2223. * @return bool
  2224. */
  2225. function isediting() {
  2226. global $USER, $PAGE;
  2227. if (empty($USER->editing)) {
  2228. return false;
  2229. } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
  2230. return $PAGE->user_allowed_editing();
  2231. }
  2232. return true;//false;
  2233. }
  2234. /**
  2235. * Determines if the logged in user is currently moving an activity
  2236. *
  2237. * @uses $USER
  2238. * @param int $courseid The id of the course being tested
  2239. * @return bool
  2240. */
  2241. function ismoving($courseid) {
  2242. global $USER;
  2243. if (!empty($USER->activitycopy)) {
  2244. return ($USER->activitycopycourse == $courseid);
  2245. }
  2246. return false;
  2247. }
  2248. /**
  2249. * Given an object containing firstname and lastname
  2250. * values, this function returns a string with the
  2251. * full name of the person.
  2252. * The result may depend on system settings
  2253. * or language. 'override' will force both names
  2254. * to be used even if system settings specify one.
  2255. *
  2256. * @uses $CFG
  2257. * @uses $SESSION
  2258. * @param object $user A {@link $USER} object to get full name of
  2259. * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
  2260. */
  2261. function fullname($user, $override=false) {
  2262. global $CFG, $SESSION;
  2263. if (!isset($user->firstname) and !isset($user->lastname)) {
  2264. return '';
  2265. }
  2266. if (!$override) {
  2267. if (!empty($CFG->forcefirstname)) {
  2268. $user->firstname = $CFG->forcefirstname;
  2269. }
  2270. if (!empty($CFG->forcelastname)) {
  2271. $user->lastname = $CFG->forcelastname;
  2272. }
  2273. }
  2274. if (!empty($SESSION->fullnamedisplay)) {
  2275. $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
  2276. }
  2277. if ($CFG->fullnamedisplay == 'firstname lastname') {
  2278. return $user->firstname .' '. $user->lastname;
  2279. } else if ($CFG->fullnamedisplay == 'lastname firstname') {
  2280. return $user->lastname .' '. $user->firstname;
  2281. } else if ($CFG->fullnamedisplay == 'firstname') {
  2282. if ($override) {
  2283. return get_string('fullnamedisplay', '', $user);
  2284. } else {
  2285. return $user->firstname;
  2286. }
  2287. }
  2288. return get_string('fullnamedisplay', '', $user);
  2289. }
  2290. /**
  2291. * Sets a moodle cookie with an encrypted string
  2292. *
  2293. * @uses $CFG
  2294. * @uses DAYSECS
  2295. * @uses HOURSECS
  2296. * @param string $thing The string to encrypt and place in a cookie
  2297. */
  2298. function set_moodle_cookie($thing) {
  2299. global $CFG;
  2300. if ($thing == 'guest') { // Ignore guest account
  2301. return;
  2302. }
  2303. $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
  2304. $days = 60;
  2305. $seconds = DAYSECS*$days;
  2306. setCookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
  2307. setCookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
  2308. }
  2309. /**
  2310. * Gets a moodle cookie with an encrypted string
  2311. *
  2312. * @uses $CFG
  2313. * @return string
  2314. */
  2315. function get_moodle_cookie() {
  2316. global $CFG;
  2317. $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
  2318. if (empty($_COOKIE[$cookiename])) {
  2319. return '';
  2320. } else {
  2321. $thing = rc4decrypt($_COOKIE[$cookiename]);
  2322. return ($thing == 'guest') ? '': $thing; // Ignore guest account
  2323. }
  2324. }
  2325. /**
  2326. * Returns whether a given authentication plugin exists.
  2327. *
  2328. * @uses $CFG
  2329. * @param string $auth Form of authentication to check for. Defaults to the
  2330. * global setting in {@link $CFG}.
  2331. * @return boolean Whether the plugin is available.
  2332. */
  2333. function exists_auth_plugin($auth) {
  2334. global $CFG;
  2335. if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
  2336. return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
  2337. }
  2338. return false;
  2339. }
  2340. /**
  2341. * Checks if a given plugin is in the list of enabled authentication plugins.
  2342. *
  2343. * @param string $auth Authentication plugin.
  2344. * @return boolean Whether the plugin is enabled.
  2345. */
  2346. function is_enabled_auth($auth) {
  2347. if (empty($auth)) {
  2348. return false;
  2349. }
  2350. $enabled = get_enabled_auth_plugins();
  2351. return in_array($auth, $enabled);
  2352. }
  2353. /**
  2354. * Returns an authentication plugin instance.
  2355. *
  2356. * @uses $CFG
  2357. * @param string $auth name of authentication plugin
  2358. * @return object An instance of the required authentication plugin.
  2359. */
  2360. function get_auth_plugin($auth) {
  2361. global $CFG;
  2362. // check the plugin exists first
  2363. if (! exists_auth_plugin($auth)) {
  2364. error("Authentication plugin '$auth' not found.");
  2365. }
  2366. // return auth plugin instance
  2367. require_once "{$CFG->dirroot}/auth/$auth/auth.php";
  2368. $class = "auth_plugin_$auth";
  2369. return new $class;
  2370. }
  2371. /**
  2372. * Returns array of active auth plugins.
  2373. *
  2374. * @param bool $fix fix $CFG->auth if needed
  2375. * @return array
  2376. */
  2377. function get_enabled_auth_plugins($fix=false) {
  2378. global $CFG;
  2379. $default = array('manual', 'nologin');
  2380. if (empty($CFG->auth)) {
  2381. $auths = array();
  2382. } else {
  2383. $auths = explode(',', $CFG->auth);
  2384. }
  2385. if ($fix) {
  2386. $auths = array_unique($auths);
  2387. foreach($auths as $k=>$authname) {
  2388. if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
  2389. unset($auths[$k]);
  2390. }
  2391. }
  2392. $newconfig = implode(',', $auths);
  2393. if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
  2394. set_config('auth', $newconfig);
  2395. }
  2396. }
  2397. return (array_merge($default, $auths));
  2398. }
  2399. /**
  2400. * Returns true if an internal authentication method is being used.
  2401. * if method not specified then, global default is assumed
  2402. *
  2403. * @uses $CFG
  2404. * @param string $auth Form of authentication required
  2405. * @return bool
  2406. */
  2407. function is_internal_auth($auth) {
  2408. $authplugin = get_auth_plugin($auth); // throws error if bad $auth
  2409. return $authplugin->is_internal();
  2410. }
  2411. /**
  2412. * Returns an array of user fields
  2413. *
  2414. * @uses $CFG
  2415. * @uses $db
  2416. * @return array User field/column names
  2417. */
  2418. function get_user_fieldnames() {
  2419. global $CFG, $db;
  2420. $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
  2421. unset($fieldarray['ID']);
  2422. return $fieldarray;
  2423. }
  2424. /**
  2425. * Creates the default "guest" user. Used both from
  2426. * admin/index.php and login/index.php
  2427. * @return mixed user object created or boolean false if the creation has failed
  2428. */
  2429. function create_guest_record() {
  2430. global $CFG;
  2431. $guest = new stdClass();
  2432. $guest->auth = 'manual';
  2433. $guest->username = 'guest';
  2434. $guest->password = hash_internal_user_password('guest');
  2435. $guest->firstname = addslashes(get_string('guestuser'));
  2436. $guest->lastname = ' ';
  2437. $guest->email = 'root@localhost';
  2438. $guest->description = addslashes(get_string('guestuserinfo'));
  2439. $guest->mnethostid = $CFG->mnet_localhost_id;
  2440. $guest->confirmed = 1;
  2441. $guest->lang = $CFG->lang;
  2442. $guest->timemodified= time();
  2443. if (! $guest->id = insert_record("user", $guest)) {
  2444. return false;
  2445. }
  2446. return $guest;
  2447. }
  2448. /**
  2449. * Creates a bare-bones user record
  2450. *
  2451. * @uses $CFG
  2452. * @param string $username New user's username to add to record
  2453. * @param string $password New user's password to add to record
  2454. * @param string $auth Form of authentication required
  2455. * @return object A {@link $USER} object
  2456. * @todo Outline auth types and provide code example
  2457. */
  2458. function create_user_record($username, $password, $auth='manual') {
  2459. global $CFG;
  2460. //just in case check text case
  2461. $username = trim(moodle_strtolower($username));
  2462. $authplugin = get_auth_plugin($auth);
  2463. if ($newinfo = $authplugin->get_userinfo($username)) {
  2464. $newinfo = truncate_userinfo($newinfo);
  2465. foreach ($newinfo as $key => $value){
  2466. $newuser->$key = addslashes($value);
  2467. }
  2468. }
  2469. if (!empty($newuser->email)) {
  2470. if (email_is_not_allowed($newuser->email)) {
  2471. unset($newuser->email);
  2472. }
  2473. }
  2474. if (!isset($newuser->city)) {
  2475. $newuser->city = '';
  2476. }
  2477. $newuser->auth = $auth;
  2478. $newuser->username = $username;
  2479. // fix for MDL-8480
  2480. // user CFG lang for user if $newuser->lang is empty
  2481. // or $user->lang is not an installed language
  2482. $sitelangs = array_keys(get_list_of_languages());
  2483. if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
  2484. $newuser -> lang = $CFG->lang;
  2485. }
  2486. $newuser->confirmed = 1;
  2487. $newuser->lastip = getremoteaddr();
  2488. $newuser->timemodified = time();
  2489. $newuser->mnethostid = $CFG->mnet_localhost_id;
  2490. if (insert_record('user', $newuser)) {
  2491. $user = get_complete_user_data('username', $newuser->username);
  2492. if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
  2493. set_user_preference('auth_forcepasswordchange', 1, $user->id);
  2494. }
  2495. update_internal_user_password($user, $password);
  2496. return $user;
  2497. }
  2498. return false;
  2499. }
  2500. /**
  2501. * Will update a local user record from an external source
  2502. *
  2503. * @uses $CFG
  2504. * @param string $username New user's username to add to record
  2505. * @return user A {@link $USER} object
  2506. */
  2507. function update_user_record($username, $authplugin) {
  2508. $username = trim(moodle_strtolower($username)); /// just in case check text case
  2509. $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
  2510. $userauth = get_auth_plugin($oldinfo->auth);
  2511. if ($newinfo = $userauth->get_userinfo($username)) {
  2512. $newinfo = truncate_userinfo($newinfo);
  2513. foreach ($newinfo as $key => $value){
  2514. if ($key === 'username') {
  2515. // 'username' is not a mapped updateable/lockable field, so skip it.
  2516. continue;
  2517. }
  2518. $confval = $userauth->config->{'field_updatelocal_' . $key};
  2519. $lockval = $userauth->config->{'field_lock_' . $key};
  2520. if (empty($confval) || empty($lockval)) {
  2521. continue;
  2522. }
  2523. if ($confval === 'onlogin') {
  2524. $value = addslashes($value);
  2525. // MDL-4207 Don't overwrite modified user profile values with
  2526. // empty LDAP values when 'unlocked if empty' is set. The purpose
  2527. // of the setting 'unlocked if empty' is to allow the user to fill
  2528. // in a value for the selected field _if LDAP is giving
  2529. // nothing_ for this field. Thus it makes sense to let this value
  2530. // stand in until LDAP is giving a value for this field.
  2531. if (!(empty($value) && $lockval === 'unlockedifempty')) {
  2532. set_field('user', $key, $value, 'username', $username)
  2533. || error_log("Error updating $key for $username");
  2534. }
  2535. }
  2536. }
  2537. }
  2538. return get_complete_user_data('username', $username);
  2539. }
  2540. function truncate_userinfo($info) {
  2541. /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
  2542. /// which may have large fields
  2543. // define the limits
  2544. $limit = array(
  2545. 'username' => 100,
  2546. 'idnumber' => 255,
  2547. 'firstname' => 100,
  2548. 'lastname' => 100,
  2549. 'email' => 100,
  2550. 'icq' => 15,
  2551. 'phone1' => 20,
  2552. 'phone2' => 20,
  2553. 'institution' => 40,
  2554. 'department' => 30,
  2555. 'address' => 70,
  2556. 'city' => 20,
  2557. 'country' => 2,
  2558. 'url' => 255,
  2559. );
  2560. // apply where needed
  2561. foreach (array_keys($info) as $key) {
  2562. if (!empty($limit[$key])) {
  2563. $info[$key] = trim(substr($info[$key],0, $limit[$key]));
  2564. }
  2565. }
  2566. return $info;
  2567. }
  2568. /**
  2569. * Marks user deleted in internal user database and notifies the auth plugin.
  2570. * Also unenrols user from all roles and does other cleanup.
  2571. * @param object $user Userobject before delete (without system magic quotes)
  2572. * @return boolean success
  2573. */
  2574. function delete_user($user) {
  2575. global $CFG;
  2576. require_once($CFG->libdir.'/grouplib.php');
  2577. require_once($CFG->libdir.'/gradelib.php');
  2578. require_once($CFG->dirroot.'/message/lib.php');
  2579. begin_sql();
  2580. // delete all grades - backup is kept in grade_grades_history table
  2581. if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
  2582. foreach ($grades as $grade) {
  2583. $grade->delete('userdelete');
  2584. }
  2585. }
  2586. //move unread messages from this user to read
  2587. message_move_userfrom_unread2read($user->id);
  2588. // remove from all groups
  2589. delete_records('groups_members', 'userid', $user->id);
  2590. // unenrol from all roles in all contexts
  2591. role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
  2592. // now do a final accesslib cleanup - removes all role assingments in user context and context itself
  2593. delete_context(CONTEXT_USER, $user->id);
  2594. require_once($CFG->dirroot.'/tag/lib.php');
  2595. tag_set('user', $user->id, array());
  2596. // workaround for bulk deletes of users with the same email address
  2597. $delname = addslashes("$user->email.".time());
  2598. while (record_exists('user', 'username', $delname)) { // no need to use mnethostid here
  2599. $delname++;
  2600. }
  2601. // mark internal user record as "deleted"
  2602. $updateuser = new object();
  2603. $updateuser->id = $user->id;
  2604. $updateuser->deleted = 1;
  2605. $updateuser->username = $delname; // Remember it just in case
  2606. $updateuser->email = ''; // Clear this field to free it up
  2607. $updateuser->idnumber = ''; // Clear this field to free it up
  2608. $updateuser->timemodified = time();
  2609. if (update_record('user', $updateuser)) {
  2610. commit_sql();
  2611. // notify auth plugin - do not block the delete even when plugin fails
  2612. $authplugin = get_auth_plugin($user->auth);
  2613. $authplugin->user_delete($user);
  2614. events_trigger('user_deleted', $user);
  2615. return true;
  2616. } else {
  2617. rollback_sql();
  2618. return false;
  2619. }
  2620. }
  2621. /**
  2622. * Retrieve the guest user object
  2623. *
  2624. * @uses $CFG
  2625. * @return user A {@link $USER} object
  2626. */
  2627. function guest_user() {
  2628. global $CFG;
  2629. if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
  2630. $newuser->confirmed = 1;
  2631. $newuser->lang = $CFG->lang;
  2632. $newuser->lastip = getremoteaddr();
  2633. }
  2634. return $newuser;
  2635. }
  2636. /**
  2637. * Given a username and password, this function looks them
  2638. * up using the currently selected authentication mechanism,
  2639. * and if the authentication is successful, it returns a
  2640. * valid $user object from the 'user' table.
  2641. *
  2642. * Uses auth_ functions from the currently active auth module
  2643. *
  2644. * After authenticate_user_login() returns success, you will need to
  2645. * log that the user has logged in, and call complete_user_login() to set
  2646. * the session up.
  2647. *
  2648. * @uses $CFG
  2649. * @param string $username User's username (with system magic quotes)
  2650. * @param string $password User's password (with system magic quotes)
  2651. * @return user|flase A {@link $USER} object or false if error
  2652. */
  2653. function authenticate_user_login($username, $password) {
  2654. global $CFG;
  2655. $authsenabled = get_enabled_auth_plugins();
  2656. if ($user = get_complete_user_data('username', $username)) {
  2657. $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
  2658. if ($auth=='nologin' or !is_enabled_auth($auth)) {
  2659. add_to_log(0, 'login', 'error', 'index.php', $username);
  2660. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  2661. return false;
  2662. }
  2663. $auths = array($auth);
  2664. } else {
  2665. // check if there's a deleted record (cheaply)
  2666. if (get_field('user', 'id', 'username', $username, 'deleted', 1, '')) {
  2667. error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  2668. return false;
  2669. }
  2670. $auths = $authsenabled;
  2671. $user = new object();
  2672. $user->id = 0; // User does not exist
  2673. }
  2674. foreach ($auths as $auth) {
  2675. $authplugin = get_auth_plugin($auth);
  2676. // on auth fail fall through to the next plugin
  2677. if (!$authplugin->user_login($username, $password)) {
  2678. continue;
  2679. }
  2680. // successful authentication
  2681. if ($user->id) { // User already exists in database
  2682. if (empty($user->auth)) { // For some reason auth isn't set yet
  2683. set_field('user', 'auth', $auth, 'username', $username);
  2684. $user->auth = $auth;
  2685. }
  2686. if (empty($user->firstaccess)) { //prevent firstaccess from remaining 0 for manual account that never required confirmation
  2687. set_field('user','firstaccess', $user->timemodified, 'id', $user->id);
  2688. $user->firstaccess = $user->timemodified;
  2689. }
  2690. update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
  2691. if (!$authplugin->is_internal()) { // update user record from external DB
  2692. $user = update_user_record($username, get_auth_plugin($user->auth));
  2693. }
  2694. } else {
  2695. // if user not found, create him
  2696. $user = create_user_record($username, $password, $auth);
  2697. }
  2698. $authplugin->sync_roles($user);
  2699. foreach ($authsenabled as $hau) {
  2700. $hauth = get_auth_plugin($hau);
  2701. $hauth->user_authenticated_hook($user, $username, $password);
  2702. }
  2703. /// Log in to a second system if necessary
  2704. /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
  2705. if (!empty($CFG->sso)) {
  2706. include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
  2707. if (function_exists('sso_user_login')) {
  2708. if (!sso_user_login($username, $password)) { // Perform the signon process
  2709. notify('Second sign-on failed');
  2710. }
  2711. }
  2712. }
  2713. if ($user->id===0) {
  2714. return false;
  2715. }
  2716. return $user;
  2717. }
  2718. // failed if all the plugins have failed
  2719. add_to_log(0, 'login', 'error', 'index.php', $username);
  2720. if (debugging('', DEBUG_ALL)) {
  2721. error_log('[client '.getremoteaddr()."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
  2722. }
  2723. return false;
  2724. }
  2725. /**
  2726. * Call to complete the user login process after authenticate_user_login()
  2727. * has succeeded. It will setup the $USER variable and other required bits
  2728. * and pieces.
  2729. *
  2730. * NOTE:
  2731. * - It will NOT log anything -- up to the caller to decide what to log.
  2732. *
  2733. *
  2734. *
  2735. * @uses $CFG, $USER
  2736. * @param string $user obj
  2737. * @return user|flase A {@link $USER} object or false if error
  2738. */
  2739. function complete_user_login($user) {
  2740. global $CFG, $USER;
  2741. $USER = $user; // this is required because we need to access preferences here!
  2742. if (!empty($CFG->regenloginsession)) {
  2743. // please note this setting may break some auth plugins
  2744. session_regenerate_id();
  2745. }
  2746. reload_user_preferences();
  2747. update_user_login_times();
  2748. if (empty($CFG->nolastloggedin)) {
  2749. set_moodle_cookie($USER->username);
  2750. } else {
  2751. // do not store last logged in user in cookie
  2752. // auth plugins can temporarily override this from loginpage_hook()
  2753. // do not save $CFG->nolastloggedin in database!
  2754. set_moodle_cookie('nobody');
  2755. }
  2756. set_login_session_preferences();
  2757. // Call enrolment plugins
  2758. check_enrolment_plugins($user);
  2759. /// This is what lets the user do anything on the site :-)
  2760. load_all_capabilities();
  2761. /// Select password change url
  2762. $userauth = get_auth_plugin($USER->auth);
  2763. /// check whether the user should be changing password
  2764. if (get_user_preferences('auth_forcepasswordchange', false)){
  2765. if ($userauth->can_change_password()) {
  2766. if ($changeurl = $userauth->change_password_url()) {
  2767. redirect($changeurl);
  2768. } else {
  2769. redirect($CFG->httpswwwroot.'/login/change_password.php');
  2770. }
  2771. } else {
  2772. print_error('nopasswordchangeforced', 'auth');
  2773. }
  2774. }
  2775. return $USER;
  2776. }
  2777. /**
  2778. * Compare password against hash stored in internal user table.
  2779. * If necessary it also updates the stored hash to new format.
  2780. *
  2781. * @param object user
  2782. * @param string plain text password
  2783. * @return bool is password valid?
  2784. */
  2785. function validate_internal_user_password(&$user, $password) {
  2786. global $CFG;
  2787. if (!isset($CFG->passwordsaltmain)) {
  2788. $CFG->passwordsaltmain = '';
  2789. }
  2790. $validated = false;
  2791. // get password original encoding in case it was not updated to unicode yet
  2792. $textlib = textlib_get_instance();
  2793. $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
  2794. if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
  2795. or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
  2796. $validated = true;
  2797. } else {
  2798. for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
  2799. $alt = 'passwordsaltalt'.$i;
  2800. if (!empty($CFG->$alt)) {
  2801. if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
  2802. $validated = true;
  2803. break;
  2804. }
  2805. }
  2806. }
  2807. }
  2808. if ($validated) {
  2809. // force update of password hash using latest main password salt and encoding if needed
  2810. update_internal_user_password($user, $password);
  2811. }
  2812. return $validated;
  2813. }
  2814. /**
  2815. * Calculate hashed value from password using current hash mechanism.
  2816. *
  2817. * @param string password
  2818. * @return string password hash
  2819. */
  2820. function hash_internal_user_password($password) {
  2821. global $CFG;
  2822. if (isset($CFG->passwordsaltmain)) {
  2823. return md5($password.$CFG->passwordsaltmain);
  2824. } else {
  2825. return md5($password);
  2826. }
  2827. }
  2828. /**
  2829. * Update pssword hash in user object.
  2830. *
  2831. * @param object user
  2832. * @param string plain text password
  2833. * @param bool store changes also in db, default true
  2834. * @return true if hash changed
  2835. */
  2836. function update_internal_user_password(&$user, $password) {
  2837. global $CFG;
  2838. $authplugin = get_auth_plugin($user->auth);
  2839. if (!empty($authplugin->config->preventpassindb)) {
  2840. $hashedpassword = 'not cached';
  2841. } else {
  2842. $hashedpassword = hash_internal_user_password($password);
  2843. }
  2844. return set_field('user', 'password', $hashedpassword, 'id', $user->id);
  2845. }
  2846. /**
  2847. * Get a complete user record, which includes all the info
  2848. * in the user record
  2849. * Intended for setting as $USER session variable
  2850. *
  2851. * @uses $CFG
  2852. * @uses SITEID
  2853. * @param string $field The user field to be checked for a given value.
  2854. * @param string $value The value to match for $field.
  2855. * @return user A {@link $USER} object.
  2856. */
  2857. function get_complete_user_data($field, $value, $mnethostid=null) {
  2858. global $CFG;
  2859. if (!$field || !$value) {
  2860. return false;
  2861. }
  2862. /// Build the WHERE clause for an SQL query
  2863. $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
  2864. // If we are loading user data based on anything other than id,
  2865. // we must also restrict our search based on mnet host.
  2866. if ($field != 'id') {
  2867. if (empty($mnethostid)) {
  2868. // if empty, we restrict to local users
  2869. $mnethostid = $CFG->mnet_localhost_id;
  2870. }
  2871. }
  2872. if (!empty($mnethostid)) {
  2873. $mnethostid = (int)$mnethostid;
  2874. $constraints .= ' AND mnethostid = ' . $mnethostid;
  2875. }
  2876. /// Get all the basic user data
  2877. if (! $user = get_record_select('user', $constraints)) {
  2878. return false;
  2879. }
  2880. /// Get various settings and preferences
  2881. if ($displays = get_records('course_display', 'userid', $user->id)) {
  2882. foreach ($displays as $display) {
  2883. $user->display[$display->course] = $display->display;
  2884. }
  2885. }
  2886. $user->preference = get_user_preferences(null, null, $user->id);
  2887. $user->lastcourseaccess = array(); // during last session
  2888. $user->currentcourseaccess = array(); // during current session
  2889. if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
  2890. foreach ($lastaccesses as $lastaccess) {
  2891. $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
  2892. }
  2893. }
  2894. $sql = "SELECT g.id, g.courseid
  2895. FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
  2896. WHERE gm.groupid=g.id AND gm.userid={$user->id}";
  2897. // this is a special hack to speedup calendar display
  2898. $user->groupmember = array();
  2899. if ($groups = get_records_sql($sql)) {
  2900. foreach ($groups as $group) {
  2901. if (!array_key_exists($group->courseid, $user->groupmember)) {
  2902. $user->groupmember[$group->courseid] = array();
  2903. }
  2904. $user->groupmember[$group->courseid][$group->id] = $group->id;
  2905. }
  2906. }
  2907. /// Add the custom profile fields to the user record
  2908. include_once($CFG->dirroot.'/user/profile/lib.php');
  2909. $customfields = (array)profile_user_record($user->id);
  2910. foreach ($customfields as $cname=>$cvalue) {
  2911. if (!isset($user->$cname)) { // Don't overwrite any standard fields
  2912. $user->$cname = $cvalue;
  2913. }
  2914. }
  2915. /// Rewrite some variables if necessary
  2916. if (!empty($user->description)) {
  2917. $user->description = true; // No need to cart all of it around
  2918. }
  2919. if ($user->username == 'guest') {
  2920. $user->lang = $CFG->lang; // Guest language always same as site
  2921. $user->firstname = get_string('guestuser'); // Name always in current language
  2922. $user->lastname = ' ';
  2923. }
  2924. if (isset($_SERVER['REMOTE_ADDR'])) {
  2925. $user->sesskey = random_string(10);
  2926. $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
  2927. }
  2928. return $user;
  2929. }
  2930. /**
  2931. * @uses $CFG
  2932. * @param string $password the password to be checked agains the password policy
  2933. * @param string $errmsg the error message to display when the password doesn't comply with the policy.
  2934. * @return bool true if the password is valid according to the policy. false otherwise.
  2935. */
  2936. function check_password_policy($password, &$errmsg) {
  2937. global $CFG;
  2938. if (empty($CFG->passwordpolicy)) {
  2939. return true;
  2940. }
  2941. $textlib = textlib_get_instance();
  2942. $errmsg = '';
  2943. if ($textlib->strlen($password) < $CFG->minpasswordlength) {
  2944. $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
  2945. }
  2946. if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
  2947. $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
  2948. }
  2949. if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
  2950. $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
  2951. }
  2952. if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
  2953. $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
  2954. }
  2955. if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
  2956. $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
  2957. }
  2958. if ($errmsg == '') {
  2959. return true;
  2960. } else {
  2961. return false;
  2962. }
  2963. }
  2964. /**
  2965. * When logging in, this function is run to set certain preferences
  2966. * for the current SESSION
  2967. */
  2968. function set_login_session_preferences() {
  2969. global $SESSION, $CFG;
  2970. $SESSION->justloggedin = true;
  2971. unset($SESSION->lang);
  2972. // Restore the calendar filters, if saved
  2973. if (intval(get_user_preferences('calendar_persistflt', 0))) {
  2974. include_once($CFG->dirroot.'/calendar/lib.php');
  2975. calendar_set_filters_status(get_user_preferences('calendar_savedflt', 0xff));
  2976. }
  2977. }
  2978. /**
  2979. * Delete a course, including all related data from the database,
  2980. * and any associated files from the moodledata folder.
  2981. *
  2982. * @param mixed $courseorid The id of the course or course object to delete.
  2983. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  2984. * @return bool true if all the removals succeeded. false if there were any failures. If this
  2985. * method returns false, some of the removals will probably have succeeded, and others
  2986. * failed, but you have no way of knowing which.
  2987. */
  2988. function delete_course($courseorid, $showfeedback = true) {
  2989. global $CFG;
  2990. $result = true;
  2991. if (is_object($courseorid)) {
  2992. $courseid = $courseorid->id;
  2993. $course = $courseorid;
  2994. } else {
  2995. $courseid = $courseorid;
  2996. if (!$course = get_record('course', 'id', $courseid)) {
  2997. return false;
  2998. }
  2999. }
  3000. // frontpage course can not be deleted!!
  3001. if ($courseid == SITEID) {
  3002. return false;
  3003. }
  3004. if (!remove_course_contents($courseid, $showfeedback)) {
  3005. if ($showfeedback) {
  3006. notify("An error occurred while deleting some of the course contents.");
  3007. }
  3008. $result = false;
  3009. }
  3010. if (!delete_records("course", "id", $courseid)) {
  3011. if ($showfeedback) {
  3012. notify("An error occurred while deleting the main course record.");
  3013. }
  3014. $result = false;
  3015. }
  3016. /// Delete all roles and overiddes in the course context
  3017. if (!delete_context(CONTEXT_COURSE, $courseid)) {
  3018. if ($showfeedback) {
  3019. notify("An error occurred while deleting the main course context.");
  3020. }
  3021. $result = false;
  3022. }
  3023. if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
  3024. if ($showfeedback) {
  3025. notify("An error occurred while deleting the course files.");
  3026. }
  3027. $result = false;
  3028. }
  3029. if ($result) {
  3030. //trigger events
  3031. events_trigger('course_deleted', $course);
  3032. }
  3033. return $result;
  3034. }
  3035. /**
  3036. * Clear a course out completely, deleting all content
  3037. * but don't delete the course itself
  3038. *
  3039. * @uses $CFG
  3040. * @param int $courseid The id of the course that is being deleted
  3041. * @param bool $showfeedback Whether to display notifications of each action the function performs.
  3042. * @return bool true if all the removals succeeded. false if there were any failures. If this
  3043. * method returns false, some of the removals will probably have succeeded, and others
  3044. * failed, but you have no way of knowing which.
  3045. */
  3046. function remove_course_contents($courseid, $showfeedback=true) {
  3047. global $CFG;
  3048. require_once($CFG->libdir.'/questionlib.php');
  3049. require_once($CFG->libdir.'/gradelib.php');
  3050. $result = true;
  3051. if (! $course = get_record('course', 'id', $courseid)) {
  3052. error('Course ID was incorrect (can\'t find it)');
  3053. }
  3054. $strdeleted = get_string('deleted');
  3055. /// Clean up course formats (iterate through all formats in the even the course format was ever changed)
  3056. $formats = get_list_of_plugins('course/format');
  3057. foreach ($formats as $format) {
  3058. $formatdelete = $format.'_course_format_delete_course';
  3059. $formatlib = "$CFG->dirroot/course/format/$format/lib.php";
  3060. if (file_exists($formatlib)) {
  3061. include_once($formatlib);
  3062. if (function_exists($formatdelete)) {
  3063. if ($showfeedback) {
  3064. notify($strdeleted.' '.$format);
  3065. }
  3066. $formatdelete($course->id);
  3067. }
  3068. }
  3069. }
  3070. /// Delete every instance of every module
  3071. if ($allmods = get_records('modules') ) {
  3072. foreach ($allmods as $mod) {
  3073. $modname = $mod->name;
  3074. $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
  3075. $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
  3076. $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
  3077. $count=0;
  3078. if (file_exists($modfile)) {
  3079. include_once($modfile);
  3080. if (function_exists($moddelete)) {
  3081. if ($instances = get_records($modname, 'course', $course->id)) {
  3082. foreach ($instances as $instance) {
  3083. if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
  3084. /// Delete activity context questions and question categories
  3085. question_delete_activity($cm, $showfeedback);
  3086. }
  3087. if ($moddelete($instance->id)) {
  3088. $count++;
  3089. } else {
  3090. notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
  3091. $result = false;
  3092. }
  3093. if ($cm) {
  3094. // delete cm and its context in correct order
  3095. delete_records('course_modules', 'id', $cm->id);
  3096. delete_context(CONTEXT_MODULE, $cm->id);
  3097. }
  3098. }
  3099. }
  3100. } else {
  3101. notify('Function '.$moddelete.'() doesn\'t exist!');
  3102. $result = false;
  3103. }
  3104. if (function_exists($moddeletecourse)) {
  3105. $moddeletecourse($course, $showfeedback);
  3106. }
  3107. }
  3108. if ($showfeedback) {
  3109. notify($strdeleted .' '. $count .' x '. $modname);
  3110. }
  3111. }
  3112. } else {
  3113. error('No modules are installed!');
  3114. }
  3115. /// Give local code a chance to delete its references to this course.
  3116. require_once($CFG->libdir.'/locallib.php');
  3117. notify_local_delete_course($courseid, $showfeedback);
  3118. /// Delete course blocks
  3119. if ($blocks = get_records_sql("SELECT *
  3120. FROM {$CFG->prefix}block_instance
  3121. WHERE pagetype = '".PAGE_COURSE_VIEW."'
  3122. AND pageid = $course->id")) {
  3123. if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
  3124. if ($showfeedback) {
  3125. notify($strdeleted .' block_instance');
  3126. }
  3127. require_once($CFG->libdir.'/blocklib.php');
  3128. foreach ($blocks as $block) { /// Delete any associated contexts for this block
  3129. delete_context(CONTEXT_BLOCK, $block->id);
  3130. // fix for MDL-7164
  3131. // Get the block object and call instance_delete()
  3132. if (!$record = blocks_get_record($block->blockid)) {
  3133. $result = false;
  3134. continue;
  3135. }
  3136. if (!$obj = block_instance($record->name, $block)) {
  3137. $result = false;
  3138. continue;
  3139. }
  3140. // Return value ignored, in core mods this does not do anything, but just in case
  3141. // third party blocks might have stuff to clean up
  3142. // we execute this anyway
  3143. $obj->instance_delete();
  3144. }
  3145. } else {
  3146. $result = false;
  3147. }
  3148. }
  3149. /// Delete any groups, removing members and grouping/course links first.
  3150. require_once($CFG->dirroot.'/group/lib.php');
  3151. groups_delete_groupings($courseid, $showfeedback);
  3152. groups_delete_groups($courseid, $showfeedback);
  3153. /// Delete all related records in other tables that may have a courseid
  3154. /// This array stores the tables that need to be cleared, as
  3155. /// table_name => column_name that contains the course id.
  3156. $tablestoclear = array(
  3157. 'event' => 'courseid', // Delete events
  3158. 'log' => 'course', // Delete logs
  3159. 'course_sections' => 'course', // Delete any course stuff
  3160. 'course_modules' => 'course',
  3161. 'backup_courses' => 'courseid', // Delete scheduled backup stuff
  3162. 'user_lastaccess' => 'courseid',
  3163. 'backup_log' => 'courseid'
  3164. );
  3165. foreach ($tablestoclear as $table => $col) {
  3166. if (delete_records($table, $col, $course->id)) {
  3167. if ($showfeedback) {
  3168. notify($strdeleted . ' ' . $table);
  3169. }
  3170. } else {
  3171. $result = false;
  3172. }
  3173. }
  3174. /// Clean up metacourse stuff
  3175. if ($course->metacourse) {
  3176. delete_records("course_meta","parent_course",$course->id);
  3177. sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
  3178. if ($showfeedback) {
  3179. notify("$strdeleted course_meta");
  3180. }
  3181. } else {
  3182. if ($parents = get_records("course_meta","child_course",$course->id)) {
  3183. foreach ($parents as $parent) {
  3184. remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
  3185. }
  3186. if ($showfeedback) {
  3187. notify("$strdeleted course_meta");
  3188. }
  3189. }
  3190. }
  3191. /// Delete questions and question categories
  3192. question_delete_course($course, $showfeedback);
  3193. /// Remove all data from gradebook
  3194. $context = get_context_instance(CONTEXT_COURSE, $courseid);
  3195. remove_course_grades($courseid, $showfeedback);
  3196. remove_grade_letters($context, $showfeedback);
  3197. return $result;
  3198. }
  3199. /**
  3200. * Change dates in module - used from course reset.
  3201. * @param strin $modname forum, assignent, etc
  3202. * @param array $fields array of date fields from mod table
  3203. * @param int $timeshift time difference
  3204. * @return success
  3205. */
  3206. function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
  3207. global $CFG;
  3208. include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
  3209. $return = true;
  3210. foreach ($fields as $field) {
  3211. $updatesql = "UPDATE {$CFG->prefix}$modname
  3212. SET $field = $field + ($timeshift)
  3213. WHERE course=$courseid AND $field<>0 AND $field<>0";
  3214. $return = execute_sql($updatesql, false) && $return;
  3215. }
  3216. $refreshfunction = $modname.'_refresh_events';
  3217. if (function_exists($refreshfunction)) {
  3218. $refreshfunction($courseid);
  3219. }
  3220. return $return;
  3221. }
  3222. /**
  3223. * This function will empty a course of user data.
  3224. * It will retain the activities and the structure of the course.
  3225. * @param object $data an object containing all the settings including courseid (without magic quotes)
  3226. * @return array status array of array component, item, error
  3227. */
  3228. function reset_course_userdata($data) {
  3229. global $CFG, $USER;
  3230. require_once($CFG->libdir.'/gradelib.php');
  3231. require_once($CFG->dirroot.'/group/lib.php');
  3232. $data->courseid = $data->id;
  3233. $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
  3234. // calculate the time shift of dates
  3235. if (!empty($data->reset_start_date)) {
  3236. // time part of course startdate should be zero
  3237. $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
  3238. } else {
  3239. $data->timeshift = 0;
  3240. }
  3241. // result array: component, item, error
  3242. $status = array();
  3243. // start the resetting
  3244. $componentstr = get_string('general');
  3245. // move the course start time
  3246. if (!empty($data->reset_start_date) and $data->timeshift) {
  3247. // change course start data
  3248. set_field('course', 'startdate', $data->reset_start_date, 'id', $data->courseid);
  3249. // update all course and group events - do not move activity events
  3250. $updatesql = "UPDATE {$CFG->prefix}event
  3251. SET timestart = timestart + ({$data->timeshift})
  3252. WHERE courseid={$data->courseid} AND instance=0";
  3253. execute_sql($updatesql, false);
  3254. $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
  3255. }
  3256. if (!empty($data->reset_logs)) {
  3257. delete_records('log', 'course', $data->courseid);
  3258. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelogs'), 'error'=>false);
  3259. }
  3260. if (!empty($data->reset_events)) {
  3261. delete_records('event', 'courseid', $data->courseid);
  3262. $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteevents', 'calendar'), 'error'=>false);
  3263. }
  3264. if (!empty($data->reset_notes)) {
  3265. require_once($CFG->dirroot.'/notes/lib.php');
  3266. note_delete_all($data->courseid);
  3267. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotes', 'notes'), 'error'=>false);
  3268. }
  3269. $componentstr = get_string('roles');
  3270. if (!empty($data->reset_roles_overrides)) {
  3271. $children = get_child_contexts($context);
  3272. foreach ($children as $child) {
  3273. delete_records('role_capabilities', 'contextid', $child->id);
  3274. }
  3275. delete_records('role_capabilities', 'contextid', $context->id);
  3276. //force refresh for logged in users
  3277. mark_context_dirty($context->path);
  3278. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecourseoverrides', 'role'), 'error'=>false);
  3279. }
  3280. if (!empty($data->reset_roles_local)) {
  3281. $children = get_child_contexts($context);
  3282. foreach ($children as $child) {
  3283. role_unassign(0, 0, 0, $child->id);
  3284. }
  3285. //force refresh for logged in users
  3286. mark_context_dirty($context->path);
  3287. $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelocalroles', 'role'), 'error'=>false);
  3288. }
  3289. // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
  3290. $data->unenrolled = array();
  3291. if (!empty($data->reset_roles)) {
  3292. foreach($data->reset_roles as $roleid) {
  3293. if ($users = get_role_users($roleid, $context, false, 'u.id', 'u.id ASC')) {
  3294. foreach ($users as $user) {
  3295. role_unassign($roleid, $user->id, 0, $context->id);
  3296. if (!has_capability('moodle/course:view', $context, $user->id)) {
  3297. $data->unenrolled[$user->id] = $user->id;
  3298. }
  3299. }
  3300. }
  3301. }
  3302. }
  3303. if (!empty($data->unenrolled)) {
  3304. $status[] = array('component'=>$componentstr, 'item'=>get_string('unenrol').' ('.count($data->unenrolled).')', 'error'=>false);
  3305. }
  3306. $componentstr = get_string('groups');
  3307. // remove all group members
  3308. if (!empty($data->reset_groups_members)) {
  3309. groups_delete_group_members($data->courseid);
  3310. $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupsmembers', 'group'), 'error'=>false);
  3311. }
  3312. // remove all groups
  3313. if (!empty($data->reset_groups_remove)) {
  3314. groups_delete_groups($data->courseid, false);
  3315. $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroups', 'group'), 'error'=>false);
  3316. }
  3317. // remove all grouping members
  3318. if (!empty($data->reset_groupings_members)) {
  3319. groups_delete_groupings_groups($data->courseid, false);
  3320. $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupingsmembers', 'group'), 'error'=>false);
  3321. }
  3322. // remove all groupings
  3323. if (!empty($data->reset_groupings_remove)) {
  3324. groups_delete_groupings($data->courseid, false);
  3325. $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroupings', 'group'), 'error'=>false);
  3326. }
  3327. // Look in every instance of every module for data to delete
  3328. $unsupported_mods = array();
  3329. if ($allmods = get_records('modules') ) {
  3330. foreach ($allmods as $mod) {
  3331. $modname = $mod->name;
  3332. if (!count_records($modname, 'course', $data->courseid)) {
  3333. continue; // skip mods with no instances
  3334. }
  3335. $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
  3336. $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data
  3337. if (file_exists($modfile)) {
  3338. include_once($modfile);
  3339. if (function_exists($moddeleteuserdata)) {
  3340. $modstatus = $moddeleteuserdata($data);
  3341. if (is_array($modstatus)) {
  3342. $status = array_merge($status, $modstatus);
  3343. } else {
  3344. debugging('Module '.$modname.' returned incorrect staus - must be an array!');
  3345. }
  3346. } else {
  3347. $unsupported_mods[] = $mod;
  3348. }
  3349. } else {
  3350. debugging('Missing lib.php in '.$modname.' module!');
  3351. }
  3352. }
  3353. }
  3354. // mention unsupported mods
  3355. if (!empty($unsupported_mods)) {
  3356. foreach($unsupported_mods as $mod) {
  3357. $status[] = array('component'=>get_string('modulenameplural', $mod->name), 'item'=>'', 'error'=>get_string('resetnotimplemented'));
  3358. }
  3359. }
  3360. $componentstr = get_string('gradebook', 'grades');
  3361. // reset gradebook
  3362. if (!empty($data->reset_gradebook_items)) {
  3363. remove_course_grades($data->courseid, false);
  3364. grade_grab_course_grades($data->courseid);
  3365. grade_regrade_final_grades($data->courseid);
  3366. $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcourseitems', 'grades'), 'error'=>false);
  3367. } else if (!empty($data->reset_gradebook_grades)) {
  3368. grade_course_reset($data->courseid);
  3369. $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcoursegrades', 'grades'), 'error'=>false);
  3370. }
  3371. return $status;
  3372. }
  3373. function generate_email_processing_address($modid,$modargs) {
  3374. global $CFG;
  3375. $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
  3376. return $header . substr(md5($header.get_site_identifier()),0,16).'@'.$CFG->maildomain;
  3377. }
  3378. function moodle_process_email($modargs,$body) {
  3379. // the first char should be an unencoded letter. We'll take this as an action
  3380. switch ($modargs{0}) {
  3381. case 'B': { // bounce
  3382. list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
  3383. if ($user = get_record_select("user","id=$userid","id,email")) {
  3384. // check the half md5 of their email
  3385. $md5check = substr(md5($user->email),0,16);
  3386. if ($md5check == substr($modargs, -16)) {
  3387. set_bounce_count($user);
  3388. }
  3389. // else maybe they've already changed it?
  3390. }
  3391. }
  3392. break;
  3393. // maybe more later?
  3394. }
  3395. }
  3396. /// CORRESPONDENCE ////////////////////////////////////////////////
  3397. /**
  3398. * Get mailer instance, enable buffering, flush buffer or disable buffering.
  3399. * @param $action string 'get', 'buffer', 'close' or 'flush'
  3400. * @return reference to mailer instance if 'get' used or nothing
  3401. */
  3402. function &get_mailer($action='get') {
  3403. global $CFG;
  3404. static $mailer = null;
  3405. static $counter = 0;
  3406. if (!isset($CFG->smtpmaxbulk)) {
  3407. $CFG->smtpmaxbulk = 1;
  3408. }
  3409. if ($action == 'get') {
  3410. $prevkeepalive = false;
  3411. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  3412. if ($counter < $CFG->smtpmaxbulk and empty($mailer->error_count)) {
  3413. $counter++;
  3414. // reset the mailer
  3415. $mailer->Priority = 3;
  3416. $mailer->CharSet = 'UTF-8'; // our default
  3417. $mailer->ContentType = "text/plain";
  3418. $mailer->Encoding = "8bit";
  3419. $mailer->From = "root@localhost";
  3420. $mailer->FromName = "Root User";
  3421. $mailer->Sender = "";
  3422. $mailer->Subject = "";
  3423. $mailer->Body = "";
  3424. $mailer->AltBody = "";
  3425. $mailer->ConfirmReadingTo = "";
  3426. $mailer->ClearAllRecipients();
  3427. $mailer->ClearReplyTos();
  3428. $mailer->ClearAttachments();
  3429. $mailer->ClearCustomHeaders();
  3430. return $mailer;
  3431. }
  3432. $prevkeepalive = $mailer->SMTPKeepAlive;
  3433. get_mailer('flush');
  3434. }
  3435. include_once($CFG->libdir.'/phpmailer/class.phpmailer.php');
  3436. $mailer = new phpmailer();
  3437. $counter = 1;
  3438. $mailer->Version = 'Moodle '.$CFG->version; // mailer version
  3439. $mailer->PluginDir = $CFG->libdir.'/phpmailer/'; // plugin directory (eg smtp plugin)
  3440. $mailer->CharSet = 'UTF-8';
  3441. // some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis
  3442. // hmm, this is a bit hacky because LE should be private
  3443. if (isset($CFG->mailnewline) and $CFG->mailnewline == 'CRLF') {
  3444. $mailer->LE = "\r\n";
  3445. } else {
  3446. $mailer->LE = "\n";
  3447. }
  3448. if ($CFG->smtphosts == 'qmail') {
  3449. $mailer->IsQmail(); // use Qmail system
  3450. } else if (empty($CFG->smtphosts)) {
  3451. $mailer->IsMail(); // use PHP mail() = sendmail
  3452. } else {
  3453. $mailer->IsSMTP(); // use SMTP directly
  3454. if (!empty($CFG->debugsmtp)) {
  3455. $mailer->SMTPDebug = true;
  3456. }
  3457. $mailer->Host = $CFG->smtphosts; // specify main and backup servers
  3458. $mailer->SMTPKeepAlive = $prevkeepalive; // use previous keepalive
  3459. if ($CFG->smtpuser) { // Use SMTP authentication
  3460. $mailer->SMTPAuth = true;
  3461. $mailer->Username = $CFG->smtpuser;
  3462. $mailer->Password = $CFG->smtppass;
  3463. }
  3464. }
  3465. return $mailer;
  3466. }
  3467. $nothing = null;
  3468. // keep smtp session open after sending
  3469. if ($action == 'buffer') {
  3470. if (!empty($CFG->smtpmaxbulk)) {
  3471. get_mailer('flush');
  3472. $m =& get_mailer();
  3473. if ($m->Mailer == 'smtp') {
  3474. $m->SMTPKeepAlive = true;
  3475. }
  3476. }
  3477. return $nothing;
  3478. }
  3479. // close smtp session, but continue buffering
  3480. if ($action == 'flush') {
  3481. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  3482. if (!empty($mailer->SMTPDebug)) {
  3483. echo '<pre>'."\n";
  3484. }
  3485. $mailer->SmtpClose();
  3486. if (!empty($mailer->SMTPDebug)) {
  3487. echo '</pre>';
  3488. }
  3489. }
  3490. return $nothing;
  3491. }
  3492. // close smtp session, do not buffer anymore
  3493. if ($action == 'close') {
  3494. if (isset($mailer) and $mailer->Mailer == 'smtp') {
  3495. get_mailer('flush');
  3496. $mailer->SMTPKeepAlive = false;
  3497. }
  3498. $mailer = null; // better force new instance
  3499. return $nothing;
  3500. }
  3501. }
  3502. /**
  3503. * Send an email to a specified user
  3504. *
  3505. * @uses $CFG
  3506. * @uses $FULLME
  3507. * @uses $MNETIDPJUMPURL IdentityProvider(IDP) URL user hits to jump to mnet peer.
  3508. * @uses SITEID
  3509. * @param user $user A {@link $USER} object
  3510. * @param user $from A {@link $USER} object
  3511. * @param string $subject plain text subject line of the email
  3512. * @param string $messagetext plain text version of the message
  3513. * @param string $messagehtml complete html version of the message (optional)
  3514. * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
  3515. * @param string $attachname the name of the file (extension indicates MIME)
  3516. * @param bool $usetrueaddress determines whether $from email address should
  3517. * be sent out. Will be overruled by user profile setting for maildisplay
  3518. * @param int $wordwrapwidth custom word wrap width
  3519. * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
  3520. * was blocked by user and "false" if there was another sort of error.
  3521. */
  3522. function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='', $wordwrapwidth=79) {
  3523. global $CFG, $FULLME, $MNETIDPJUMPURL;
  3524. static $mnetjumps = array();
  3525. if (empty($user) || empty($user->email)) {
  3526. return false;
  3527. }
  3528. if (!empty($user->deleted)) {
  3529. // do not mail delted users
  3530. return false;
  3531. }
  3532. if (!empty($CFG->noemailever)) {
  3533. // hidden setting for development sites, set in config.php if needed
  3534. return true;
  3535. }
  3536. // skip mail to suspended users
  3537. if (isset($user->auth) && $user->auth=='nologin') {
  3538. return true;
  3539. }
  3540. if (!empty($user->emailstop)) {
  3541. return 'emailstop';
  3542. }
  3543. if (over_bounce_threshold($user)) {
  3544. error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
  3545. return false;
  3546. }
  3547. // If the user is a remote mnet user, parse the email text for URL to the
  3548. // wwwroot and modify the url to direct the user's browser to login at their
  3549. // home site (identity provider - idp) before hitting the link itself
  3550. if (is_mnet_remote_user($user)) {
  3551. require_once($CFG->dirroot.'/mnet/lib.php');
  3552. // Form the request url to hit the idp's jump.php
  3553. if (isset($mnetjumps[$user->mnethostid])) {
  3554. $MNETIDPJUMPURL = $mnetjumps[$user->mnethostid];
  3555. } else {
  3556. $idp = mnet_get_peer_host($user->mnethostid);
  3557. $idpjumppath = '/auth/mnet/jump.php';
  3558. $MNETIDPJUMPURL = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
  3559. $mnetjumps[$user->mnethostid] = $MNETIDPJUMPURL;
  3560. }
  3561. $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
  3562. 'mnet_sso_apply_indirection',
  3563. $messagetext);
  3564. $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
  3565. 'mnet_sso_apply_indirection',
  3566. $messagehtml);
  3567. }
  3568. $mail =& get_mailer();
  3569. if (!empty($mail->SMTPDebug)) {
  3570. echo '<pre>' . "\n";
  3571. }
  3572. /// We are going to use textlib services here
  3573. $textlib = textlib_get_instance();
  3574. $supportuser = generate_email_supportuser();
  3575. // make up an email address for handling bounces
  3576. if (!empty($CFG->handlebounces)) {
  3577. $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
  3578. $mail->Sender = generate_email_processing_address(0,$modargs);
  3579. } else {
  3580. $mail->Sender = $supportuser->email;
  3581. }
  3582. if (is_string($from)) { // So we can pass whatever we want if there is need
  3583. $mail->From = $CFG->noreplyaddress;
  3584. $mail->FromName = $from;
  3585. } else if ($usetrueaddress and $from->maildisplay) {
  3586. $mail->From = stripslashes($from->email);
  3587. $mail->FromName = fullname($from);
  3588. } else {
  3589. $mail->From = $CFG->noreplyaddress;
  3590. $mail->FromName = fullname($from);
  3591. if (empty($replyto)) {
  3592. $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
  3593. }
  3594. }
  3595. if (!empty($replyto)) {
  3596. $mail->AddReplyTo($replyto,$replytoname);
  3597. }
  3598. $mail->Subject = substr(stripslashes($subject), 0, 900);
  3599. $mail->AddAddress(stripslashes($user->email), fullname($user) );
  3600. $mail->WordWrap = $wordwrapwidth; // set word wrap
  3601. if (!empty($from->customheaders)) { // Add custom headers
  3602. if (is_array($from->customheaders)) {
  3603. foreach ($from->customheaders as $customheader) {
  3604. $mail->AddCustomHeader($customheader);
  3605. }
  3606. } else {
  3607. $mail->AddCustomHeader($from->customheaders);
  3608. }
  3609. }
  3610. if (!empty($from->priority)) {
  3611. $mail->Priority = $from->priority;
  3612. }
  3613. if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
  3614. $mail->IsHTML(true);
  3615. $mail->Encoding = 'quoted-printable'; // Encoding to use
  3616. $mail->Body = $messagehtml;
  3617. $mail->AltBody = "\n$messagetext\n";
  3618. } else {
  3619. $mail->IsHTML(false);
  3620. $mail->Body = "\n$messagetext\n";
  3621. }
  3622. if ($attachment && $attachname) {
  3623. if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
  3624. $mail->AddAddress($supportuser->email, fullname($supportuser, true) );
  3625. $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
  3626. } else {
  3627. require_once($CFG->libdir.'/filelib.php');
  3628. $mimetype = mimeinfo('type', $attachname);
  3629. $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
  3630. }
  3631. }
  3632. /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
  3633. /// encoding to the specified one
  3634. if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
  3635. /// Set it to site mail charset
  3636. $charset = $CFG->sitemailcharset;
  3637. /// Overwrite it with the user mail charset
  3638. if (!empty($CFG->allowusermailcharset)) {
  3639. if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
  3640. $charset = $useremailcharset;
  3641. }
  3642. }
  3643. /// If it has changed, convert all the necessary strings
  3644. $charsets = get_list_of_charsets();
  3645. unset($charsets['UTF-8']);
  3646. if (in_array($charset, $charsets)) {
  3647. /// Save the new mail charset
  3648. $mail->CharSet = $charset;
  3649. /// And convert some strings
  3650. $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
  3651. foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names
  3652. $mail->ReplyTo[$key][1] = $textlib->convert($rt[1], 'utf-8', $mail->CharSet);
  3653. }
  3654. $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject
  3655. foreach ($mail->to as $key => $to) {
  3656. $mail->to[$key][1] = $textlib->convert($to[1], 'utf-8', $mail->CharSet); //To Names
  3657. }
  3658. $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body
  3659. $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject
  3660. }
  3661. }
  3662. if ($mail->Send()) {
  3663. set_send_count($user);
  3664. $mail->IsSMTP(); // use SMTP directly
  3665. if (!empty($mail->SMTPDebug)) {
  3666. echo '</pre>';
  3667. }
  3668. return true;
  3669. } else {
  3670. mtrace('ERROR: '. $mail->ErrorInfo);
  3671. add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
  3672. if (!empty($mail->SMTPDebug)) {
  3673. echo '</pre>';
  3674. }
  3675. return false;
  3676. }
  3677. }
  3678. /**
  3679. * Generate a signoff for emails based on support settings
  3680. *
  3681. */
  3682. function generate_email_signoff() {
  3683. global $CFG;
  3684. $signoff = "\n";
  3685. if (!empty($CFG->supportname)) {
  3686. $signoff .= $CFG->supportname."\n";
  3687. }
  3688. if (!empty($CFG->supportemail)) {
  3689. $signoff .= $CFG->supportemail."\n";
  3690. }
  3691. if (!empty($CFG->supportpage)) {
  3692. $signoff .= $CFG->supportpage."\n";
  3693. }
  3694. return $signoff;
  3695. }
  3696. /**
  3697. * Generate a fake user for emails based on support settings
  3698. *
  3699. */
  3700. function generate_email_supportuser() {
  3701. global $CFG;
  3702. static $supportuser;
  3703. if (!empty($supportuser)) {
  3704. return $supportuser;
  3705. }
  3706. $supportuser = new object;
  3707. $supportuser->email = $CFG->supportemail ? $CFG->supportemail : $CFG->noreplyaddress;
  3708. $supportuser->firstname = $CFG->supportname ? $CFG->supportname : get_string('noreplyname');
  3709. $supportuser->lastname = '';
  3710. $supportuser->maildisplay = true;
  3711. return $supportuser;
  3712. }
  3713. /**
  3714. * Sets specified user's password and send the new password to the user via email.
  3715. *
  3716. * @uses $CFG
  3717. * @param user $user A {@link $USER} object
  3718. * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
  3719. * was blocked by user and "false" if there was another sort of error.
  3720. */
  3721. function setnew_password_and_mail($user) {
  3722. global $CFG;
  3723. $site = get_site();
  3724. $supportuser = generate_email_supportuser();
  3725. $newpassword = generate_password();
  3726. if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
  3727. trigger_error('Could not set user password!');
  3728. return false;
  3729. }
  3730. $a = new object();
  3731. $a->firstname = fullname($user, true);
  3732. $a->sitename = format_string($site->fullname);
  3733. $a->username = $user->username;
  3734. $a->newpassword = $newpassword;
  3735. $a->link = $CFG->wwwroot .'/login/';
  3736. $a->signoff = generate_email_signoff();
  3737. $message = get_string('newusernewpasswordtext', '', $a);
  3738. $subject = format_string($site->fullname) .': '. get_string('newusernewpasswordsubj');
  3739. return email_to_user($user, $supportuser, $subject, $message);
  3740. }
  3741. /**
  3742. * Resets specified user's password and send the new password to the user via email.
  3743. *
  3744. * @uses $CFG
  3745. * @param user $user A {@link $USER} object
  3746. * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
  3747. * was blocked by user and "false" if there was another sort of error.
  3748. */
  3749. function reset_password_and_mail($user) {
  3750. global $CFG;
  3751. $site = get_site();
  3752. $supportuser = generate_email_supportuser();
  3753. $userauth = get_auth_plugin($user->auth);
  3754. if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
  3755. trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
  3756. return false;
  3757. }
  3758. $newpassword = generate_password();
  3759. if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
  3760. error("Could not set user password!");
  3761. }
  3762. $a = new object();
  3763. $a->firstname = $user->firstname;
  3764. $a->lastname = $user->lastname;
  3765. $a->sitename = format_string($site->fullname);
  3766. $a->username = $user->username;
  3767. $a->newpassword = $newpassword;
  3768. $a->link = $CFG->httpswwwroot .'/login/change_password.php';
  3769. $a->signoff = generate_email_signoff();
  3770. $message = get_string('newpasswordtext', '', $a);
  3771. $subject = format_string($site->fullname) .': '. get_string('changedpassword');
  3772. return email_to_user($user, $supportuser, $subject, $message);
  3773. }
  3774. /**
  3775. * Send email to specified user with confirmation text and activation link.
  3776. *
  3777. * @uses $CFG
  3778. * @param user $user A {@link $USER} object
  3779. * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
  3780. * was blocked by user and "false" if there was another sort of error.
  3781. */
  3782. function send_confirmation_email($user) {
  3783. global $CFG;
  3784. $site = get_site();
  3785. $supportuser = generate_email_supportuser();
  3786. $data = new object();
  3787. $data->firstname = fullname($user);
  3788. $data->sitename = format_string($site->fullname);
  3789. $data->admin = generate_email_signoff();
  3790. $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
  3791. $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. urlencode($user->username);
  3792. $message = get_string('emailconfirmation', '', $data);
  3793. $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
  3794. $user->mailformat = 1; // Always send HTML version as well
  3795. return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
  3796. }
  3797. /**
  3798. * send_password_change_confirmation_email.
  3799. *
  3800. * @uses $CFG
  3801. * @param user $user A {@link $USER} object
  3802. * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
  3803. * was blocked by user and "false" if there was another sort of error.
  3804. */
  3805. function send_password_change_confirmation_email($user) {
  3806. global $CFG;
  3807. $site = get_site();
  3808. $supportuser = generate_email_supportuser();
  3809. $data = new object();
  3810. $data->firstname = $user->firstname;
  3811. $data->lastname = $user->lastname;
  3812. $data->sitename = format_string($site->fullname);
  3813. $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
  3814. $data->admin = generate_email_signoff();
  3815. $message = get_string('emailpasswordconfirmation', '', $data);
  3816. $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
  3817. return email_to_user($user, $supportuser, $subject, $message);
  3818. }
  3819. /**
  3820. * send_password_change_info.
  3821. *
  3822. * @uses $CFG
  3823. * @param user $user A {@link $USER} object
  3824. * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
  3825. * was blocked by user and "false" if there was another sort of error.
  3826. */
  3827. function send_password_change_info($user) {
  3828. global $CFG;
  3829. $site = get_site();
  3830. $supportuser = generate_email_supportuser();
  3831. $systemcontext = get_context_instance(CONTEXT_SYSTEM);
  3832. $data = new object();
  3833. $data->firstname = $user->firstname;
  3834. $data->lastname = $user->lastname;
  3835. $data->sitename = format_string($site->fullname);
  3836. $data->admin = generate_email_signoff();
  3837. $userauth = get_auth_plugin($user->auth);
  3838. if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
  3839. $message = get_string('emailpasswordchangeinfodisabled', '', $data);
  3840. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  3841. return email_to_user($user, $supportuser, $subject, $message);
  3842. }
  3843. if ($userauth->can_change_password() and $userauth->change_password_url()) {
  3844. // we have some external url for password changing
  3845. $data->link .= $userauth->change_password_url();
  3846. } else {
  3847. //no way to change password, sorry
  3848. $data->link = '';
  3849. }
  3850. if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
  3851. $message = get_string('emailpasswordchangeinfo', '', $data);
  3852. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  3853. } else {
  3854. $message = get_string('emailpasswordchangeinfofail', '', $data);
  3855. $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
  3856. }
  3857. return email_to_user($user, $supportuser, $subject, $message);
  3858. }
  3859. /**
  3860. * Check that an email is allowed. It returns an error message if there
  3861. * was a problem.
  3862. *
  3863. * @uses $CFG
  3864. * @param string $email Content of email
  3865. * @return string|false
  3866. */
  3867. function email_is_not_allowed($email) {
  3868. global $CFG;
  3869. if (!empty($CFG->allowemailaddresses)) {
  3870. $allowed = explode(' ', $CFG->allowemailaddresses);
  3871. foreach ($allowed as $allowedpattern) {
  3872. $allowedpattern = trim($allowedpattern);
  3873. if (!$allowedpattern) {
  3874. continue;
  3875. }
  3876. if (strpos($allowedpattern, '.') === 0) {
  3877. if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
  3878. // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
  3879. return false;
  3880. }
  3881. } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
  3882. return false;
  3883. }
  3884. }
  3885. return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
  3886. } else if (!empty($CFG->denyemailaddresses)) {
  3887. $denied = explode(' ', $CFG->denyemailaddresses);
  3888. foreach ($denied as $deniedpattern) {
  3889. $deniedpattern = trim($deniedpattern);
  3890. if (!$deniedpattern) {
  3891. continue;
  3892. }
  3893. if (strpos($deniedpattern, '.') === 0) {
  3894. if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
  3895. // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
  3896. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  3897. }
  3898. } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
  3899. return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
  3900. }
  3901. }
  3902. }
  3903. return false;
  3904. }
  3905. function email_welcome_message_to_user($course, $user=NULL) {
  3906. global $CFG, $USER;
  3907. if (isset($CFG->sendcoursewelcomemessage) and !$CFG->sendcoursewelcomemessage) {
  3908. return;
  3909. }
  3910. if (empty($user)) {
  3911. if (!isloggedin()) {
  3912. return false;
  3913. }
  3914. $user = $USER;
  3915. }
  3916. if (!empty($course->welcomemessage)) {
  3917. $message = $course->welcomemessage;
  3918. } else {
  3919. $a = new Object();
  3920. $a->coursename = $course->fullname;
  3921. $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&course=$course->id";
  3922. $message = get_string("welcometocoursetext", "", $a);
  3923. }
  3924. /// If you don't want a welcome message sent, then make the message string blank.
  3925. if (!empty($message)) {
  3926. $subject = get_string('welcometocourse', '', format_string($course->fullname));
  3927. if (! $teacher = get_teacher($course->id)) {
  3928. $teacher = get_admin();
  3929. }
  3930. email_to_user($user, $teacher, $subject, $message);
  3931. }
  3932. }
  3933. /// FILE HANDLING /////////////////////////////////////////////
  3934. /**
  3935. * Makes an upload directory for a particular module.
  3936. *
  3937. * @uses $CFG
  3938. * @param int $courseid The id of the course in question - maps to id field of 'course' table.
  3939. * @return string|false Returns full path to directory if successful, false if not
  3940. */
  3941. function make_mod_upload_directory($courseid) {
  3942. global $CFG;
  3943. if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
  3944. return false;
  3945. }
  3946. $strreadme = get_string('readme');
  3947. if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
  3948. copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
  3949. } else {
  3950. copy($CFG->dirroot .'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
  3951. }
  3952. return $moddata;
  3953. }
  3954. /**
  3955. * Makes a directory for a particular user.
  3956. *
  3957. * @uses $CFG
  3958. * @param int $userid The id of the user in question - maps to id field of 'user' table.
  3959. * @param bool $test Whether we are only testing the return value (do not create the directory)
  3960. * @return string|false Returns full path to directory if successful, false if not
  3961. */
  3962. function make_user_directory($userid, $test=false) {
  3963. global $CFG;
  3964. if (is_bool($userid) || $userid < 0 || !ereg('^[0-9]{1,10}$', $userid) || $userid > 2147483647) {
  3965. if (!$test) {
  3966. notify("Given userid was not a valid integer! (" . gettype($userid) . " $userid)");
  3967. }
  3968. return false;
  3969. }
  3970. // Generate a two-level path for the userid. First level groups them by slices of 1000 users, second level is userid
  3971. $level1 = floor($userid / 1000) * 1000;
  3972. $userdir = "user/$level1/$userid";
  3973. if ($test) {
  3974. return $CFG->dataroot . '/' . $userdir;
  3975. } else {
  3976. return make_upload_directory($userdir);
  3977. }
  3978. }
  3979. /**
  3980. * Returns an array of full paths to user directories, indexed by their userids.
  3981. *
  3982. * @param bool $only_non_empty Only return directories that contain files
  3983. * @param bool $legacy Search for user directories in legacy location (dataroot/users/userid) instead of (dataroot/user/section/userid)
  3984. * @return array An associative array: userid=>array(basedir => $basedir, userfolder => $userfolder)
  3985. */
  3986. function get_user_directories($only_non_empty=true, $legacy=false) {
  3987. global $CFG;
  3988. $rootdir = $CFG->dataroot."/user";
  3989. if ($legacy) {
  3990. $rootdir = $CFG->dataroot."/users";
  3991. }
  3992. $dirlist = array();
  3993. //Check if directory exists
  3994. if (check_dir_exists($rootdir, true)) {
  3995. if ($legacy) {
  3996. if ($userlist = get_directory_list($rootdir, '', true, true, false)) {
  3997. foreach ($userlist as $userid) {
  3998. $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $userid);
  3999. }
  4000. } else {
  4001. notify("no directories found under $rootdir");
  4002. }
  4003. } else {
  4004. if ($grouplist =get_directory_list($rootdir, '', true, true, false)) { // directories will be in the form 0, 1000, 2000 etc...
  4005. foreach ($grouplist as $group) {
  4006. if ($userlist = get_directory_list("$rootdir/$group", '', true, true, false)) {
  4007. foreach ($userlist as $userid) {
  4008. $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $group . '/' . $userid);
  4009. }
  4010. }
  4011. }
  4012. }
  4013. }
  4014. } else {
  4015. notify("$rootdir does not exist!");
  4016. return false;
  4017. }
  4018. return $dirlist;
  4019. }
  4020. /**
  4021. * Returns current name of file on disk if it exists.
  4022. *
  4023. * @param string $newfile File to be verified
  4024. * @return string Current name of file on disk if true
  4025. */
  4026. function valid_uploaded_file($newfile) {
  4027. if (empty($newfile)) {
  4028. return '';
  4029. }
  4030. if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
  4031. return $newfile['tmp_name'];
  4032. } else {
  4033. return '';
  4034. }
  4035. }
  4036. /**
  4037. * Returns the maximum size for uploading files.
  4038. *
  4039. * There are seven possible upload limits:
  4040. * 1. in Apache using LimitRequestBody (no way of checking or changing this)
  4041. * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
  4042. * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
  4043. * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
  4044. * 5. by the Moodle admin in $CFG->maxbytes
  4045. * 6. by the teacher in the current course $course->maxbytes
  4046. * 7. by the teacher for the current module, eg $assignment->maxbytes
  4047. *
  4048. * These last two are passed to this function as arguments (in bytes).
  4049. * Anything defined as 0 is ignored.
  4050. * The smallest of all the non-zero numbers is returned.
  4051. *
  4052. * @param int $sizebytes ?
  4053. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  4054. * @param int $modulebytes Current module ->maxbytes (in bytes)
  4055. * @return int The maximum size for uploading files.
  4056. * @todo Finish documenting this function
  4057. */
  4058. function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
  4059. if (! $filesize = ini_get('upload_max_filesize')) {
  4060. $filesize = '5M';
  4061. }
  4062. $minimumsize = get_real_size($filesize);
  4063. if ($postsize = ini_get('post_max_size')) {
  4064. $postsize = get_real_size($postsize);
  4065. if ($postsize < $minimumsize) {
  4066. $minimumsize = $postsize;
  4067. }
  4068. }
  4069. if ($sitebytes and $sitebytes < $minimumsize) {
  4070. $minimumsize = $sitebytes;
  4071. }
  4072. if ($coursebytes and $coursebytes < $minimumsize) {
  4073. $minimumsize = $coursebytes;
  4074. }
  4075. if ($modulebytes and $modulebytes < $minimumsize) {
  4076. $minimumsize = $modulebytes;
  4077. }
  4078. return $minimumsize;
  4079. }
  4080. /**
  4081. * Related to {@link get_max_upload_file_size()} - this function returns an
  4082. * array of possible sizes in an array, translated to the
  4083. * local language.
  4084. *
  4085. * @uses SORT_NUMERIC
  4086. * @param int $sizebytes ?
  4087. * @param int $coursebytes Current course $course->maxbytes (in bytes)
  4088. * @param int $modulebytes Current module ->maxbytes (in bytes)
  4089. * @return int
  4090. * @todo Finish documenting this function
  4091. */
  4092. function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
  4093. global $CFG;
  4094. if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
  4095. return array();
  4096. }
  4097. $filesize[$maxsize] = display_size($maxsize);
  4098. $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
  4099. 5242880, 10485760, 20971520, 52428800, 104857600);
  4100. // Allow maxbytes to be selected if it falls outside the above boundaries
  4101. if( isset($CFG->maxbytes) && !in_array($CFG->maxbytes, $sizelist) ){
  4102. $sizelist[] = $CFG->maxbytes;
  4103. }
  4104. foreach ($sizelist as $sizebytes) {
  4105. if ($sizebytes < $maxsize) {
  4106. $filesize[$sizebytes] = display_size($sizebytes);
  4107. }
  4108. }
  4109. krsort($filesize, SORT_NUMERIC);
  4110. return $filesize;
  4111. }
  4112. /**
  4113. * If there has been an error uploading a file, print the appropriate error message
  4114. * Numerical constants used as constant definitions not added until PHP version 4.2.0
  4115. *
  4116. * $filearray is a 1-dimensional sub-array of the $_FILES array
  4117. * eg $filearray = $_FILES['userfile1']
  4118. * If left empty then the first element of the $_FILES array will be used
  4119. *
  4120. * @uses $_FILES
  4121. * @param array $filearray A 1-dimensional sub-array of the $_FILES array
  4122. * @param bool $returnerror If true then a string error message will be returned. Otherwise the user will be notified of the error in a notify() call.
  4123. * @return bool|string
  4124. */
  4125. function print_file_upload_error($filearray = '', $returnerror = false) {
  4126. if ($filearray == '' or !isset($filearray['error'])) {
  4127. if (empty($_FILES)) return false;
  4128. $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
  4129. $filearray = array_shift($files); /// use first element of array
  4130. }
  4131. switch ($filearray['error']) {
  4132. case 0: // UPLOAD_ERR_OK
  4133. if ($filearray['size'] > 0) {
  4134. $errmessage = get_string('uploadproblem', $filearray['name']);
  4135. } else {
  4136. $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
  4137. }
  4138. break;
  4139. case 1: // UPLOAD_ERR_INI_SIZE
  4140. $errmessage = get_string('uploadserverlimit');
  4141. break;
  4142. case 2: // UPLOAD_ERR_FORM_SIZE
  4143. $errmessage = get_string('uploadformlimit');
  4144. break;
  4145. case 3: // UPLOAD_ERR_PARTIAL
  4146. $errmessage = get_string('uploadpartialfile');
  4147. break;
  4148. case 4: // UPLOAD_ERR_NO_FILE
  4149. $errmessage = get_string('uploadnofilefound');
  4150. break;
  4151. default:
  4152. $errmessage = get_string('uploadproblem', $filearray['name']);
  4153. }
  4154. if ($returnerror) {
  4155. return $errmessage;
  4156. } else {
  4157. notify($errmessage);
  4158. return true;
  4159. }
  4160. }
  4161. /**
  4162. * handy function to loop through an array of files and resolve any filename conflicts
  4163. * both in the array of filenames and for what is already on disk.
  4164. * not really compatible with the similar function in uploadlib.php
  4165. * but this could be used for files/index.php for moving files around.
  4166. */
  4167. function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
  4168. foreach ($files as $k => $f) {
  4169. if (check_potential_filename($destination,$f,$files)) {
  4170. $bits = explode('.', $f);
  4171. for ($i = 1; true; $i++) {
  4172. $try = sprintf($format, $bits[0], $i, $bits[1]);
  4173. if (!check_potential_filename($destination,$try,$files)) {
  4174. $files[$k] = $try;
  4175. break;
  4176. }
  4177. }
  4178. }
  4179. }
  4180. return $files;
  4181. }
  4182. /**
  4183. * @used by resolve_filename_collisions
  4184. */
  4185. function check_potential_filename($destination,$filename,$files) {
  4186. if (file_exists($destination.'/'.$filename)) {
  4187. return true;
  4188. }
  4189. if (count(array_keys($files,$filename)) > 1) {
  4190. return true;
  4191. }
  4192. return false;
  4193. }
  4194. /**
  4195. * Returns an array with all the filenames in
  4196. * all subdirectories, relative to the given rootdir.
  4197. * If excludefile is defined, then that file/directory is ignored
  4198. * If getdirs is true, then (sub)directories are included in the output
  4199. * If getfiles is true, then files are included in the output
  4200. * (at least one of these must be true!)
  4201. *
  4202. * @param string $rootdir ?
  4203. * @param string $excludefile If defined then the specified file/directory is ignored
  4204. * @param bool $descend ?
  4205. * @param bool $getdirs If true then (sub)directories are included in the output
  4206. * @param bool $getfiles If true then files are included in the output
  4207. * @return array An array with all the filenames in
  4208. * all subdirectories, relative to the given rootdir
  4209. * @todo Finish documenting this function. Add examples of $excludefile usage.
  4210. */
  4211. function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
  4212. $dirs = array();
  4213. if (!$getdirs and !$getfiles) { // Nothing to show
  4214. return $dirs;
  4215. }
  4216. if (!is_dir($rootdir)) { // Must be a directory
  4217. return $dirs;
  4218. }
  4219. if (!$dir = opendir($rootdir)) { // Can't open it for some reason
  4220. return $dirs;
  4221. }
  4222. if (!is_array($excludefiles)) {
  4223. $excludefiles = array($excludefiles);
  4224. }
  4225. while (false !== ($file = readdir($dir))) {
  4226. $firstchar = substr($file, 0, 1);
  4227. if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
  4228. continue;
  4229. }
  4230. $fullfile = $rootdir .'/'. $file;
  4231. if (filetype($fullfile) == 'dir') {
  4232. if ($getdirs) {
  4233. $dirs[] = $file;
  4234. }
  4235. if ($descend) {
  4236. $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
  4237. foreach ($subdirs as $subdir) {
  4238. $dirs[] = $file .'/'. $subdir;
  4239. }
  4240. }
  4241. } else if ($getfiles) {
  4242. $dirs[] = $file;
  4243. }
  4244. }
  4245. closedir($dir);
  4246. asort($dirs);
  4247. return $dirs;
  4248. }
  4249. /**
  4250. * Adds up all the files in a directory and works out the size.
  4251. *
  4252. * @param string $rootdir ?
  4253. * @param string $excludefile ?
  4254. * @return array
  4255. * @todo Finish documenting this function
  4256. */
  4257. function get_directory_size($rootdir, $excludefile='') {
  4258. global $CFG;
  4259. // do it this way if we can, it's much faster
  4260. if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
  4261. $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
  4262. $output = null;
  4263. $return = null;
  4264. exec($command,$output,$return);
  4265. if (is_array($output)) {
  4266. return get_real_size(intval($output[0]).'k'); // we told it to return k.
  4267. }
  4268. }
  4269. if (!is_dir($rootdir)) { // Must be a directory
  4270. return 0;
  4271. }
  4272. if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
  4273. return 0;
  4274. }
  4275. $size = 0;
  4276. while (false !== ($file = readdir($dir))) {
  4277. $firstchar = substr($file, 0, 1);
  4278. if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
  4279. continue;
  4280. }
  4281. $fullfile = $rootdir .'/'. $file;
  4282. if (filetype($fullfile) == 'dir') {
  4283. $size += get_directory_size($fullfile, $excludefile);
  4284. } else {
  4285. $size += filesize($fullfile);
  4286. }
  4287. }
  4288. closedir($dir);
  4289. return $size;
  4290. }
  4291. /**
  4292. * Converts bytes into display form
  4293. *
  4294. * @param string $size ?
  4295. * @return string
  4296. * @staticvar string $gb Localized string for size in gigabytes
  4297. * @staticvar string $mb Localized string for size in megabytes
  4298. * @staticvar string $kb Localized string for size in kilobytes
  4299. * @staticvar string $b Localized string for size in bytes
  4300. * @todo Finish documenting this function. Verify return type.
  4301. */
  4302. function display_size($size) {
  4303. static $gb, $mb, $kb, $b;
  4304. if (empty($gb)) {
  4305. $gb = get_string('sizegb');
  4306. $mb = get_string('sizemb');
  4307. $kb = get_string('sizekb');
  4308. $b = get_string('sizeb');
  4309. }
  4310. if ($size >= 1073741824) {
  4311. $size = round($size / 1073741824 * 10) / 10 . $gb;
  4312. } else if ($size >= 1048576) {
  4313. $size = round($size / 1048576 * 10) / 10 . $mb;
  4314. } else if ($size >= 1024) {
  4315. $size = round($size / 1024 * 10) / 10 . $kb;
  4316. } else {
  4317. $size = $size .' '. $b;
  4318. }
  4319. return $size;
  4320. }
  4321. /**
  4322. * Cleans a given filename by removing suspicious or troublesome characters
  4323. * Only these are allowed: alphanumeric _ - .
  4324. * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
  4325. *
  4326. * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
  4327. * because native zip binaries do weird character conversions. Use PHP zipping instead.
  4328. *
  4329. * @param string $string file name
  4330. * @return string cleaned file name
  4331. */
  4332. function clean_filename($string) {
  4333. global $CFG;
  4334. if (empty($CFG->unicodecleanfilename)) {
  4335. $textlib = textlib_get_instance();
  4336. $string = $textlib->specialtoascii($string);
  4337. $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
  4338. } else {
  4339. //clean only ascii range
  4340. $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
  4341. }
  4342. $string = preg_replace("/_+/", '_', $string);
  4343. $string = preg_replace("/\.\.+/", '.', $string);
  4344. return $string;
  4345. }
  4346. /// STRING TRANSLATION ////////////////////////////////////////
  4347. /**
  4348. * Returns the code for the current language
  4349. *
  4350. * @uses $CFG
  4351. * @param $USER
  4352. * @param $SESSION
  4353. * @return string
  4354. */
  4355. function current_language() {
  4356. global $CFG, $USER, $SESSION, $COURSE;
  4357. if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
  4358. $return = $COURSE->lang;
  4359. } else if (!empty($SESSION->lang)) { // Session language can override other settings
  4360. $return = $SESSION->lang;
  4361. } else if (!empty($USER->lang)) {
  4362. $return = $USER->lang;
  4363. } else {
  4364. $return = $CFG->lang;
  4365. }
  4366. if ($return == 'en') {
  4367. $return = 'en_utf8';
  4368. }
  4369. return $return;
  4370. }
  4371. /**
  4372. * Prints out a translated string.
  4373. *
  4374. * Prints out a translated string using the return value from the {@link get_string()} function.
  4375. *
  4376. * Example usage of this function when the string is in the moodle.php file:<br/>
  4377. * <code>
  4378. * echo '<strong>';
  4379. * print_string('wordforstudent');
  4380. * echo '</strong>';
  4381. * </code>
  4382. *
  4383. * Example usage of this function when the string is not in the moodle.php file:<br/>
  4384. * <code>
  4385. * echo '<h1>';
  4386. * print_string('typecourse', 'calendar');
  4387. * echo '</h1>';
  4388. * </code>
  4389. *
  4390. * @param string $identifier The key identifier for the localized string
  4391. * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
  4392. * @param mixed $a An object, string or number that can be used
  4393. * within translation strings
  4394. */
  4395. function print_string($identifier, $module='', $a=NULL) {
  4396. echo get_string($identifier, $module, $a);
  4397. }
  4398. /**
  4399. * fix up the optional data in get_string()/print_string() etc
  4400. * ensure possible sprintf() format characters are escaped correctly
  4401. * needs to handle arbitrary strings and objects
  4402. * @param mixed $a An object, string or number that can be used
  4403. * @return mixed the supplied parameter 'cleaned'
  4404. */
  4405. function clean_getstring_data( $a ) {
  4406. if (is_string($a)) {
  4407. return str_replace( '%','%%',$a );
  4408. }
  4409. elseif (is_object($a)) {
  4410. $a_vars = get_object_vars( $a );
  4411. $new_a_vars = array();
  4412. foreach ($a_vars as $fname => $a_var) {
  4413. $new_a_vars[$fname] = clean_getstring_data( $a_var );
  4414. }
  4415. return (object)$new_a_vars;
  4416. }
  4417. else {
  4418. return $a;
  4419. }
  4420. }
  4421. /**
  4422. * @return array places to look for lang strings based on the prefix to the
  4423. * module name. For example qtype_ in question/type. Used by get_string and
  4424. * help.php.
  4425. */
  4426. function places_to_search_for_lang_strings() {
  4427. global $CFG;
  4428. return array(
  4429. '__exceptions' => array('moodle', 'langconfig'),
  4430. 'assignment_' => array('mod/assignment/type'),
  4431. 'auth_' => array('auth'),
  4432. 'block_' => array('blocks'),
  4433. 'datafield_' => array('mod/data/field'),
  4434. 'datapreset_' => array('mod/data/preset'),
  4435. 'enrol_' => array('enrol'),
  4436. 'filter_' => array('filter'),
  4437. 'format_' => array('course/format'),
  4438. 'qtype_' => array('question/type'),
  4439. 'report_' => array($CFG->admin.'/report', 'course/report', 'mod/quiz/report'),
  4440. 'resource_' => array('mod/resource/type'),
  4441. 'gradereport_' => array('grade/report'),
  4442. 'gradeimport_' => array('grade/import'),
  4443. 'gradeexport_' => array('grade/export'),
  4444. 'qformat_' => array('question/format'),
  4445. 'profilefield_' => array('user/profile/field'),
  4446. '' => array('mod')
  4447. );
  4448. }
  4449. /**
  4450. * Returns a localized string.
  4451. *
  4452. * Returns the translated string specified by $identifier as
  4453. * for $module. Uses the same format files as STphp.
  4454. * $a is an object, string or number that can be used
  4455. * within translation strings
  4456. *
  4457. * eg "hello \$a->firstname \$a->lastname"
  4458. * or "hello \$a"
  4459. *
  4460. * If you would like to directly echo the localized string use
  4461. * the function {@link print_string()}
  4462. *
  4463. * Example usage of this function involves finding the string you would
  4464. * like a local equivalent of and using its identifier and module information
  4465. * to retrive it.<br/>
  4466. * If you open moodle/lang/en/moodle.php and look near line 1031
  4467. * you will find a string to prompt a user for their word for student
  4468. * <code>
  4469. * $string['wordforstudent'] = 'Your word for Student';
  4470. * </code>
  4471. * So if you want to display the string 'Your word for student'
  4472. * in any language that supports it on your site
  4473. * you just need to use the identifier 'wordforstudent'
  4474. * <code>
  4475. * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
  4476. or
  4477. * </code>
  4478. * If the string you want is in another file you'd take a slightly
  4479. * different approach. Looking in moodle/lang/en/calendar.php you find
  4480. * around line 75:
  4481. * <code>
  4482. * $string['typecourse'] = 'Course event';
  4483. * </code>
  4484. * If you want to display the string "Course event" in any language
  4485. * supported you would use the identifier 'typecourse' and the module 'calendar'
  4486. * (because it is in the file calendar.php):
  4487. * <code>
  4488. * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
  4489. * </code>
  4490. *
  4491. * As a last resort, should the identifier fail to map to a string
  4492. * the returned string will be [[ $identifier ]]
  4493. *
  4494. * @uses $CFG
  4495. * @param string $identifier The key identifier for the localized string
  4496. * @param string $module The module where the key identifier is stored, usually expressed as the filename in the language pack without the .php on the end but can also be written as mod/forum or grade/export/xls. If none is specified then moodle.php is used.
  4497. * @param mixed $a An object, string or number that can be used
  4498. * within translation strings
  4499. * @param array $extralocations An array of strings with other locations to look for string files
  4500. * @return string The localized string.
  4501. */
  4502. function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
  4503. global $CFG;
  4504. /// originally these special strings were stored in moodle.php now we are only in langconfig.php
  4505. $langconfigstrs = array('alphabet', 'backupnameformat', 'decsep', 'firstdayofweek', 'listsep', 'locale',
  4506. 'localewin', 'localewincharset', 'oldcharset',
  4507. 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
  4508. 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
  4509. 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
  4510. 'thischarset', 'thisdirection', 'thislanguage', 'strftimedatetimeshort', 'thousandssep');
  4511. $filetocheck = 'langconfig.php';
  4512. $defaultlang = 'en_utf8';
  4513. if (in_array($identifier, $langconfigstrs)) {
  4514. $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
  4515. }
  4516. $lang = current_language();
  4517. if ($module == '') {
  4518. $module = 'moodle';
  4519. }
  4520. /// If the "module" is actually a pathname, then automatically derive the proper module name
  4521. if (strpos($module, '/') !== false) {
  4522. $modulepath = split('/', $module);
  4523. switch ($modulepath[0]) {
  4524. case 'mod':
  4525. $module = $modulepath[1];
  4526. break;
  4527. case 'blocks':
  4528. case 'block':
  4529. $module = 'block_'.$modulepath[1];
  4530. break;
  4531. case 'enrol':
  4532. $module = 'enrol_'.$modulepath[1];
  4533. break;
  4534. case 'format':
  4535. $module = 'format_'.$modulepath[1];
  4536. break;
  4537. case 'grade':
  4538. $module = 'grade'.$modulepath[1].'_'.$modulepath[2];
  4539. break;
  4540. }
  4541. }
  4542. /// if $a happens to have % in it, double it so sprintf() doesn't break
  4543. if ($a) {
  4544. $a = clean_getstring_data( $a );
  4545. }
  4546. /// Define the two or three major locations of language strings for this module
  4547. $locations = array();
  4548. if (!empty($extralocations)) { // Calling code has a good idea where to look
  4549. if (is_array($extralocations)) {
  4550. $locations += $extralocations;
  4551. } else if (is_string($extralocations)) {
  4552. $locations[] = $extralocations;
  4553. } else {
  4554. debugging('Bad lang path provided');
  4555. }
  4556. }
  4557. if (isset($CFG->running_installer)) {
  4558. $module = 'installer';
  4559. $filetocheck = 'installer.php';
  4560. $locations[] = $CFG->dirroot.'/install/lang/';
  4561. $locations[] = $CFG->dataroot.'/lang/';
  4562. $locations[] = $CFG->dirroot.'/lang/';
  4563. $defaultlang = 'en_utf8';
  4564. } else {
  4565. $locations[] = $CFG->dataroot.'/lang/';
  4566. $locations[] = $CFG->dirroot.'/lang/';
  4567. }
  4568. /// Add extra places to look for strings for particular plugin types.
  4569. $rules = places_to_search_for_lang_strings();
  4570. $exceptions = $rules['__exceptions'];
  4571. unset($rules['__exceptions']);
  4572. if (!in_array($module, $exceptions)) {
  4573. $dividerpos = strpos($module, '_');
  4574. if ($dividerpos === false) {
  4575. $type = '';
  4576. $plugin = $module;
  4577. } else {
  4578. $type = substr($module, 0, $dividerpos + 1);
  4579. $plugin = substr($module, $dividerpos + 1);
  4580. }
  4581. if ($module == 'local') {
  4582. $locations[] = $CFG->dirroot . '/local/lang/';
  4583. } if (!empty($rules[$type])) {
  4584. foreach ($rules[$type] as $location) {
  4585. $locations[] = $CFG->dirroot . "/$location/$plugin/lang/";
  4586. }
  4587. }
  4588. }
  4589. /// First check all the normal locations for the string in the current language
  4590. $resultstring = '';
  4591. foreach ($locations as $location) {
  4592. $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
  4593. if (file_exists($locallangfile)) {
  4594. if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
  4595. if (eval($result) === FALSE) {
  4596. trigger_error('Lang error: '.$identifier.':'.$locallangfile, E_USER_NOTICE);
  4597. }
  4598. return $resultstring;
  4599. }
  4600. }
  4601. //if local directory not found, or particular string does not exist in local direcotry
  4602. $langfile = $location.$lang.'/'.$module.'.php';
  4603. if (file_exists($langfile)) {
  4604. if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
  4605. if (eval($result) === FALSE) {
  4606. trigger_error('Lang error: '.$identifier.':'.$langfile, E_USER_NOTICE);
  4607. }
  4608. return $resultstring;
  4609. }
  4610. }
  4611. }
  4612. /// If the preferred language was English (utf8) we can abort now
  4613. /// saving some checks beacuse it's the only "root" lang
  4614. if ($lang == 'en_utf8') {
  4615. return '[['. $identifier .']]';
  4616. }
  4617. /// Is a parent language defined? If so, try to find this string in a parent language file
  4618. foreach ($locations as $location) {
  4619. $langfile = $location.$lang.'/'.$filetocheck;
  4620. if (file_exists($langfile)) {
  4621. if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
  4622. if (eval($result) === FALSE) {
  4623. trigger_error('Lang error: '.$identifier.':'.$langfile, E_USER_NOTICE);
  4624. }
  4625. if (!empty($parentlang)) { // found it!
  4626. //first, see if there's a local file for parent
  4627. $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
  4628. if (file_exists($locallangfile)) {
  4629. if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
  4630. if (eval($result) === FALSE) {
  4631. trigger_error('Lang error: '.$identifier.':'.$locallangfile, E_USER_NOTICE);
  4632. }
  4633. return $resultstring;
  4634. }
  4635. }
  4636. //if local directory not found, or particular string does not exist in local direcotry
  4637. $langfile = $location.$parentlang.'/'.$module.'.php';
  4638. if (file_exists($langfile)) {
  4639. if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
  4640. eval($result);
  4641. return $resultstring;
  4642. }
  4643. }
  4644. }
  4645. }
  4646. }
  4647. }
  4648. /// Our only remaining option is to try English
  4649. foreach ($locations as $location) {
  4650. $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
  4651. if (file_exists($locallangfile)) {
  4652. if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
  4653. eval($result);
  4654. return $resultstring;
  4655. }
  4656. }
  4657. //if local_en not found, or string not found in local_en
  4658. $langfile = $location.$defaultlang.'/'.$module.'.php';
  4659. if (file_exists($langfile)) {
  4660. if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
  4661. eval($result);
  4662. return $resultstring;
  4663. }
  4664. }
  4665. }
  4666. /// And, because under 1.6 en is defined as en_utf8 child, me must try
  4667. /// if it hasn't been queried before.
  4668. if ($defaultlang == 'en') {
  4669. $defaultlang = 'en_utf8';
  4670. foreach ($locations as $location) {
  4671. $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
  4672. if (file_exists($locallangfile)) {
  4673. if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
  4674. eval($result);
  4675. return $resultstring;
  4676. }
  4677. }
  4678. //if local_en not found, or string not found in local_en
  4679. $langfile = $location.$defaultlang.'/'.$module.'.php';
  4680. if (file_exists($langfile)) {
  4681. if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
  4682. eval($result);
  4683. return $resultstring;
  4684. }
  4685. }
  4686. }
  4687. }
  4688. return '[['.$identifier.']]'; // Last resort
  4689. }
  4690. /**
  4691. * This function is only used from {@link get_string()}.
  4692. *
  4693. * @internal Only used from get_string, not meant to be public API
  4694. * @param string $identifier ?
  4695. * @param string $langfile ?
  4696. * @param string $destination ?
  4697. * @return string|false ?
  4698. * @staticvar array $strings Localized strings
  4699. * @access private
  4700. * @todo Finish documenting this function.
  4701. */
  4702. function get_string_from_file($identifier, $langfile, $destination) {
  4703. static $strings; // Keep the strings cached in memory.
  4704. if (empty($strings[$langfile])) {
  4705. $string = array();
  4706. include ($langfile);
  4707. $strings[$langfile] = $string;
  4708. } else {
  4709. $string = &$strings[$langfile];
  4710. }
  4711. if (!isset ($string[$identifier])) {
  4712. return false;
  4713. }
  4714. return $destination .'= sprintf("'. $string[$identifier] .'");';
  4715. }
  4716. /**
  4717. * Converts an array of strings to their localized value.
  4718. *
  4719. * @param array $array An array of strings
  4720. * @param string $module The language module that these strings can be found in.
  4721. * @return string
  4722. */
  4723. function get_strings($array, $module='') {
  4724. $string = NULL;
  4725. foreach ($array as $item) {
  4726. $string->$item = get_string($item, $module);
  4727. }
  4728. return $string;
  4729. }
  4730. /**
  4731. * Returns a list of language codes and their full names
  4732. * hides the _local files from everyone.
  4733. * @param bool refreshcache force refreshing of lang cache
  4734. * @param bool returnall ignore langlist, return all languages available
  4735. * @return array An associative array with contents in the form of LanguageCode => LanguageName
  4736. */
  4737. function get_list_of_languages($refreshcache=false, $returnall=false) {
  4738. global $CFG;
  4739. $languages = array();
  4740. $filetocheck = 'langconfig.php';
  4741. if (!$refreshcache && !$returnall && !empty($CFG->langcache) && file_exists($CFG->dataroot .'/cache/languages')) {
  4742. /// read available langs from cache
  4743. $lines = file($CFG->dataroot .'/cache/languages');
  4744. foreach ($lines as $line) {
  4745. $line = trim($line);
  4746. if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
  4747. $languages[$matches[1]] = $matches[2];
  4748. }
  4749. }
  4750. unset($lines); unset($line); unset($matches);
  4751. return $languages;
  4752. }
  4753. if (!$returnall && !empty($CFG->langlist)) {
  4754. /// return only languages allowed in langlist admin setting
  4755. $langlist = explode(',', $CFG->langlist);
  4756. // fix short lang names first - non existing langs are skipped anyway...
  4757. foreach ($langlist as $lang) {
  4758. if (strpos($lang, '_utf8') === false) {
  4759. $langlist[] = $lang.'_utf8';
  4760. }
  4761. }
  4762. // find existing langs from langlist
  4763. foreach ($langlist as $lang) {
  4764. $lang = trim($lang); //Just trim spaces to be a bit more permissive
  4765. if (strstr($lang, '_local')!==false) {
  4766. continue;
  4767. }
  4768. if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
  4769. $shortlang = substr($lang, 0, -5);
  4770. } else {
  4771. $shortlang = $lang;
  4772. }
  4773. /// Search under dirroot/lang
  4774. if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
  4775. include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
  4776. if (!empty($string['thislanguage'])) {
  4777. $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
  4778. }
  4779. unset($string);
  4780. }
  4781. /// And moodledata/lang
  4782. if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
  4783. include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
  4784. if (!empty($string['thislanguage'])) {
  4785. $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
  4786. }
  4787. unset($string);
  4788. }
  4789. }
  4790. } else {
  4791. /// return all languages available in system
  4792. /// Fetch langs from moodle/lang directory
  4793. $langdirs = get_list_of_plugins('lang');
  4794. /// Fetch langs from moodledata/lang directory
  4795. $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot);
  4796. /// Merge both lists of langs
  4797. $langdirs = array_merge($langdirs, $langdirs2);
  4798. /// Sort all
  4799. asort($langdirs);
  4800. /// Get some info from each lang (first from moodledata, then from moodle)
  4801. foreach ($langdirs as $lang) {
  4802. if (strstr($lang, '_local')!==false) {
  4803. continue;
  4804. }
  4805. if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
  4806. $shortlang = substr($lang, 0, -5);
  4807. } else {
  4808. $shortlang = $lang;
  4809. }
  4810. /// Search under moodledata/lang
  4811. if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
  4812. include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
  4813. if (!empty($string['thislanguage'])) {
  4814. $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
  4815. }
  4816. unset($string);
  4817. }
  4818. /// And dirroot/lang
  4819. if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
  4820. include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
  4821. if (!empty($string['thislanguage'])) {
  4822. $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
  4823. }
  4824. unset($string);
  4825. }
  4826. }
  4827. }
  4828. if ($refreshcache && !empty($CFG->langcache)) {
  4829. if ($returnall) {
  4830. // we have a list of all langs only, just delete old cache
  4831. @unlink($CFG->dataroot.'/cache/languages');
  4832. } else {
  4833. // store the list of allowed languages
  4834. if ($file = fopen($CFG->dataroot .'/cache/languages', 'w')) {
  4835. foreach ($languages as $key => $value) {
  4836. fwrite($file, "$key $value\n");
  4837. }
  4838. fclose($file);
  4839. }
  4840. }
  4841. }
  4842. return $languages;
  4843. }
  4844. /**
  4845. * Returns a list of charset codes. It's hardcoded, so they should be added manually
  4846. * (cheking that such charset is supported by the texlib library!)
  4847. *
  4848. * @return array And associative array with contents in the form of charset => charset
  4849. */
  4850. function get_list_of_charsets() {
  4851. $charsets = array(
  4852. 'EUC-JP' => 'EUC-JP',
  4853. 'ISO-2022-JP'=> 'ISO-2022-JP',
  4854. 'ISO-8859-1' => 'ISO-8859-1',
  4855. 'SHIFT-JIS' => 'SHIFT-JIS',
  4856. 'GB2312' => 'GB2312',
  4857. 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
  4858. 'UTF-8' => 'UTF-8');
  4859. asort($charsets);
  4860. return $charsets;
  4861. }
  4862. /**
  4863. * For internal use only.
  4864. * @return array with two elements, the path to use and the name of the lang.
  4865. */
  4866. function get_list_of_countries_language() {
  4867. global $CFG;
  4868. $lang = current_language();
  4869. if (is_readable($CFG->dataroot.'/lang/'. $lang .'/countries.php')) {
  4870. return array($CFG->dataroot, $lang);
  4871. }
  4872. if (is_readable($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
  4873. return array($CFG->dirroot , $lang);
  4874. }
  4875. if ($lang == 'en_utf8') {
  4876. return;
  4877. }
  4878. $parentlang = get_string('parentlanguage');
  4879. if (substr($parentlang, 0, 1) != '[') {
  4880. if (is_readable($CFG->dataroot.'/lang/'. $parentlang .'/countries.php')) {
  4881. return array($CFG->dataroot, $parentlang);
  4882. }
  4883. if (is_readable($CFG->dirroot .'/lang/'. $parentlang .'/countries.php')) {
  4884. return array($CFG->dirroot , $parentlang);
  4885. }
  4886. if ($parentlang == 'en_utf8') {
  4887. return;
  4888. }
  4889. }
  4890. if (is_readable($CFG->dataroot.'/lang/en_utf8/countries.php')) {
  4891. return array($CFG->dataroot, 'en_utf8');
  4892. }
  4893. if (is_readable($CFG->dirroot .'/lang/en_utf8/countries.php')) {
  4894. return array($CFG->dirroot , 'en_utf8');
  4895. }
  4896. return array(null, null);
  4897. }
  4898. /**
  4899. * Returns a list of country names in the current language
  4900. *
  4901. * @uses $CFG
  4902. * @uses $USER
  4903. * @return array
  4904. */
  4905. function get_list_of_countries() {
  4906. global $CFG;
  4907. list($path, $lang) = get_list_of_countries_language();
  4908. if (empty($path)) {
  4909. print_error('countriesphpempty', '', '', $lang);
  4910. }
  4911. // Load all the strings into $string.
  4912. include($path . '/lang/' . $lang . '/countries.php');
  4913. // See if there are local overrides to countries.php.
  4914. // If so, override those elements of $string.
  4915. if (is_readable($CFG->dirroot .'/lang/' . $lang . '_local/countries.php')) {
  4916. include($CFG->dirroot .'/lang/' . $lang . '_local/countries.php');
  4917. }
  4918. if (is_readable($CFG->dataroot.'/lang/' . $lang . '_local/countries.php')) {
  4919. include($CFG->dataroot.'/lang/' . $lang . '_local/countries.php');
  4920. }
  4921. if (empty($string)) {
  4922. print_error('countriesphpempty', '', '', $lang);
  4923. }
  4924. uasort($string, 'strcoll');
  4925. return $string;
  4926. }
  4927. /**
  4928. * Returns a list of valid and compatible themes
  4929. *
  4930. * @uses $CFG
  4931. * @return array
  4932. */
  4933. function get_list_of_themes() {
  4934. global $CFG;
  4935. $themes = array();
  4936. if (!empty($CFG->themelist)) { // use admin's list of themes
  4937. $themelist = explode(',', $CFG->themelist);
  4938. } else {
  4939. $themelist = get_list_of_plugins("theme");
  4940. }
  4941. foreach ($themelist as $key => $theme) {
  4942. if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
  4943. continue;
  4944. }
  4945. $THEME = new object(); // Note this is not the global one!! :-)
  4946. include("$CFG->themedir/$theme/config.php");
  4947. if (!isset($THEME->sheets)) { // Not a valid 1.5 theme
  4948. continue;
  4949. }
  4950. $themes[$theme] = $theme;
  4951. }
  4952. asort($themes);
  4953. return $themes;
  4954. }
  4955. /**
  4956. * Returns a list of picture names in the current or specified language
  4957. *
  4958. * @uses $CFG
  4959. * @return array
  4960. */
  4961. function get_list_of_pixnames($lang = '') {
  4962. global $CFG;
  4963. if (empty($lang)) {
  4964. $lang = current_language();
  4965. }
  4966. $string = array();
  4967. $path = $CFG->dirroot .'/lang/en_utf8/pix.php'; // always exists
  4968. if (file_exists($CFG->dataroot .'/lang/'. $lang .'_local/pix.php')) {
  4969. $path = $CFG->dataroot .'/lang/'. $lang .'_local/pix.php';
  4970. } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
  4971. $path = $CFG->dirroot .'/lang/'. $lang .'/pix.php';
  4972. } else if (file_exists($CFG->dataroot .'/lang/'. $lang .'/pix.php')) {
  4973. $path = $CFG->dataroot .'/lang/'. $lang .'/pix.php';
  4974. } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
  4975. return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
  4976. }
  4977. include($path);
  4978. return $string;
  4979. }
  4980. /**
  4981. * Returns a list of timezones in the current language
  4982. *
  4983. * @uses $CFG
  4984. * @return array
  4985. */
  4986. function get_list_of_timezones() {
  4987. global $CFG;
  4988. static $timezones;
  4989. if (!empty($timezones)) { // This function has been called recently
  4990. return $timezones;
  4991. }
  4992. $timezones = array();
  4993. if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix.'timezone GROUP BY name')) {
  4994. foreach($rawtimezones as $timezone) {
  4995. if (!empty($timezone->name)) {
  4996. $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
  4997. if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
  4998. $timezones[$timezone->name] = $timezone->name;
  4999. }
  5000. }
  5001. }
  5002. }
  5003. asort($timezones);
  5004. for ($i = -13; $i <= 13; $i += .5) {
  5005. $tzstring = 'UTC';
  5006. if ($i < 0) {
  5007. $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
  5008. } else if ($i > 0) {
  5009. $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
  5010. } else {
  5011. $timezones[sprintf("%.1f", $i)] = $tzstring;
  5012. }
  5013. }
  5014. return $timezones;
  5015. }
  5016. /**
  5017. * Returns a list of currencies in the current language
  5018. *
  5019. * @uses $CFG
  5020. * @uses $USER
  5021. * @return array
  5022. */
  5023. function get_list_of_currencies() {
  5024. global $CFG, $USER;
  5025. $lang = current_language();
  5026. if (!file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
  5027. if ($parentlang = get_string('parentlanguage')) {
  5028. if (file_exists($CFG->dataroot .'/lang/'. $parentlang .'/currencies.php')) {
  5029. $lang = $parentlang;
  5030. } else {
  5031. $lang = 'en_utf8'; // currencies.php must exist in this pack
  5032. }
  5033. } else {
  5034. $lang = 'en_utf8'; // currencies.php must exist in this pack
  5035. }
  5036. }
  5037. if (file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
  5038. include_once($CFG->dataroot .'/lang/'. $lang .'/currencies.php');
  5039. } else { //if en_utf8 is not installed in dataroot
  5040. include_once($CFG->dirroot .'/lang/'. $lang .'/currencies.php');
  5041. }
  5042. if (!empty($string)) {
  5043. asort($string);
  5044. }
  5045. return $string;
  5046. }
  5047. /// ENCRYPTION ////////////////////////////////////////////////
  5048. /**
  5049. * rc4encrypt
  5050. *
  5051. * @param string $data ?
  5052. * @return string
  5053. * @todo Finish documenting this function
  5054. */
  5055. function rc4encrypt($data) {
  5056. $password = 'nfgjeingjk';
  5057. return endecrypt($password, $data, '');
  5058. }
  5059. /**
  5060. * rc4decrypt
  5061. *
  5062. * @param string $data ?
  5063. * @return string
  5064. * @todo Finish documenting this function
  5065. */
  5066. function rc4decrypt($data) {
  5067. $password = 'nfgjeingjk';
  5068. return endecrypt($password, $data, 'de');
  5069. }
  5070. /**
  5071. * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
  5072. *
  5073. * @param string $pwd ?
  5074. * @param string $data ?
  5075. * @param string $case ?
  5076. * @return string
  5077. * @todo Finish documenting this function
  5078. */
  5079. function endecrypt ($pwd, $data, $case) {
  5080. if ($case == 'de') {
  5081. $data = urldecode($data);
  5082. }
  5083. $key[] = '';
  5084. $box[] = '';
  5085. $temp_swap = '';
  5086. $pwd_length = 0;
  5087. $pwd_length = strlen($pwd);
  5088. for ($i = 0; $i <= 255; $i++) {
  5089. $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
  5090. $box[$i] = $i;
  5091. }
  5092. $x = 0;
  5093. for ($i = 0; $i <= 255; $i++) {
  5094. $x = ($x + $box[$i] + $key[$i]) % 256;
  5095. $temp_swap = $box[$i];
  5096. $box[$i] = $box[$x];
  5097. $box[$x] = $temp_swap;
  5098. }
  5099. $temp = '';
  5100. $k = '';
  5101. $cipherby = '';
  5102. $cipher = '';
  5103. $a = 0;
  5104. $j = 0;
  5105. for ($i = 0; $i < strlen($data); $i++) {
  5106. $a = ($a + 1) % 256;
  5107. $j = ($j + $box[$a]) % 256;
  5108. $temp = $box[$a];
  5109. $box[$a] = $box[$j];
  5110. $box[$j] = $temp;
  5111. $k = $box[(($box[$a] + $box[$j]) % 256)];
  5112. $cipherby = ord(substr($data, $i, 1)) ^ $k;
  5113. $cipher .= chr($cipherby);
  5114. }
  5115. if ($case == 'de') {
  5116. $cipher = urldecode(urlencode($cipher));
  5117. } else {
  5118. $cipher = urlencode($cipher);
  5119. }
  5120. return $cipher;
  5121. }
  5122. /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
  5123. /**
  5124. * Call this function to add an event to the calendar table
  5125. * and to call any calendar plugins
  5126. *
  5127. * @uses $CFG
  5128. * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field. The object event should include the following:
  5129. * <ul>
  5130. * <li><b>$event->name</b> - Name for the event
  5131. * <li><b>$event->description</b> - Description of the event (defaults to '')
  5132. * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
  5133. * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
  5134. * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
  5135. * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
  5136. * <li><b>$event->modulename</b> - Name of the module that creates this event
  5137. * <li><b>$event->instance</b> - Instance of the module that owns this event
  5138. * <li><b>$event->eventtype</b> - The type info together with the module info could
  5139. * be used by calendar plugins to decide how to display event
  5140. * <li><b>$event->timestart</b>- Timestamp for start of event
  5141. * <li><b>$event->timeduration</b> - Duration (defaults to zero)
  5142. * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
  5143. * </ul>
  5144. * @return int The id number of the resulting record
  5145. */
  5146. function add_event($event) {
  5147. global $CFG;
  5148. $event->timemodified = time();
  5149. if (!$event->id = insert_record('event', $event)) {
  5150. return false;
  5151. }
  5152. if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
  5153. if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
  5154. include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
  5155. $calendar_add_event = $CFG->calendar.'_add_event';
  5156. if (function_exists($calendar_add_event)) {
  5157. $calendar_add_event($event);
  5158. }
  5159. }
  5160. }
  5161. return $event->id;
  5162. }
  5163. /**
  5164. * Call this function to update an event in the calendar table
  5165. * the event will be identified by the id field of the $event object.
  5166. *
  5167. * @uses $CFG
  5168. * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
  5169. * @return bool
  5170. */
  5171. function update_event($event) {
  5172. global $CFG;
  5173. $event->timemodified = time();
  5174. if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
  5175. if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
  5176. include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
  5177. $calendar_update_event = $CFG->calendar.'_update_event';
  5178. if (function_exists($calendar_update_event)) {
  5179. $calendar_update_event($event);
  5180. }
  5181. }
  5182. }
  5183. return update_record('event', $event);
  5184. }
  5185. /**
  5186. * Call this function to delete the event with id $id from calendar table.
  5187. *
  5188. * @uses $CFG
  5189. * @param int $id The id of an event from the 'calendar' table.
  5190. * @return array An associative array with the results from the SQL call.
  5191. * @todo Verify return type
  5192. */
  5193. function delete_event($id) {
  5194. global $CFG;
  5195. if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
  5196. if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
  5197. include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
  5198. $calendar_delete_event = $CFG->calendar.'_delete_event';
  5199. if (function_exists($calendar_delete_event)) {
  5200. $calendar_delete_event($id);
  5201. }
  5202. }
  5203. }
  5204. return delete_records('event', 'id', $id);
  5205. }
  5206. /**
  5207. * Call this function to hide an event in the calendar table
  5208. * the event will be identified by the id field of the $event object.
  5209. *
  5210. * @uses $CFG
  5211. * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
  5212. * @return array An associative array with the results from the SQL call.
  5213. * @todo Verify return type
  5214. */
  5215. function hide_event($event) {
  5216. global $CFG;
  5217. if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
  5218. if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
  5219. include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
  5220. $calendar_hide_event = $CFG->calendar.'_hide_event';
  5221. if (function_exists($calendar_hide_event)) {
  5222. $calendar_hide_event($event);
  5223. }
  5224. }
  5225. }
  5226. return set_field('event', 'visible', 0, 'id', $event->id);
  5227. }
  5228. /**
  5229. * Call this function to unhide an event in the calendar table
  5230. * the event will be identified by the id field of the $event object.
  5231. *
  5232. * @uses $CFG
  5233. * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
  5234. * @return array An associative array with the results from the SQL call.
  5235. * @todo Verify return type
  5236. */
  5237. function show_event($event) {
  5238. global $CFG;
  5239. if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
  5240. if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
  5241. include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
  5242. $calendar_show_event = $CFG->calendar.'_show_event';
  5243. if (function_exists($calendar_show_event)) {
  5244. $calendar_show_event($event);
  5245. }
  5246. }
  5247. }
  5248. return set_field('event', 'visible', 1, 'id', $event->id);
  5249. }
  5250. /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
  5251. /**
  5252. * Lists plugin directories within some directory
  5253. *
  5254. * @uses $CFG
  5255. * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
  5256. * @param string $exclude dir name to exclude from the list (defaults to none)
  5257. * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
  5258. * @return array of plugins found under the requested parameters
  5259. */
  5260. function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
  5261. global $CFG;
  5262. $plugins = array();
  5263. if (empty($basedir)) {
  5264. # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
  5265. switch ($plugin) {
  5266. case "theme":
  5267. $basedir = $CFG->themedir;
  5268. break;
  5269. default:
  5270. $basedir = $CFG->dirroot .'/'. $plugin;
  5271. }
  5272. } else {
  5273. $basedir = $basedir .'/'. $plugin;
  5274. }
  5275. if (file_exists($basedir) && filetype($basedir) == 'dir') {
  5276. $dirhandle = opendir($basedir);
  5277. while (false !== ($dir = readdir($dirhandle))) {
  5278. $firstchar = substr($dir, 0, 1);
  5279. if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == 'simpletest' or $dir == $exclude) {
  5280. continue;
  5281. }
  5282. if (filetype($basedir .'/'. $dir) != 'dir') {
  5283. continue;
  5284. }
  5285. $plugins[] = $dir;
  5286. }
  5287. closedir($dirhandle);
  5288. }
  5289. if ($plugins) {
  5290. asort($plugins);
  5291. }
  5292. return $plugins;
  5293. }
  5294. /**
  5295. * Returns true if the current version of PHP is greater that the specified one.
  5296. *
  5297. * @param string $version The version of php being tested.
  5298. * @return bool
  5299. */
  5300. function check_php_version($version='4.1.0') {
  5301. return (version_compare(phpversion(), $version) >= 0);
  5302. }
  5303. /**
  5304. * Checks to see if is the browser operating system matches the specified
  5305. * brand.
  5306. *
  5307. * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
  5308. *
  5309. * @uses $_SERVER
  5310. * @param string $brand The operating system identifier being tested
  5311. * @return bool true if the given brand below to the detected operating system
  5312. */
  5313. function check_browser_operating_system($brand) {
  5314. if (empty($_SERVER['HTTP_USER_AGENT'])) {
  5315. return false;
  5316. }
  5317. if (preg_match("/$brand/i", $_SERVER['HTTP_USER_AGENT'])) {
  5318. return true;
  5319. }
  5320. return false;
  5321. }
  5322. /**
  5323. * Checks to see if is a browser matches the specified
  5324. * brand and is equal or better version.
  5325. *
  5326. * @uses $_SERVER
  5327. * @param string $brand The browser identifier being tested
  5328. * @param int $version The version of the browser
  5329. * @return bool true if the given version is below that of the detected browser
  5330. */
  5331. function check_browser_version($brand='MSIE', $version=5.5) {
  5332. if (empty($_SERVER['HTTP_USER_AGENT'])) {
  5333. return false;
  5334. }
  5335. $agent = $_SERVER['HTTP_USER_AGENT'];
  5336. switch ($brand) {
  5337. case 'Camino': /// Mozilla Firefox browsers
  5338. if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
  5339. if (version_compare($match[1], $version) >= 0) {
  5340. return true;
  5341. }
  5342. }
  5343. break;
  5344. case 'Firefox': /// Mozilla Firefox browsers
  5345. if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
  5346. if (version_compare($match[1], $version) >= 0) {
  5347. return true;
  5348. }
  5349. }
  5350. break;
  5351. case 'Gecko': /// Gecko based browsers
  5352. if (substr_count($agent, 'Camino')) {
  5353. // MacOS X Camino support
  5354. $version = 20041110;
  5355. }
  5356. // the proper string - Gecko/CCYYMMDD Vendor/Version
  5357. // Faster version and work-a-round No IDN problem.
  5358. if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
  5359. if ($match[1] > $version) {
  5360. return true;
  5361. }
  5362. }
  5363. break;
  5364. case 'MSIE': /// Internet Explorer
  5365. if (strpos($agent, 'Opera')) { // Reject Opera
  5366. return false;
  5367. }
  5368. $string = explode(';', $agent);
  5369. if (!isset($string[1])) {
  5370. return false;
  5371. }
  5372. $string = explode(' ', trim($string[1]));
  5373. if (!isset($string[0]) and !isset($string[1])) {
  5374. return false;
  5375. }
  5376. if ($string[0] == $brand and (float)$string[1] >= $version ) {
  5377. return true;
  5378. }
  5379. break;
  5380. case 'Opera': /// Opera
  5381. if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
  5382. if (version_compare($match[1], $version) >= 0) {
  5383. return true;
  5384. }
  5385. }
  5386. break;
  5387. case 'Safari': /// Safari
  5388. // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
  5389. if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
  5390. return false;
  5391. } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
  5392. return false;
  5393. } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
  5394. return false;
  5395. }
  5396. if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
  5397. if (version_compare($match[1], $version) >= 0) {
  5398. return true;
  5399. }
  5400. }
  5401. break;
  5402. }
  5403. return false;
  5404. }
  5405. /**
  5406. * Returns one or several CSS class names that match the user's browser. These can be put
  5407. * in the body tag of the page to apply browser-specific rules without relying on CSS hacks
  5408. */
  5409. function get_browser_version_classes() {
  5410. $classes = '';
  5411. if (check_browser_version("MSIE", "0")) {
  5412. $classes .= 'ie ';
  5413. if (check_browser_version("MSIE", 8)) {
  5414. $classes .= 'ie8 ';
  5415. } elseif (check_browser_version("MSIE", 7)) {
  5416. $classes .= 'ie7 ';
  5417. } elseif (check_browser_version("MSIE", 6)) {
  5418. $classes .= 'ie6 ';
  5419. }
  5420. } elseif (check_browser_version("Firefox", 0) || check_browser_version("Gecko", 0) || check_browser_version("Camino", 0)) {
  5421. $classes .= 'gecko ';
  5422. if (preg_match('/rv\:([1-2])\.([0-9])/', $_SERVER['HTTP_USER_AGENT'], $matches)) {
  5423. $classes .= "gecko{$matches[1]}{$matches[2]} ";
  5424. }
  5425. } elseif (check_browser_version("Safari", 0)) {
  5426. $classes .= 'safari ';
  5427. } elseif (check_browser_version("Opera", 0)) {
  5428. $classes .= 'opera ';
  5429. }
  5430. return $classes;
  5431. }
  5432. /**
  5433. * This function makes the return value of ini_get consistent if you are
  5434. * setting server directives through the .htaccess file in apache.
  5435. * Current behavior for value set from php.ini On = 1, Off = [blank]
  5436. * Current behavior for value set from .htaccess On = On, Off = Off
  5437. * Contributed by jdell @ unr.edu
  5438. *
  5439. * @param string $ini_get_arg ?
  5440. * @return bool
  5441. * @todo Finish documenting this function
  5442. */
  5443. function ini_get_bool($ini_get_arg) {
  5444. $temp = ini_get($ini_get_arg);
  5445. if ($temp == '1' or strtolower($temp) == 'on') {
  5446. return true;
  5447. }
  5448. return false;
  5449. }
  5450. /**
  5451. * Compatibility stub to provide backward compatibility
  5452. *
  5453. * Determines if the HTML editor is enabled.
  5454. * @deprecated Use {@link can_use_html_editor()} instead.
  5455. */
  5456. function can_use_richtext_editor() {
  5457. return can_use_html_editor();
  5458. }
  5459. /**
  5460. * Determines if the HTML editor is enabled.
  5461. *
  5462. * This depends on site and user
  5463. * settings, as well as the current browser being used.
  5464. *
  5465. * @return string|false Returns false if editor is not being used, otherwise
  5466. * returns 'MSIE' or 'Gecko'.
  5467. */
  5468. function can_use_html_editor() {
  5469. global $USER, $CFG;
  5470. if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
  5471. if (check_browser_version('MSIE', 5.5)) {
  5472. return 'MSIE';
  5473. } else if (check_browser_version('Gecko', 20030516)) {
  5474. return 'Gecko';
  5475. }
  5476. }
  5477. return false;
  5478. }
  5479. /**
  5480. * Hack to find out the GD version by parsing phpinfo output
  5481. *
  5482. * @return int GD version (1, 2, or 0)
  5483. */
  5484. function check_gd_version() {
  5485. $gdversion = 0;
  5486. if (function_exists('gd_info')){
  5487. $gd_info = gd_info();
  5488. if (substr_count($gd_info['GD Version'], '2.')) {
  5489. $gdversion = 2;
  5490. } else if (substr_count($gd_info['GD Version'], '1.')) {
  5491. $gdversion = 1;
  5492. }
  5493. } else {
  5494. ob_start();
  5495. phpinfo(INFO_MODULES);
  5496. $phpinfo = ob_get_contents();
  5497. ob_end_clean();
  5498. $phpinfo = explode("\n", $phpinfo);
  5499. foreach ($phpinfo as $text) {
  5500. $parts = explode('</td>', $text);
  5501. foreach ($parts as $key => $val) {
  5502. $parts[$key] = trim(strip_tags($val));
  5503. }
  5504. if ($parts[0] == 'GD Version') {
  5505. if (substr_count($parts[1], '2.0')) {
  5506. $parts[1] = '2.0';
  5507. }
  5508. $gdversion = intval($parts[1]);
  5509. }
  5510. }
  5511. }
  5512. return $gdversion; // 1, 2 or 0
  5513. }
  5514. /**
  5515. * Determine if moodle installation requires update
  5516. *
  5517. * Checks version numbers of main code and all modules to see
  5518. * if there are any mismatches
  5519. *
  5520. * @uses $CFG
  5521. * @return bool
  5522. */
  5523. function moodle_needs_upgrading() {
  5524. global $CFG;
  5525. $version = null;
  5526. include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
  5527. if ($CFG->version) {
  5528. if ($version > $CFG->version) {
  5529. return true;
  5530. }
  5531. if ($mods = get_list_of_plugins('mod')) {
  5532. foreach ($mods as $mod) {
  5533. $fullmod = $CFG->dirroot .'/mod/'. $mod;
  5534. $module = new object();
  5535. if (!is_readable($fullmod .'/version.php')) {
  5536. notify('Module "'. $mod .'" is not readable - check permissions');
  5537. continue;
  5538. }
  5539. include_once($fullmod .'/version.php'); # defines $module with version etc
  5540. if ($currmodule = get_record('modules', 'name', $mod)) {
  5541. if ($module->version > $currmodule->version) {
  5542. return true;
  5543. }
  5544. }
  5545. }
  5546. }
  5547. } else {
  5548. return true;
  5549. }
  5550. return false;
  5551. }
  5552. /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
  5553. /**
  5554. * Notify admin users or admin user of any failed logins (since last notification).
  5555. *
  5556. * Note that this function must be only executed from the cron script
  5557. * It uses the cache_flags system to store temporary records, deleting them
  5558. * by name before finishing
  5559. *
  5560. * @uses $CFG
  5561. * @uses $db
  5562. * @uses HOURSECS
  5563. */
  5564. function notify_login_failures() {
  5565. global $CFG, $db;
  5566. switch ($CFG->notifyloginfailures) {
  5567. case 'mainadmin' :
  5568. $recip = array(get_admin());
  5569. break;
  5570. case 'alladmins':
  5571. $recip = get_admins();
  5572. break;
  5573. }
  5574. if (empty($CFG->lastnotifyfailure)) {
  5575. $CFG->lastnotifyfailure=0;
  5576. }
  5577. // we need to deal with the threshold stuff first.
  5578. if (empty($CFG->notifyloginthreshold)) {
  5579. $CFG->notifyloginthreshold = 10; // default to something sensible.
  5580. }
  5581. /// Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
  5582. /// and insert them into the cache_flags temp table
  5583. $iprs = get_recordset_sql("SELECT ip, count(*)
  5584. FROM {$CFG->prefix}log
  5585. WHERE module = 'login'
  5586. AND action = 'error'
  5587. AND time > $CFG->lastnotifyfailure
  5588. GROUP BY ip
  5589. HAVING count(*) >= $CFG->notifyloginthreshold");
  5590. while ($iprec = rs_fetch_next_record($iprs)) {
  5591. if (!empty($iprec->ip)) {
  5592. set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
  5593. }
  5594. }
  5595. rs_close($iprs);
  5596. /// Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
  5597. /// and insert them into the cache_flags temp table
  5598. $infors = get_recordset_sql("SELECT info, count(*)
  5599. FROM {$CFG->prefix}log
  5600. WHERE module = 'login'
  5601. AND action = 'error'
  5602. AND time > $CFG->lastnotifyfailure
  5603. GROUP BY info
  5604. HAVING count(*) >= $CFG->notifyloginthreshold");
  5605. while ($inforec = rs_fetch_next_record($infors)) {
  5606. if (!empty($inforec->info)) {
  5607. set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
  5608. }
  5609. }
  5610. rs_close($infors);
  5611. /// Now, select all the login error logged records belonging to the ips and infos
  5612. /// since lastnotifyfailure, that we have stored in the cache_flags table
  5613. $logsrs = get_recordset_sql("SELECT l.*, u.firstname, u.lastname
  5614. FROM {$CFG->prefix}log l
  5615. JOIN {$CFG->prefix}cache_flags cf ON (l.ip = cf.name)
  5616. LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
  5617. WHERE l.module = 'login'
  5618. AND l.action = 'error'
  5619. AND l.time > $CFG->lastnotifyfailure
  5620. AND cf.flagtype = 'login_failure_by_ip'
  5621. UNION ALL
  5622. SELECT l.*, u.firstname, u.lastname
  5623. FROM {$CFG->prefix}log l
  5624. JOIN {$CFG->prefix}cache_flags cf ON (l.info = cf.name)
  5625. LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
  5626. WHERE l.module = 'login'
  5627. AND l.action = 'error'
  5628. AND l.time > $CFG->lastnotifyfailure
  5629. AND cf.flagtype = 'login_failure_by_info'
  5630. ORDER BY time DESC");
  5631. /// Init some variables
  5632. $count = 0;
  5633. $messages = '';
  5634. /// Iterate over the logs recordset
  5635. while ($log = rs_fetch_next_record($logsrs)) {
  5636. $log->time = userdate($log->time);
  5637. $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
  5638. $count++;
  5639. }
  5640. rs_close($logsrs);
  5641. /// If we haven't run in the last hour and
  5642. /// we have something useful to report and we
  5643. /// are actually supposed to be reporting to somebody
  5644. if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
  5645. $site = get_site();
  5646. $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
  5647. /// Calculate the complete body of notification (start + messages + end)
  5648. $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
  5649. (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
  5650. $messages .
  5651. "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
  5652. /// For each destination, send mail
  5653. foreach ($recip as $admin) {
  5654. mtrace('Emailing '. $admin->username .' about '. $count .' failed login attempts');
  5655. email_to_user($admin,get_admin(), $subject, $body);
  5656. }
  5657. /// Update lastnotifyfailure with current time
  5658. set_config('lastnotifyfailure', time());
  5659. }
  5660. /// Finally, delete all the temp records we have created in cache_flags
  5661. delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
  5662. }
  5663. /**
  5664. * moodle_setlocale
  5665. *
  5666. * @uses $CFG
  5667. * @param string $locale ?
  5668. * @todo Finish documenting this function
  5669. */
  5670. function moodle_setlocale($locale='') {
  5671. global $CFG;
  5672. static $currentlocale = ''; // last locale caching
  5673. $oldlocale = $currentlocale;
  5674. /// Fetch the correct locale based on ostype
  5675. if($CFG->ostype == 'WINDOWS') {
  5676. $stringtofetch = 'localewin';
  5677. } else {
  5678. $stringtofetch = 'locale';
  5679. }
  5680. /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
  5681. if (!empty($locale)) {
  5682. $currentlocale = $locale;
  5683. } else if (!empty($CFG->locale)) { // override locale for all language packs
  5684. $currentlocale = $CFG->locale;
  5685. } else {
  5686. $currentlocale = get_string($stringtofetch);
  5687. }
  5688. /// do nothing if locale already set up
  5689. if ($oldlocale == $currentlocale) {
  5690. return;
  5691. }
  5692. /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
  5693. /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
  5694. /// Some day, numeric, monetary and other categories should be set too, I think. :-/
  5695. /// Get current values
  5696. $monetary= setlocale (LC_MONETARY, 0);
  5697. $numeric = setlocale (LC_NUMERIC, 0);
  5698. $ctype = setlocale (LC_CTYPE, 0);
  5699. if ($CFG->ostype != 'WINDOWS') {
  5700. $messages= setlocale (LC_MESSAGES, 0);
  5701. }
  5702. /// Set locale to all
  5703. setlocale (LC_ALL, $currentlocale);
  5704. /// Set old values
  5705. setlocale (LC_MONETARY, $monetary);
  5706. setlocale (LC_NUMERIC, $numeric);
  5707. if ($CFG->ostype != 'WINDOWS') {
  5708. setlocale (LC_MESSAGES, $messages);
  5709. }
  5710. if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
  5711. setlocale (LC_CTYPE, $ctype);
  5712. }
  5713. }
  5714. /**
  5715. * Converts string to lowercase using most compatible function available.
  5716. *
  5717. * @param string $string The string to convert to all lowercase characters.
  5718. * @param string $encoding The encoding on the string.
  5719. * @return string
  5720. * @todo Add examples of calling this function with/without encoding types
  5721. * @deprecated Use textlib->strtolower($text) instead.
  5722. */
  5723. function moodle_strtolower ($string, $encoding='') {
  5724. //If not specified use utf8
  5725. if (empty($encoding)) {
  5726. $encoding = 'UTF-8';
  5727. }
  5728. //Use text services
  5729. $textlib = textlib_get_instance();
  5730. return $textlib->strtolower($string, $encoding);
  5731. }
  5732. /**
  5733. * Count words in a string.
  5734. *
  5735. * Words are defined as things between whitespace.
  5736. *
  5737. * @param string $string The text to be searched for words.
  5738. * @return int The count of words in the specified string
  5739. */
  5740. function count_words($string) {
  5741. $string = strip_tags($string);
  5742. return count(preg_split("/\w\b/", $string)) - 1;
  5743. }
  5744. /** Count letters in a string.
  5745. *
  5746. * Letters are defined as chars not in tags and different from whitespace.
  5747. *
  5748. * @param string $string The text to be searched for letters.
  5749. * @return int The count of letters in the specified text.
  5750. */
  5751. function count_letters($string) {
  5752. /// Loading the textlib singleton instance. We are going to need it.
  5753. $textlib = textlib_get_instance();
  5754. $string = strip_tags($string); // Tags are out now
  5755. $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
  5756. return $textlib->strlen($string);
  5757. }
  5758. /**
  5759. * Generate and return a random string of the specified length.
  5760. *
  5761. * @param int $length The length of the string to be created.
  5762. * @return string
  5763. */
  5764. function random_string ($length=15) {
  5765. $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  5766. $pool .= 'abcdefghijklmnopqrstuvwxyz';
  5767. $pool .= '0123456789';
  5768. $poollen = strlen($pool);
  5769. mt_srand ((double) microtime() * 1000000);
  5770. $string = '';
  5771. for ($i = 0; $i < $length; $i++) {
  5772. $string .= substr($pool, (mt_rand()%($poollen)), 1);
  5773. }
  5774. return $string;
  5775. }
  5776. /*
  5777. * Given some text (which may contain HTML) and an ideal length,
  5778. * this function truncates the text neatly on a word boundary if possible
  5779. * @param string $text - text to be shortened
  5780. * @param int $ideal - ideal string length
  5781. * @param boolean $exact if false, $text will not be cut mid-word
  5782. * @return string $truncate - shortened string
  5783. */
  5784. function shorten_text($text, $ideal=30, $exact = false) {
  5785. global $CFG;
  5786. $ending = '...';
  5787. // if the plain text is shorter than the maximum length, return the whole text
  5788. if (strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
  5789. return $text;
  5790. }
  5791. // splits all html-tags to scanable lines
  5792. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  5793. $total_length = strlen($ending);
  5794. $open_tags = array();
  5795. $truncate = '';
  5796. foreach ($lines as $line_matchings) {
  5797. // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  5798. if (!empty($line_matchings[1])) {
  5799. // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
  5800. if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  5801. // do nothing
  5802. // if tag is a closing tag (f.e. </b>)
  5803. } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  5804. // delete tag from $open_tags list
  5805. $pos = array_search($tag_matchings[1], array_reverse($open_tags, true)); // can have multiple exact same open tags, close the last one
  5806. if ($pos !== false) {
  5807. unset($open_tags[$pos]);
  5808. }
  5809. // if tag is an opening tag (f.e. <b>)
  5810. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  5811. // add tag to the beginning of $open_tags list
  5812. array_unshift($open_tags, strtolower($tag_matchings[1]));
  5813. }
  5814. // add html-tag to $truncate'd text
  5815. $truncate .= $line_matchings[1];
  5816. }
  5817. // calculate the length of the plain text part of the line; handle entities as one character
  5818. $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  5819. if ($total_length+$content_length > $ideal) {
  5820. // the number of characters which are left
  5821. $left = $ideal - $total_length;
  5822. $entities_length = 0;
  5823. // search for html entities
  5824. 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)) {
  5825. // calculate the real length of all entities in the legal range
  5826. foreach ($entities[0] as $entity) {
  5827. if ($entity[1]+1-$entities_length <= $left) {
  5828. $left--;
  5829. $entities_length += strlen($entity[0]);
  5830. } else {
  5831. // no more characters left
  5832. break;
  5833. }
  5834. }
  5835. }
  5836. $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
  5837. // maximum lenght is reached, so get off the loop
  5838. break;
  5839. } else {
  5840. $truncate .= $line_matchings[2];
  5841. $total_length += $content_length;
  5842. }
  5843. // if the maximum length is reached, get off the loop
  5844. if($total_length >= $ideal) {
  5845. break;
  5846. }
  5847. }
  5848. // if the words shouldn't be cut in the middle...
  5849. if (!$exact) {
  5850. // ...search the last occurance of a space...
  5851. for ($k=strlen($truncate);$k>0;$k--) {
  5852. if (!empty($truncate[$k]) && ($char = $truncate[$k])) {
  5853. if ($char == '.' or $char == ' ') {
  5854. $breakpos = $k+1;
  5855. break;
  5856. } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
  5857. $breakpos = $k; // can be truncated at any UTF-8
  5858. break; // character boundary.
  5859. }
  5860. }
  5861. }
  5862. if (isset($breakpos)) {
  5863. // ...and cut the text in this position
  5864. $truncate = substr($truncate, 0, $breakpos);
  5865. }
  5866. }
  5867. // add the defined ending to the text
  5868. $truncate .= $ending;
  5869. // close all unclosed html-tags
  5870. foreach ($open_tags as $tag) {
  5871. $truncate .= '</' . $tag . '>';
  5872. }
  5873. return $truncate;
  5874. }
  5875. /**
  5876. * Given dates in seconds, how many weeks is the date from startdate
  5877. * The first week is 1, the second 2 etc ...
  5878. *
  5879. * @uses WEEKSECS
  5880. * @param ? $startdate ?
  5881. * @param ? $thedate ?
  5882. * @return string
  5883. * @todo Finish documenting this function
  5884. */
  5885. function getweek ($startdate, $thedate) {
  5886. if ($thedate < $startdate) { // error
  5887. return 0;
  5888. }
  5889. return floor(($thedate - $startdate) / WEEKSECS) + 1;
  5890. }
  5891. /**
  5892. * returns a randomly generated password of length $maxlen. inspired by
  5893. * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
  5894. * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
  5895. *
  5896. * @param int $maxlen The maximum size of the password being generated.
  5897. * @return string
  5898. */
  5899. function generate_password($maxlen=10) {
  5900. global $CFG;
  5901. if (empty($CFG->passwordpolicy)) {
  5902. $fillers = PASSWORD_DIGITS;
  5903. $wordlist = file($CFG->wordlist);
  5904. $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  5905. $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
  5906. $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
  5907. $password = $word1 . $filler1 . $word2;
  5908. } else {
  5909. $maxlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
  5910. $digits = $CFG->minpassworddigits;
  5911. $lower = $CFG->minpasswordlower;
  5912. $upper = $CFG->minpasswordupper;
  5913. $nonalphanum = $CFG->minpasswordnonalphanum;
  5914. $additional = $maxlen - ($lower + $upper + $digits + $nonalphanum);
  5915. // Make sure we have enough characters to fulfill
  5916. // complexity requirements
  5917. $passworddigits = PASSWORD_DIGITS;
  5918. while ($digits > strlen($passworddigits)) {
  5919. $passworddigits .= PASSWORD_DIGITS;
  5920. }
  5921. $passwordlower = PASSWORD_LOWER;
  5922. while ($lower > strlen($passwordlower)) {
  5923. $passwordlower .= PASSWORD_LOWER;
  5924. }
  5925. $passwordupper = PASSWORD_UPPER;
  5926. while ($upper > strlen($passwordupper)) {
  5927. $passwordupper .= PASSWORD_UPPER;
  5928. }
  5929. $passwordnonalphanum = PASSWORD_NONALPHANUM;
  5930. while ($nonalphanum > strlen($passwordnonalphanum)) {
  5931. $passwordnonalphanum .= PASSWORD_NONALPHANUM;
  5932. }
  5933. // Now mix and shuffle it all
  5934. $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
  5935. substr(str_shuffle ($passwordupper), 0, $upper) .
  5936. substr(str_shuffle ($passworddigits), 0, $digits) .
  5937. substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
  5938. substr(str_shuffle ($passwordlower .
  5939. $passwordupper .
  5940. $passworddigits .
  5941. $passwordnonalphanum), 0 , $additional));
  5942. }
  5943. return substr ($password, 0, $maxlen);
  5944. }
  5945. /**
  5946. * Given a float, prints it nicely.
  5947. * Localized floats must not be used in calculations!
  5948. *
  5949. * @param float $flaot The float to print
  5950. * @param int $places The number of decimal places to print.
  5951. * @param bool $localized use localized decimal separator
  5952. * @return string locale float
  5953. */
  5954. function format_float($float, $decimalpoints=1, $localized=true) {
  5955. if (is_null($float)) {
  5956. return '';
  5957. }
  5958. if ($localized) {
  5959. return number_format($float, $decimalpoints, get_string('decsep'), '');
  5960. } else {
  5961. return number_format($float, $decimalpoints, '.', '');
  5962. }
  5963. }
  5964. /**
  5965. * Converts locale specific floating point/comma number back to standard PHP float value
  5966. * Do NOT try to do any math operations before this conversion on any user submitted floats!
  5967. *
  5968. * @param string $locale_float locale aware float representation
  5969. */
  5970. function unformat_float($locale_float) {
  5971. $locale_float = trim($locale_float);
  5972. if ($locale_float == '') {
  5973. return null;
  5974. }
  5975. $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
  5976. return (float)str_replace(get_string('decsep'), '.', $locale_float);
  5977. }
  5978. /**
  5979. * Given a simple array, this shuffles it up just like shuffle()
  5980. * Unlike PHP's shuffle() this function works on any machine.
  5981. *
  5982. * @param array $array The array to be rearranged
  5983. * @return array
  5984. */
  5985. function swapshuffle($array) {
  5986. srand ((double) microtime() * 10000000);
  5987. $last = count($array) - 1;
  5988. for ($i=0;$i<=$last;$i++) {
  5989. $from = rand(0,$last);
  5990. $curr = $array[$i];
  5991. $array[$i] = $array[$from];
  5992. $array[$from] = $curr;
  5993. }
  5994. return $array;
  5995. }
  5996. /**
  5997. * Like {@link swapshuffle()}, but works on associative arrays
  5998. *
  5999. * @param array $array The associative array to be rearranged
  6000. * @return array
  6001. */
  6002. function swapshuffle_assoc($array) {
  6003. $newarray = array();
  6004. $newkeys = swapshuffle(array_keys($array));
  6005. foreach ($newkeys as $newkey) {
  6006. $newarray[$newkey] = $array[$newkey];
  6007. }
  6008. return $newarray;
  6009. }
  6010. /**
  6011. * Given an arbitrary array, and a number of draws,
  6012. * this function returns an array with that amount
  6013. * of items. The indexes are retained.
  6014. *
  6015. * @param array $array ?
  6016. * @param ? $draws ?
  6017. * @return ?
  6018. * @todo Finish documenting this function
  6019. */
  6020. function draw_rand_array($array, $draws) {
  6021. srand ((double) microtime() * 10000000);
  6022. $return = array();
  6023. $last = count($array);
  6024. if ($draws > $last) {
  6025. $draws = $last;
  6026. }
  6027. while ($draws > 0) {
  6028. $last--;
  6029. $keys = array_keys($array);
  6030. $rand = rand(0, $last);
  6031. $return[$keys[$rand]] = $array[$keys[$rand]];
  6032. unset($array[$keys[$rand]]);
  6033. $draws--;
  6034. }
  6035. return $return;
  6036. }
  6037. /**
  6038. * microtime_diff
  6039. *
  6040. * @param string $a ?
  6041. * @param string $b ?
  6042. * @return string
  6043. * @todo Finish documenting this function
  6044. */
  6045. function microtime_diff($a, $b) {
  6046. list($a_dec, $a_sec) = explode(' ', $a);
  6047. list($b_dec, $b_sec) = explode(' ', $b);
  6048. return $b_sec - $a_sec + $b_dec - $a_dec;
  6049. }
  6050. /**
  6051. * Given a list (eg a,b,c,d,e) this function returns
  6052. * an array of 1->a, 2->b, 3->c etc
  6053. *
  6054. * @param array $list ?
  6055. * @param string $separator ?
  6056. * @todo Finish documenting this function
  6057. */
  6058. function make_menu_from_list($list, $separator=',') {
  6059. $array = array_reverse(explode($separator, $list), true);
  6060. foreach ($array as $key => $item) {
  6061. $outarray[$key+1] = trim($item);
  6062. }
  6063. return $outarray;
  6064. }
  6065. /**
  6066. * Creates an array that represents all the current grades that
  6067. * can be chosen using the given grading type. Negative numbers
  6068. * are scales, zero is no grade, and positive numbers are maximum
  6069. * grades.
  6070. *
  6071. * @param int $gradingtype ?
  6072. * return int
  6073. * @todo Finish documenting this function
  6074. */
  6075. function make_grades_menu($gradingtype) {
  6076. $grades = array();
  6077. if ($gradingtype < 0) {
  6078. if ($scale = get_record('scale', 'id', - $gradingtype)) {
  6079. return make_menu_from_list($scale->scale);
  6080. }
  6081. } else if ($gradingtype > 0) {
  6082. for ($i=$gradingtype; $i>=0; $i--) {
  6083. $grades[$i] = $i .' / '. $gradingtype;
  6084. }
  6085. return $grades;
  6086. }
  6087. return $grades;
  6088. }
  6089. /**
  6090. * This function returns the nummber of activities
  6091. * using scaleid in a courseid
  6092. *
  6093. * @param int $courseid ?
  6094. * @param int $scaleid ?
  6095. * @return int
  6096. * @todo Finish documenting this function
  6097. */
  6098. function course_scale_used($courseid, $scaleid) {
  6099. global $CFG;
  6100. $return = 0;
  6101. if (!empty($scaleid)) {
  6102. if ($cms = get_course_mods($courseid)) {
  6103. foreach ($cms as $cm) {
  6104. //Check cm->name/lib.php exists
  6105. if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
  6106. include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
  6107. $function_name = $cm->modname.'_scale_used';
  6108. if (function_exists($function_name)) {
  6109. if ($function_name($cm->instance,$scaleid)) {
  6110. $return++;
  6111. }
  6112. }
  6113. }
  6114. }
  6115. }
  6116. // check if any course grade item makes use of the scale
  6117. $return += count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
  6118. // check if any outcome in the course makes use of the scale
  6119. $return += count_records_sql("SELECT COUNT(*)
  6120. FROM {$CFG->prefix}grade_outcomes_courses goc,
  6121. {$CFG->prefix}grade_outcomes go
  6122. WHERE go.id = goc.outcomeid
  6123. AND go.scaleid = $scaleid
  6124. AND goc.courseid = $courseid");
  6125. }
  6126. return $return;
  6127. }
  6128. /**
  6129. * This function returns the nummber of activities
  6130. * using scaleid in the entire site
  6131. *
  6132. * @param int $scaleid ?
  6133. * @return int
  6134. * @todo Finish documenting this function. Is return type correct?
  6135. */
  6136. function site_scale_used($scaleid,&$courses) {
  6137. global $CFG;
  6138. $return = 0;
  6139. if (!is_array($courses) || count($courses) == 0) {
  6140. $courses = get_courses("all",false,"c.id,c.shortname");
  6141. }
  6142. if (!empty($scaleid)) {
  6143. if (is_array($courses) && count($courses) > 0) {
  6144. foreach ($courses as $course) {
  6145. $return += course_scale_used($course->id,$scaleid);
  6146. }
  6147. }
  6148. }
  6149. return $return;
  6150. }
  6151. /**
  6152. * make_unique_id_code
  6153. *
  6154. * @param string $extra ?
  6155. * @return string
  6156. * @todo Finish documenting this function
  6157. */
  6158. function make_unique_id_code($extra='') {
  6159. $hostname = 'unknownhost';
  6160. if (!empty($_SERVER['HTTP_HOST'])) {
  6161. $hostname = $_SERVER['HTTP_HOST'];
  6162. } else if (!empty($_ENV['HTTP_HOST'])) {
  6163. $hostname = $_ENV['HTTP_HOST'];
  6164. } else if (!empty($_SERVER['SERVER_NAME'])) {
  6165. $hostname = $_SERVER['SERVER_NAME'];
  6166. } else if (!empty($_ENV['SERVER_NAME'])) {
  6167. $hostname = $_ENV['SERVER_NAME'];
  6168. }
  6169. $date = gmdate("ymdHis");
  6170. $random = random_string(6);
  6171. if ($extra) {
  6172. return $hostname .'+'. $date .'+'. $random .'+'. $extra;
  6173. } else {
  6174. return $hostname .'+'. $date .'+'. $random;
  6175. }
  6176. }
  6177. /**
  6178. * Function to check the passed address is within the passed subnet
  6179. *
  6180. * The parameter is a comma separated string of subnet definitions.
  6181. * Subnet strings can be in one of three formats:
  6182. * 1: xxx.xxx.xxx.xxx/xx
  6183. * 2: xxx.xxx
  6184. * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
  6185. * Code for type 1 modified from user posted comments by mediator at
  6186. * {@link http://au.php.net/manual/en/function.ip2long.php}
  6187. *
  6188. * TODO one day we will have to make this work with IP6.
  6189. *
  6190. * @param string $addr The address you are checking
  6191. * @param string $subnetstr The string of subnet addresses
  6192. * @return bool
  6193. */
  6194. function address_in_subnet($addr, $subnetstr) {
  6195. $subnets = explode(',', $subnetstr);
  6196. $found = false;
  6197. $addr = trim($addr);
  6198. foreach ($subnets as $subnet) {
  6199. $subnet = trim($subnet);
  6200. if (strpos($subnet, '/') !== false) { /// type 1
  6201. list($ip, $mask) = explode('/', $subnet);
  6202. if (!is_number($mask) || $mask < 0 || $mask > 32) {
  6203. continue;
  6204. }
  6205. if ($mask == 0) {
  6206. return true;
  6207. }
  6208. if ($mask == 32) {
  6209. if ($ip === $addr) {
  6210. return true;
  6211. }
  6212. continue;
  6213. }
  6214. $mask = 0xffffffff << (32 - $mask);
  6215. $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
  6216. } else if (strpos($subnet, '-') !== false) {/// type 3
  6217. $subnetparts = explode('.', $subnet);
  6218. $addrparts = explode('.', $addr);
  6219. $subnetrange = explode('-', array_pop($subnetparts));
  6220. if (count($subnetrange) == 2) {
  6221. $lastaddrpart = array_pop($addrparts);
  6222. $found = ($subnetparts == $addrparts &&
  6223. $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
  6224. }
  6225. } else { /// type 2
  6226. if ($subnet[strlen($subnet) - 1] != '.') {
  6227. $subnet .= '.';
  6228. }
  6229. $found = (strpos($addr . '.', $subnet) === 0);
  6230. }
  6231. if ($found) {
  6232. break;
  6233. }
  6234. }
  6235. return $found;
  6236. }
  6237. /**
  6238. * This function sets the $HTTPSPAGEREQUIRED global
  6239. * (used in some parts of moodle to change some links)
  6240. * and calculate the proper wwwroot to be used
  6241. *
  6242. * By using this function properly, we can ensure 100% https-ized pages
  6243. * at our entire discretion (login, forgot_password, change_password)
  6244. */
  6245. function httpsrequired() {
  6246. global $CFG, $HTTPSPAGEREQUIRED;
  6247. if (!empty($CFG->loginhttps)) {
  6248. $HTTPSPAGEREQUIRED = true;
  6249. $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
  6250. $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
  6251. // change theme URLs to https
  6252. theme_setup();
  6253. } else {
  6254. $CFG->httpswwwroot = $CFG->wwwroot;
  6255. $CFG->httpsthemewww = $CFG->themewww;
  6256. }
  6257. }
  6258. /**
  6259. * For outputting debugging info
  6260. *
  6261. * @uses STDOUT
  6262. * @param string $string ?
  6263. * @param string $eol ?
  6264. * @todo Finish documenting this function
  6265. */
  6266. function mtrace($string, $eol="\n", $sleep=0) {
  6267. if (defined('STDOUT')) {
  6268. fwrite(STDOUT, $string.$eol);
  6269. } else {
  6270. echo $string . $eol;
  6271. }
  6272. flush();
  6273. //delay to keep message on user's screen in case of subsequent redirect
  6274. if ($sleep) {
  6275. sleep($sleep);
  6276. }
  6277. }
  6278. //Replace 1 or more slashes or backslashes to 1 slash
  6279. function cleardoubleslashes ($path) {
  6280. return preg_replace('/(\/|\\\){1,}/','/',$path);
  6281. }
  6282. function zip_files ($originalfiles, $destination) {
  6283. //Zip an array of files/dirs to a destination zip file
  6284. //Both parameters must be FULL paths to the files/dirs
  6285. global $CFG;
  6286. //Extract everything from destination
  6287. $path_parts = pathinfo(cleardoubleslashes($destination));
  6288. $destpath = $path_parts["dirname"]; //The path of the zip file
  6289. $destfilename = $path_parts["basename"]; //The name of the zip file
  6290. $extension = $path_parts["extension"]; //The extension of the file
  6291. //If no file, error
  6292. if (empty($destfilename)) {
  6293. return false;
  6294. }
  6295. //If no extension, add it
  6296. if (empty($extension)) {
  6297. $extension = 'zip';
  6298. $destfilename = $destfilename.'.'.$extension;
  6299. }
  6300. //Check destination path exists
  6301. if (!is_dir($destpath)) {
  6302. return false;
  6303. }
  6304. //Check destination path is writable. TODO!!
  6305. //Clean destination filename
  6306. $destfilename = clean_filename($destfilename);
  6307. //Now check and prepare every file
  6308. $files = array();
  6309. $origpath = NULL;
  6310. foreach ($originalfiles as $file) { //Iterate over each file
  6311. //Check for every file
  6312. $tempfile = cleardoubleslashes($file); // no doubleslashes!
  6313. //Calculate the base path for all files if it isn't set
  6314. if ($origpath === NULL) {
  6315. $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
  6316. }
  6317. //See if the file is readable
  6318. if (!is_readable($tempfile)) { //Is readable
  6319. continue;
  6320. }
  6321. //See if the file/dir is in the same directory than the rest
  6322. if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
  6323. continue;
  6324. }
  6325. //Add the file to the array
  6326. $files[] = $tempfile;
  6327. }
  6328. //Everything is ready:
  6329. // -$origpath is the path where ALL the files to be compressed reside (dir).
  6330. // -$destpath is the destination path where the zip file will go (dir).
  6331. // -$files is an array of files/dirs to compress (fullpath)
  6332. // -$destfilename is the name of the zip file (without path)
  6333. //print_object($files); //Debug
  6334. if (empty($CFG->zip)) { // Use built-in php-based zip function
  6335. include_once("$CFG->libdir/pclzip/pclzip.lib.php");
  6336. //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
  6337. $zipfiles = array();
  6338. $start = strlen($origpath)+1;
  6339. foreach($files as $file) {
  6340. $tf = array();
  6341. $tf[PCLZIP_ATT_FILE_NAME] = $file;
  6342. $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME] = substr($file, $start);
  6343. $zipfiles[] = $tf;
  6344. }
  6345. //create the archive
  6346. $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
  6347. if (($list = $archive->create($zipfiles) == 0)) {
  6348. notice($archive->errorInfo(true));
  6349. return false;
  6350. }
  6351. } else { // Use external zip program
  6352. $filestozip = "";
  6353. foreach ($files as $filetozip) {
  6354. $filestozip .= escapeshellarg(basename($filetozip));
  6355. $filestozip .= " ";
  6356. }
  6357. //Construct the command
  6358. $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
  6359. $command = 'cd '.escapeshellarg($origpath).$separator.
  6360. escapeshellarg($CFG->zip).' -r '.
  6361. escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
  6362. //All converted to backslashes in WIN
  6363. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  6364. $command = str_replace('/','\\',$command);
  6365. }
  6366. Exec($command);
  6367. }
  6368. return true;
  6369. }
  6370. function unzip_file ($zipfile, $destination = '', $showstatus = true) {
  6371. //Unzip one zip file to a destination dir
  6372. //Both parameters must be FULL paths
  6373. //If destination isn't specified, it will be the
  6374. //SAME directory where the zip file resides.
  6375. global $CFG;
  6376. //Extract everything from zipfile
  6377. $path_parts = pathinfo(cleardoubleslashes($zipfile));
  6378. $zippath = $path_parts["dirname"]; //The path of the zip file
  6379. $zipfilename = $path_parts["basename"]; //The name of the zip file
  6380. $extension = $path_parts["extension"]; //The extension of the file
  6381. //If no file, error
  6382. if (empty($zipfilename)) {
  6383. return false;
  6384. }
  6385. //If no extension, error
  6386. if (empty($extension)) {
  6387. return false;
  6388. }
  6389. //Clear $zipfile
  6390. $zipfile = cleardoubleslashes($zipfile);
  6391. //Check zipfile exists
  6392. if (!file_exists($zipfile)) {
  6393. return false;
  6394. }
  6395. //If no destination, passed let's go with the same directory
  6396. if (empty($destination)) {
  6397. $destination = $zippath;
  6398. }
  6399. //Clear $destination
  6400. $destpath = rtrim(cleardoubleslashes($destination), "/");
  6401. //Check destination path exists
  6402. if (!is_dir($destpath)) {
  6403. return false;
  6404. }
  6405. //Check destination path is writable. TODO!!
  6406. //Everything is ready:
  6407. // -$zippath is the path where the zip file resides (dir)
  6408. // -$zipfilename is the name of the zip file (without path)
  6409. // -$destpath is the destination path where the zip file will uncompressed (dir)
  6410. $list = array();
  6411. require_once("$CFG->libdir/filelib.php");
  6412. do {
  6413. $temppath = "$CFG->dataroot/temp/unzip/".random_string(10);
  6414. } while (file_exists($temppath));
  6415. if (!check_dir_exists($temppath, true, true)) {
  6416. return false;
  6417. }
  6418. if (empty($CFG->unzip)) { // Use built-in php-based unzip function
  6419. include_once("$CFG->libdir/pclzip/pclzip.lib.php");
  6420. $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
  6421. if (!$list = $archive->extract(PCLZIP_OPT_PATH, $temppath,
  6422. PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename',
  6423. PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $temppath)) {
  6424. if (!empty($showstatus)) {
  6425. notice($archive->errorInfo(true));
  6426. }
  6427. return false;
  6428. }
  6429. } else { // Use external unzip program
  6430. $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
  6431. $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
  6432. $command = 'cd '.escapeshellarg($zippath).$separator.
  6433. escapeshellarg($CFG->unzip).' -o '.
  6434. escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
  6435. escapeshellarg($temppath).$redirection;
  6436. //All converted to backslashes in WIN
  6437. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  6438. $command = str_replace('/','\\',$command);
  6439. }
  6440. Exec($command,$list);
  6441. }
  6442. unzip_process_temp_dir($temppath, $destpath);
  6443. fulldelete($temppath);
  6444. //Display some info about the unzip execution
  6445. if ($showstatus) {
  6446. unzip_show_status($list, $temppath, $destpath);
  6447. }
  6448. return true;
  6449. }
  6450. /**
  6451. * Sanitize temporary unzipped files and move to target dir.
  6452. * @param string $temppath path to temporary dir with unzip output
  6453. * @param string $destpath destination path
  6454. * @return void
  6455. */
  6456. function unzip_process_temp_dir($temppath, $destpath) {
  6457. global $CFG;
  6458. $filepermissions = ($CFG->directorypermissions & 0666); // strip execute flags
  6459. if (check_dir_exists($destpath, true, true)) {
  6460. $currdir = opendir($temppath);
  6461. while (false !== ($file = readdir($currdir))) {
  6462. if ($file <> ".." && $file <> ".") {
  6463. $fullfile = "$temppath/$file";
  6464. if (is_link($fullfile)) {
  6465. //somebody tries to sneak in symbolik link - no way!
  6466. continue;
  6467. }
  6468. $cleanfile = clean_param($file, PARAM_FILE); // no dangerous chars
  6469. if ($cleanfile === '') {
  6470. // invalid file name
  6471. continue;
  6472. }
  6473. if ($cleanfile !== $file and file_exists("$temppath/$cleanfile")) {
  6474. // eh, weird chars collision detected
  6475. continue;
  6476. }
  6477. $descfile = "$destpath/$cleanfile";
  6478. if (is_dir($fullfile)) {
  6479. // recurse into subdirs
  6480. unzip_process_temp_dir($fullfile, $descfile);
  6481. }
  6482. if (is_file($fullfile)) {
  6483. // rename and move the file
  6484. if (file_exists($descfile)) {
  6485. //override existing files
  6486. unlink($descfile);
  6487. }
  6488. rename($fullfile, $descfile);
  6489. chmod($descfile, $filepermissions);
  6490. }
  6491. }
  6492. }
  6493. closedir($currdir);
  6494. }
  6495. }
  6496. function unzip_cleanfilename ($p_event, &$p_header) {
  6497. //This function is used as callback in unzip_file() function
  6498. //to clean illegal characters for given platform and to prevent directory traversal.
  6499. //Produces the same result as info-zip unzip.
  6500. $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
  6501. $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
  6502. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  6503. $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
  6504. $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
  6505. } else {
  6506. //Add filtering for other systems here
  6507. // BSD: none (tested)
  6508. // Linux: ??
  6509. // MacosX: ??
  6510. }
  6511. $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
  6512. return 1;
  6513. }
  6514. function unzip_show_status($list, $removepath, $removepath2) {
  6515. //This function shows the results of the unzip execution
  6516. //depending of the value of the $CFG->zip, results will be
  6517. //text or an array of files.
  6518. global $CFG;
  6519. if (empty($CFG->unzip)) { // Use built-in php-based zip function
  6520. $strname = get_string("name");
  6521. $strsize = get_string("size");
  6522. $strmodified = get_string("modified");
  6523. $strstatus = get_string("status");
  6524. echo "<table width=\"640\">";
  6525. echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
  6526. echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
  6527. echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
  6528. echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
  6529. foreach ($list as $item) {
  6530. echo "<tr>";
  6531. $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
  6532. $item['filename'] = str_replace(cleardoubleslashes($removepath2).'/', "", $item['filename']);
  6533. print_cell("left", s(clean_param($item['filename'], PARAM_PATH)));
  6534. if (! $item['folder']) {
  6535. print_cell("right", display_size($item['size']));
  6536. } else {
  6537. echo "<td>&nbsp;</td>";
  6538. }
  6539. $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
  6540. print_cell("right", $filedate);
  6541. print_cell("right", $item['status']);
  6542. echo "</tr>";
  6543. }
  6544. echo "</table>";
  6545. } else { // Use external zip program
  6546. print_simple_box_start("center");
  6547. echo "<pre>";
  6548. foreach ($list as $item) {
  6549. $item = str_replace(cleardoubleslashes($removepath.'/'), '', $item);
  6550. $item = str_replace(cleardoubleslashes($removepath2.'/'), '', $item);
  6551. echo s($item).'<br />';
  6552. }
  6553. echo "</pre>";
  6554. print_simple_box_end();
  6555. }
  6556. }
  6557. /**
  6558. * Returns most reliable client address
  6559. *
  6560. * @return string The remote IP address
  6561. */
  6562. define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
  6563. define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
  6564. function getremoteaddr() {
  6565. global $CFG;
  6566. if (empty($CFG->getremoteaddrconf)) {
  6567. // This will happen, for example, before just after the upgrade, as the
  6568. // user is redirected to the admin screen.
  6569. $variablestoskip = 0;
  6570. } else {
  6571. $variablestoskip = $CFG->getremoteaddrconf;
  6572. }
  6573. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
  6574. if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
  6575. return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
  6576. }
  6577. }
  6578. if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
  6579. if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  6580. return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
  6581. }
  6582. }
  6583. if (!empty($_SERVER['REMOTE_ADDR'])) {
  6584. return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
  6585. } else {
  6586. return null;
  6587. }
  6588. }
  6589. /**
  6590. * Cleans a remote address ready to put into the log table
  6591. */
  6592. function cleanremoteaddr($addr) {
  6593. $originaladdr = $addr;
  6594. $matches = array();
  6595. // first get all things that look like IP addresses.
  6596. if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER)) {
  6597. return '';
  6598. }
  6599. $goodmatches = array();
  6600. $lanmatches = array();
  6601. foreach ($matches as $match) {
  6602. // print_r($match);
  6603. // check to make sure it's not an internal address.
  6604. // the following are reserved for private lans...
  6605. // 10.0.0.0 - 10.255.255.255
  6606. // 172.16.0.0 - 172.31.255.255
  6607. // 192.168.0.0 - 192.168.255.255
  6608. // 169.254.0.0 -169.254.255.255
  6609. $bits = explode('.',$match[0]);
  6610. if (count($bits) != 4) {
  6611. // weird, preg match shouldn't give us it.
  6612. continue;
  6613. }
  6614. if (($bits[0] == 10)
  6615. || ($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
  6616. || ($bits[0] == 192 && $bits[1] == 168)
  6617. || ($bits[0] == 169 && $bits[1] == 254)) {
  6618. $lanmatches[] = $match[0];
  6619. continue;
  6620. }
  6621. // finally, it's ok
  6622. $goodmatches[] = $match[0];
  6623. }
  6624. if (!count($goodmatches)) {
  6625. // perhaps we have a lan match, it's probably better to return that.
  6626. if (!count($lanmatches)) {
  6627. return '';
  6628. } else {
  6629. return array_pop($lanmatches);
  6630. }
  6631. }
  6632. if (count($goodmatches) == 1) {
  6633. return $goodmatches[0];
  6634. }
  6635. //Commented out following because there are so many, and it clogs the logs MDL-13544
  6636. //error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
  6637. // We need to return something, so return the first
  6638. return array_pop($goodmatches);
  6639. }
  6640. /**
  6641. * file_put_contents is only supported by php 5.0 and higher
  6642. * so if it is not predefined, define it here
  6643. *
  6644. * @param $file full path of the file to write
  6645. * @param $contents contents to be sent
  6646. * @return number of bytes written (false on error)
  6647. */
  6648. if(!function_exists('file_put_contents')) {
  6649. function file_put_contents($file, $contents) {
  6650. $result = false;
  6651. if ($f = fopen($file, 'w')) {
  6652. $result = fwrite($f, $contents);
  6653. fclose($f);
  6654. }
  6655. return $result;
  6656. }
  6657. }
  6658. /**
  6659. * The clone keyword is only supported from PHP 5 onwards.
  6660. * The behaviour of $obj2 = $obj1 differs fundamentally
  6661. * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
  6662. * created, in PHP 5 $obj1 is referenced. To create a copy
  6663. * in PHP 5 the clone keyword was introduced. This function
  6664. * simulates this behaviour for PHP < 5.0.0.
  6665. * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
  6666. *
  6667. * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
  6668. * Found a better implementation (more checks and possibilities) from PEAR:
  6669. * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
  6670. *
  6671. * @param object $obj
  6672. * @return object
  6673. */
  6674. if(!check_php_version('5.0.0')) {
  6675. // the eval is needed to prevent PHP 5 from getting a parse error!
  6676. eval('
  6677. function clone($obj) {
  6678. /// Sanity check
  6679. if (!is_object($obj)) {
  6680. user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
  6681. return;
  6682. }
  6683. /// Use serialize/unserialize trick to deep copy the object
  6684. $obj = unserialize(serialize($obj));
  6685. /// If there is a __clone method call it on the "new" class
  6686. if (method_exists($obj, \'__clone\')) {
  6687. $obj->__clone();
  6688. }
  6689. return $obj;
  6690. }
  6691. // Supply the PHP5 function scandir() to older versions.
  6692. function scandir($directory) {
  6693. $files = array();
  6694. if ($dh = opendir($directory)) {
  6695. while (($file = readdir($dh)) !== false) {
  6696. $files[] = $file;
  6697. }
  6698. closedir($dh);
  6699. }
  6700. return $files;
  6701. }
  6702. // Supply the PHP5 function array_combine() to older versions.
  6703. function array_combine($keys, $values) {
  6704. if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
  6705. return false;
  6706. }
  6707. reset($values);
  6708. $result = array();
  6709. foreach ($keys as $key) {
  6710. $result[$key] = current($values);
  6711. next($values);
  6712. }
  6713. return $result;
  6714. }
  6715. ');
  6716. }
  6717. /**
  6718. * This function will make a complete copy of anything it's given,
  6719. * regardless of whether it's an object or not.
  6720. * @param mixed $thing
  6721. * @return mixed
  6722. */
  6723. function fullclone($thing) {
  6724. return unserialize(serialize($thing));
  6725. }
  6726. /*
  6727. * This function expects to called during shutdown
  6728. * should be set via register_shutdown_function()
  6729. * in lib/setup.php .
  6730. *
  6731. * Right now we do it only if we are under apache, to
  6732. * make sure apache children that hog too much mem are
  6733. * killed.
  6734. *
  6735. */
  6736. function moodle_request_shutdown() {
  6737. global $CFG;
  6738. // initially, we are only ever called under apache
  6739. // but check just in case
  6740. if (function_exists('apache_child_terminate')
  6741. && function_exists('memory_get_usage')
  6742. && ini_get_bool('child_terminate')) {
  6743. if (empty($CFG->apachemaxmem)) {
  6744. $CFG->apachemaxmem = 25000000; // default 25MiB
  6745. }
  6746. if (memory_get_usage() > (int)$CFG->apachemaxmem) {
  6747. trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
  6748. @apache_child_terminate();
  6749. }
  6750. }
  6751. if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
  6752. if (defined('MDL_PERFTOLOG')) {
  6753. $perf = get_performance_info();
  6754. error_log("PERF: " . $perf['txt']);
  6755. }
  6756. if (defined('MDL_PERFINC')) {
  6757. $inc = get_included_files();
  6758. $ts = 0;
  6759. foreach($inc as $f) {
  6760. if (preg_match(':^/:', $f)) {
  6761. $fs = filesize($f);
  6762. $ts += $fs;
  6763. $hfs = display_size($fs);
  6764. error_log(substr($f,strlen($CFG->dirroot)) . " size: $fs ($hfs)"
  6765. , NULL, NULL, 0);
  6766. } else {
  6767. error_log($f , NULL, NULL, 0);
  6768. }
  6769. }
  6770. if ($ts > 0 ) {
  6771. $hts = display_size($ts);
  6772. error_log("Total size of files included: $ts ($hts)");
  6773. }
  6774. }
  6775. }
  6776. }
  6777. /**
  6778. * If new messages are waiting for the current user, then return
  6779. * Javascript code to create a popup window
  6780. *
  6781. * @return string Javascript code
  6782. */
  6783. function message_popup_window() {
  6784. global $USER;
  6785. $popuplimit = 30; // Minimum seconds between popups
  6786. if (!defined('MESSAGE_WINDOW')) {
  6787. if (isset($USER->id) and !isguestuser()) {
  6788. if (!isset($USER->message_lastpopup)) {
  6789. $USER->message_lastpopup = 0;
  6790. }
  6791. if ((time() - $USER->message_lastpopup) > $popuplimit) { /// It's been long enough
  6792. if (get_user_preferences('message_showmessagewindow', 1) == 1) {
  6793. if (count_records_select('message', 'useridto = \''.$USER->id.'\' AND timecreated > \''.$USER->message_lastpopup.'\'')) {
  6794. $USER->message_lastpopup = time();
  6795. return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
  6796. 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
  6797. }
  6798. }
  6799. }
  6800. }
  6801. }
  6802. return '';
  6803. }
  6804. // Used to make sure that $min <= $value <= $max
  6805. function bounded_number($min, $value, $max) {
  6806. if($value < $min) {
  6807. return $min;
  6808. }
  6809. if($value > $max) {
  6810. return $max;
  6811. }
  6812. return $value;
  6813. }
  6814. function array_is_nested($array) {
  6815. foreach ($array as $value) {
  6816. if (is_array($value)) {
  6817. return true;
  6818. }
  6819. }
  6820. return false;
  6821. }
  6822. /**
  6823. *** get_performance_info() pairs up with init_performance_info()
  6824. *** loaded in setup.php. Returns an array with 'html' and 'txt'
  6825. *** values ready for use, and each of the individual stats provided
  6826. *** separately as well.
  6827. ***
  6828. **/
  6829. function get_performance_info() {
  6830. global $CFG, $PERF, $rcache;
  6831. $info = array();
  6832. $info['html'] = ''; // holds userfriendly HTML representation
  6833. $info['txt'] = me() . ' '; // holds log-friendly representation
  6834. $info['realtime'] = microtime_diff($PERF->starttime, microtime());
  6835. $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
  6836. $info['txt'] .= 'time: '.$info['realtime'].'s ';
  6837. if (function_exists('memory_get_usage')) {
  6838. $info['memory_total'] = memory_get_usage();
  6839. $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
  6840. $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
  6841. $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
  6842. }
  6843. if (function_exists('memory_get_peak_usage')) {
  6844. $info['memory_peak'] = memory_get_peak_usage();
  6845. $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
  6846. $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
  6847. }
  6848. $inc = get_included_files();
  6849. //error_log(print_r($inc,1));
  6850. $info['includecount'] = count($inc);
  6851. $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
  6852. $info['txt'] .= 'includecount: '.$info['includecount'].' ';
  6853. if (!empty($PERF->dbqueries)) {
  6854. $info['dbqueries'] = $PERF->dbqueries;
  6855. $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
  6856. $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
  6857. }
  6858. if (!empty($PERF->logwrites)) {
  6859. $info['logwrites'] = $PERF->logwrites;
  6860. $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
  6861. $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
  6862. }
  6863. if (!empty($PERF->profiling) && $PERF->profiling) {
  6864. require_once($CFG->dirroot .'/lib/profilerlib.php');
  6865. $info['html'] .= '<span class="profilinginfo">'.Profiler::get_profiling(array('-R')).'</span>';
  6866. }
  6867. if (function_exists('posix_times')) {
  6868. $ptimes = posix_times();
  6869. if (is_array($ptimes)) {
  6870. foreach ($ptimes as $key => $val) {
  6871. $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
  6872. }
  6873. $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
  6874. $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
  6875. }
  6876. }
  6877. // Grab the load average for the last minute
  6878. // /proc will only work under some linux configurations
  6879. // while uptime is there under MacOSX/Darwin and other unices
  6880. if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
  6881. list($server_load) = explode(' ', $loadavg[0]);
  6882. unset($loadavg);
  6883. } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
  6884. if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
  6885. $server_load = $matches[1];
  6886. } else {
  6887. trigger_error('Could not parse uptime output!');
  6888. }
  6889. }
  6890. if (!empty($server_load)) {
  6891. $info['serverload'] = $server_load;
  6892. $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
  6893. $info['txt'] .= "serverload: {$info['serverload']} ";
  6894. }
  6895. if (isset($rcache->hits) && isset($rcache->misses)) {
  6896. $info['rcachehits'] = $rcache->hits;
  6897. $info['rcachemisses'] = $rcache->misses;
  6898. $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
  6899. "{$rcache->hits}/{$rcache->misses}</span> ";
  6900. $info['txt'] .= 'rcache: '.
  6901. "{$rcache->hits}/{$rcache->misses} ";
  6902. }
  6903. $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
  6904. return $info;
  6905. }
  6906. function apd_get_profiling() {
  6907. return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
  6908. }
  6909. /**
  6910. * Delete directory or only it's content
  6911. * @param string $dir directory path
  6912. * @param bool $content_only
  6913. * @return bool success, true also if dir does not exist
  6914. */
  6915. function remove_dir($dir, $content_only=false) {
  6916. if (!file_exists($dir)) {
  6917. // nothing to do
  6918. return true;
  6919. }
  6920. $handle = opendir($dir);
  6921. $result = true;
  6922. while (false!==($item = readdir($handle))) {
  6923. if($item != '.' && $item != '..') {
  6924. if(is_dir($dir.'/'.$item)) {
  6925. $result = remove_dir($dir.'/'.$item) && $result;
  6926. }else{
  6927. $result = unlink($dir.'/'.$item) && $result;
  6928. }
  6929. }
  6930. }
  6931. closedir($handle);
  6932. if ($content_only) {
  6933. return $result;
  6934. }
  6935. return rmdir($dir); // if anything left the result will be false, noo need for && $result
  6936. }
  6937. /**
  6938. * Function to check if a directory exists and optionally create it.
  6939. *
  6940. * @param string absolute directory path (must be under $CFG->dataroot)
  6941. * @param boolean create directory if does not exist
  6942. * @param boolean create directory recursively
  6943. *
  6944. * @return boolean true if directory exists or created
  6945. */
  6946. function check_dir_exists($dir, $create=false, $recursive=false) {
  6947. global $CFG;
  6948. if (strstr(cleardoubleslashes($dir), cleardoubleslashes($CFG->dataroot.'/')) === false) {
  6949. debugging('Warning. Wrong call to check_dir_exists(). $dir must be an absolute path under $CFG->dataroot ("' . $dir . '" is incorrect)', DEBUG_DEVELOPER);
  6950. }
  6951. $status = true;
  6952. if(!is_dir($dir)) {
  6953. if (!$create) {
  6954. $status = false;
  6955. } else {
  6956. umask(0000);
  6957. if ($recursive) {
  6958. /// We are going to make it recursive under $CFG->dataroot only
  6959. /// (will help sites running open_basedir security and others)
  6960. $dir = str_replace(cleardoubleslashes($CFG->dataroot . '/'), '', cleardoubleslashes($dir));
  6961. /// PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
  6962. $dirs = explode('/', $dir); /// Extract path parts
  6963. /// Iterate over each part with start point $CFG->dataroot
  6964. $dir = $CFG->dataroot . '/';
  6965. foreach ($dirs as $part) {
  6966. if ($part == '') {
  6967. continue;
  6968. }
  6969. $dir .= $part.'/';
  6970. if (!is_dir($dir)) {
  6971. if (!mkdir($dir, $CFG->directorypermissions)) {
  6972. $status = false;
  6973. break;
  6974. }
  6975. }
  6976. }
  6977. } else {
  6978. $status = mkdir($dir, $CFG->directorypermissions);
  6979. }
  6980. }
  6981. }
  6982. return $status;
  6983. }
  6984. function report_session_error() {
  6985. global $CFG, $FULLME;
  6986. if (empty($CFG->lang)) {
  6987. $CFG->lang = "en";
  6988. }
  6989. // Set up default theme and locale
  6990. theme_setup();
  6991. moodle_setlocale();
  6992. //clear session cookies
  6993. if (check_php_version('5.2.0')) {
  6994. //PHP 5.2.0
  6995. setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
  6996. setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure, $CFG->cookiehttponly);
  6997. } else {
  6998. setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
  6999. setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, $CFG->sessioncookiedomain, $CFG->cookiesecure);
  7000. }
  7001. //increment database error counters
  7002. if (isset($CFG->session_error_counter)) {
  7003. set_config('session_error_counter', 1 + $CFG->session_error_counter);
  7004. } else {
  7005. set_config('session_error_counter', 1);
  7006. }
  7007. redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
  7008. }
  7009. /**
  7010. * Detect if an object or a class contains a given property
  7011. * will take an actual object or the name of a class
  7012. * @param mix $obj Name of class or real object to test
  7013. * @param string $property name of property to find
  7014. * @return bool true if property exists
  7015. */
  7016. function object_property_exists( $obj, $property ) {
  7017. if (is_string( $obj )) {
  7018. $properties = get_class_vars( $obj );
  7019. }
  7020. else {
  7021. $properties = get_object_vars( $obj );
  7022. }
  7023. return array_key_exists( $property, $properties );
  7024. }
  7025. /**
  7026. * Detect a custom script replacement in the data directory that will
  7027. * replace an existing moodle script
  7028. * @param string $urlpath path to the original script
  7029. * @return string full path name if a custom script exists
  7030. * @return bool false if no custom script exists
  7031. */
  7032. function custom_script_path($urlpath='') {
  7033. global $CFG;
  7034. // set default $urlpath, if necessary
  7035. if (empty($urlpath)) {
  7036. $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
  7037. }
  7038. // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
  7039. if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot) === false )) {
  7040. return false;
  7041. }
  7042. // replace wwwroot with the path to the customscripts folder and clean path
  7043. $scriptpath = $CFG->customscripts . clean_param(substr($urlpath, strlen($CFG->wwwroot)), PARAM_PATH);
  7044. // remove the query string, if any
  7045. if (($strpos = strpos($scriptpath, '?')) !== false) {
  7046. $scriptpath = substr($scriptpath, 0, $strpos);
  7047. }
  7048. // remove trailing slashes, if any
  7049. $scriptpath = rtrim($scriptpath, '/\\');
  7050. // append index.php, if necessary
  7051. if (is_dir($scriptpath)) {
  7052. $scriptpath .= '/index.php';
  7053. }
  7054. // check the custom script exists
  7055. if (file_exists($scriptpath)) {
  7056. return $scriptpath;
  7057. } else {
  7058. return false;
  7059. }
  7060. }
  7061. /**
  7062. * Wrapper function to load necessary editor scripts
  7063. * to $CFG->editorsrc array. Params can be coursei id
  7064. * or associative array('courseid' => value, 'name' => 'editorname').
  7065. * @uses $CFG
  7066. * @param mixed $args Courseid or associative array.
  7067. */
  7068. function loadeditor($args) {
  7069. global $CFG;
  7070. include($CFG->libdir .'/editorlib.php');
  7071. return editorObject::loadeditor($args);
  7072. }
  7073. /**
  7074. * Returns whether or not the user object is a remote MNET user. This function
  7075. * is in moodlelib because it does not rely on loading any of the MNET code.
  7076. *
  7077. * @param object $user A valid user object
  7078. * @return bool True if the user is from a remote Moodle.
  7079. */
  7080. function is_mnet_remote_user($user) {
  7081. global $CFG;
  7082. if (!isset($CFG->mnet_localhost_id)) {
  7083. include_once $CFG->dirroot . '/mnet/lib.php';
  7084. $env = new mnet_environment();
  7085. $env->init();
  7086. unset($env);
  7087. }
  7088. return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
  7089. }
  7090. /**
  7091. * Checks if a given plugin is in the list of enabled enrolment plugins.
  7092. *
  7093. * @param string $auth Enrolment plugin.
  7094. * @return boolean Whether the plugin is enabled.
  7095. */
  7096. function is_enabled_enrol($enrol='') {
  7097. global $CFG;
  7098. // use the global default if not specified
  7099. if ($enrol == '') {
  7100. $enrol = $CFG->enrol;
  7101. }
  7102. return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
  7103. }
  7104. /**
  7105. * This function will search for browser prefereed languages, setting Moodle
  7106. * to use the best one available if $SESSION->lang is undefined
  7107. */
  7108. function setup_lang_from_browser() {
  7109. global $CFG, $SESSION, $USER;
  7110. if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
  7111. // Lang is defined in session or user profile, nothing to do
  7112. return;
  7113. }
  7114. if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
  7115. return;
  7116. }
  7117. /// Extract and clean langs from headers
  7118. $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  7119. $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
  7120. $rawlangs = explode(',', $rawlangs); // Convert to array
  7121. $langs = array();
  7122. $order = 1.0;
  7123. foreach ($rawlangs as $lang) {
  7124. if (strpos($lang, ';') === false) {
  7125. $langs[(string)$order] = $lang;
  7126. $order = $order-0.01;
  7127. } else {
  7128. $parts = explode(';', $lang);
  7129. $pos = strpos($parts[1], '=');
  7130. $langs[substr($parts[1], $pos+1)] = $parts[0];
  7131. }
  7132. }
  7133. krsort($langs, SORT_NUMERIC);
  7134. $langlist = get_list_of_languages();
  7135. /// Look for such langs under standard locations
  7136. foreach ($langs as $lang) {
  7137. $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR)); // clean it properly for include
  7138. if (!array_key_exists($lang, $langlist)) {
  7139. continue; // language not allowed, try next one
  7140. }
  7141. if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
  7142. $SESSION->lang = $lang; /// Lang exists, set it in session
  7143. break; /// We have finished. Go out
  7144. }
  7145. }
  7146. return;
  7147. }
  7148. ////////////////////////////////////////////////////////////////////////////////
  7149. function is_newnav($navigation) {
  7150. if (is_array($navigation) && !empty($navigation['newnav'])) {
  7151. return true;
  7152. } else {
  7153. return false;
  7154. }
  7155. }
  7156. /**
  7157. * Checks whether the given variable name is defined as a variable within the given object.
  7158. * @note This will NOT work with stdClass objects, which have no class variables.
  7159. * @param string $var The variable name
  7160. * @param object $object The object to check
  7161. * @return boolean
  7162. */
  7163. function in_object_vars($var, $object) {
  7164. $class_vars = get_class_vars(get_class($object));
  7165. $class_vars = array_keys($class_vars);
  7166. return in_array($var, $class_vars);
  7167. }
  7168. /**
  7169. * Returns an array without repeated objects.
  7170. * This function is similar to array_unique, but for arrays that have objects as values
  7171. *
  7172. * @param unknown_type $array
  7173. * @param unknown_type $keep_key_assoc
  7174. * @return unknown
  7175. */
  7176. function object_array_unique($array, $keep_key_assoc = true) {
  7177. $duplicate_keys = array();
  7178. $tmp = array();
  7179. foreach ($array as $key=>$val) {
  7180. // convert objects to arrays, in_array() does not support objects
  7181. if (is_object($val)) {
  7182. $val = (array)$val;
  7183. }
  7184. if (!in_array($val, $tmp)) {
  7185. $tmp[] = $val;
  7186. } else {
  7187. $duplicate_keys[] = $key;
  7188. }
  7189. }
  7190. foreach ($duplicate_keys as $key) {
  7191. unset($array[$key]);
  7192. }
  7193. return $keep_key_assoc ? $array : array_values($array);
  7194. }
  7195. /**
  7196. * Returns the language string for the given plugin.
  7197. *
  7198. * @param string $plugin the plugin code name
  7199. * @param string $type the type of plugin (mod, block, filter)
  7200. * @return string The plugin language string
  7201. */
  7202. function get_plugin_name($plugin, $type='mod') {
  7203. $plugin_name = '';
  7204. switch ($type) {
  7205. case 'mod':
  7206. $plugin_name = get_string('modulename', $plugin);
  7207. break;
  7208. case 'blocks':
  7209. $plugin_name = get_string('blockname', "block_$plugin");
  7210. if (empty($plugin_name) || $plugin_name == '[[blockname]]') {
  7211. if (($block = block_instance($plugin)) !== false) {
  7212. $plugin_name = $block->get_title();
  7213. } else {
  7214. $plugin_name = "[[$plugin]]";
  7215. }
  7216. }
  7217. break;
  7218. case 'filter':
  7219. $plugin_name = trim(get_string('filtername', $plugin));
  7220. if (empty($plugin_name) or ($plugin_name == '[[filtername]]')) {
  7221. $textlib = textlib_get_instance();
  7222. $plugin_name = $textlib->strtotitle($plugin);
  7223. }
  7224. break;
  7225. default:
  7226. $plugin_name = $plugin;
  7227. break;
  7228. }
  7229. return $plugin_name;
  7230. }
  7231. /**
  7232. * Is a userid the primary administrator?
  7233. *
  7234. * @param $userid int id of user to check
  7235. * @return boolean
  7236. */
  7237. function is_primary_admin($userid){
  7238. $primaryadmin = get_admin();
  7239. if($userid == $primaryadmin->id){
  7240. return true;
  7241. }else{
  7242. return false;
  7243. }
  7244. }
  7245. /**
  7246. * @return string $CFG->siteidentifier, first making sure it is properly initialised.
  7247. */
  7248. function get_site_identifier() {
  7249. global $CFG;
  7250. // Check to see if it is missing. If so, initialise it.
  7251. if (empty($CFG->siteidentifier)) {
  7252. set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
  7253. }
  7254. // Return it.
  7255. return $CFG->siteidentifier;
  7256. }
  7257. // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
  7258. ?>