MDL-6850 Removed apparent-size from du
[moodle-linuxchix.git] / lib / moodlelib.php
blobfbe8c46484f7c74fafb4b4336658592470406c87
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999 onwards Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * moodlelib.php - Moodle main library
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
33 * @author Martin Dougiamas
34 * @version $Id$
35 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
36 * @package moodlecore
39 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
41 /**
42 * Used by some scripts to check they are being called by Moodle
44 define('MOODLE_INTERNAL', true);
46 /// Date and time constants ///
47 /**
48 * Time constant - the number of seconds in a year
51 define('YEARSECS', 31536000);
53 /**
54 * Time constant - the number of seconds in a week
56 define('WEEKSECS', 604800);
58 /**
59 * Time constant - the number of seconds in a day
61 define('DAYSECS', 86400);
63 /**
64 * Time constant - the number of seconds in an hour
66 define('HOURSECS', 3600);
68 /**
69 * Time constant - the number of seconds in a minute
71 define('MINSECS', 60);
73 /**
74 * Time constant - the number of minutes in a day
76 define('DAYMINS', 1440);
78 /**
79 * Time constant - the number of minutes in an hour
81 define('HOURMINS', 60);
83 /// Parameter constants - every call to optional_param(), required_param() ///
84 /// or clean_param() should have a specified type of parameter. //////////////
86 /**
87 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
88 * originally was 0, but changed because we need to detect unknown
89 * parameter types and swiched order in clean_param().
91 define('PARAM_RAW', 666);
93 /**
94 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
95 * It was one of the first types, that is why it is abused so much ;-)
97 define('PARAM_CLEAN', 0x0001);
99 /**
100 * PARAM_INT - integers only, use when expecting only numbers.
102 define('PARAM_INT', 0x0002);
105 * PARAM_INTEGER - an alias for PARAM_INT
107 define('PARAM_INTEGER', 0x0002);
110 * PARAM_NUMBER - a real/floating point number.
112 define('PARAM_NUMBER', 0x000a);
115 * PARAM_ALPHA - contains only english letters.
117 define('PARAM_ALPHA', 0x0004);
120 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
121 * @TODO: should we alias it to PARAM_ALPHANUM ?
123 define('PARAM_ACTION', 0x0004);
126 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
127 * @TODO: should we alias it to PARAM_ALPHANUM ?
129 define('PARAM_FORMAT', 0x0004);
132 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
134 define('PARAM_NOTAGS', 0x0008);
137 * PARAM_MULTILANG - alias of PARAM_TEXT.
139 define('PARAM_MULTILANG', 0x0009);
142 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
144 define('PARAM_TEXT', 0x0009);
147 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
149 define('PARAM_FILE', 0x0010);
152 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international alphanumeric with spaces
154 define('PARAM_TAG', 0x0011);
157 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
159 define('PARAM_TAGLIST', 0x0012);
162 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
163 * note: the leading slash is not removed, window drive letter is not allowed
165 define('PARAM_PATH', 0x0020);
168 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
170 define('PARAM_HOST', 0x0040);
173 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not acceppted but http://localhost.localdomain/ is ok.
175 define('PARAM_URL', 0x0080);
178 * 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!)
180 define('PARAM_LOCALURL', 0x0180);
183 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
184 * use when you want to store a new file submitted by students
186 define('PARAM_CLEANFILE',0x0200);
189 * PARAM_ALPHANUM - expected numbers and letters only.
191 define('PARAM_ALPHANUM', 0x0400);
194 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
196 define('PARAM_BOOL', 0x0800);
199 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
200 * note: do not forget to addslashes() before storing into database!
202 define('PARAM_CLEANHTML',0x1000);
205 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
206 * suitable for include() and require()
207 * @TODO: should we rename this function to PARAM_SAFEDIRS??
209 define('PARAM_ALPHAEXT', 0x2000);
212 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
214 define('PARAM_SAFEDIR', 0x4000);
217 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
219 define('PARAM_SEQUENCE', 0x8000);
222 * PARAM_PEM - Privacy Enhanced Mail format
224 define('PARAM_PEM', 0x10000);
227 * PARAM_BASE64 - Base 64 encoded format
229 define('PARAM_BASE64', 0x20000);
232 /// Page types ///
234 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
236 define('PAGE_COURSE_VIEW', 'course-view');
238 /// Debug levels ///
239 /** no warnings at all */
240 define ('DEBUG_NONE', 0);
241 /** E_ERROR | E_PARSE */
242 define ('DEBUG_MINIMAL', 5);
243 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
244 define ('DEBUG_NORMAL', 15);
245 /** E_ALL without E_STRICT for now, do show recoverable fatal errors */
246 define ('DEBUG_ALL', 6143);
247 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
248 define ('DEBUG_DEVELOPER', 38911);
251 * Blog access level constant declaration
253 define ('BLOG_USER_LEVEL', 1);
254 define ('BLOG_GROUP_LEVEL', 2);
255 define ('BLOG_COURSE_LEVEL', 3);
256 define ('BLOG_SITE_LEVEL', 4);
257 define ('BLOG_GLOBAL_LEVEL', 5);
260 * Tag constanst
262 //To prevent problems with multibytes strings, this should not exceed the
263 //length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
264 define('TAG_MAX_LENGTH', 50);
267 * Password policy constants
269 define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
270 define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
271 define ('PASSWORD_DIGITS', '0123456789');
272 define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
274 if (!defined('SORT_LOCALE_STRING')) { // PHP < 4.4.0 - TODO: remove in 2.0
275 define('SORT_LOCALE_STRING', SORT_STRING);
279 /// PARAMETER HANDLING ////////////////////////////////////////////////////
282 * Returns a particular value for the named variable, taken from
283 * POST or GET. If the parameter doesn't exist then an error is
284 * thrown because we require this variable.
286 * This function should be used to initialise all required values
287 * in a script that are based on parameters. Usually it will be
288 * used like this:
289 * $id = required_param('id');
291 * @param string $parname the name of the page parameter we want
292 * @param int $type expected type of parameter
293 * @return mixed
295 function required_param($parname, $type=PARAM_CLEAN) {
297 // detect_unchecked_vars addition
298 global $CFG;
299 if (!empty($CFG->detect_unchecked_vars)) {
300 global $UNCHECKED_VARS;
301 unset ($UNCHECKED_VARS->vars[$parname]);
304 if (isset($_POST[$parname])) { // POST has precedence
305 $param = $_POST[$parname];
306 } else if (isset($_GET[$parname])) {
307 $param = $_GET[$parname];
308 } else {
309 error('A required parameter ('.$parname.') was missing');
312 return clean_param($param, $type);
316 * Returns a particular value for the named variable, taken from
317 * POST or GET, otherwise returning a given default.
319 * This function should be used to initialise all optional values
320 * in a script that are based on parameters. Usually it will be
321 * used like this:
322 * $name = optional_param('name', 'Fred');
324 * @param string $parname the name of the page parameter we want
325 * @param mixed $default the default value to return if nothing is found
326 * @param int $type expected type of parameter
327 * @return mixed
329 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
331 // detect_unchecked_vars addition
332 global $CFG;
333 if (!empty($CFG->detect_unchecked_vars)) {
334 global $UNCHECKED_VARS;
335 unset ($UNCHECKED_VARS->vars[$parname]);
338 if (isset($_POST[$parname])) { // POST has precedence
339 $param = $_POST[$parname];
340 } else if (isset($_GET[$parname])) {
341 $param = $_GET[$parname];
342 } else {
343 return $default;
346 return clean_param($param, $type);
350 * Used by {@link optional_param()} and {@link required_param()} to
351 * clean the variables and/or cast to specific types, based on
352 * an options field.
353 * <code>
354 * $course->format = clean_param($course->format, PARAM_ALPHA);
355 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
356 * </code>
358 * @uses $CFG
359 * @uses PARAM_RAW
360 * @uses PARAM_CLEAN
361 * @uses PARAM_CLEANHTML
362 * @uses PARAM_INT
363 * @uses PARAM_NUMBER
364 * @uses PARAM_ALPHA
365 * @uses PARAM_ALPHANUM
366 * @uses PARAM_ALPHAEXT
367 * @uses PARAM_SEQUENCE
368 * @uses PARAM_BOOL
369 * @uses PARAM_NOTAGS
370 * @uses PARAM_TEXT
371 * @uses PARAM_SAFEDIR
372 * @uses PARAM_CLEANFILE
373 * @uses PARAM_FILE
374 * @uses PARAM_PATH
375 * @uses PARAM_HOST
376 * @uses PARAM_URL
377 * @uses PARAM_LOCALURL
378 * @uses PARAM_PEM
379 * @uses PARAM_BASE64
380 * @uses PARAM_TAG
381 * @uses PARAM_SEQUENCE
382 * @param mixed $param the variable we are cleaning
383 * @param int $type expected format of param after cleaning.
384 * @return mixed
386 function clean_param($param, $type) {
388 global $CFG;
390 if (is_array($param)) { // Let's loop
391 $newparam = array();
392 foreach ($param as $key => $value) {
393 $newparam[$key] = clean_param($value, $type);
395 return $newparam;
398 switch ($type) {
399 case PARAM_RAW: // no cleaning at all
400 return $param;
402 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
403 if (is_numeric($param)) {
404 return $param;
406 $param = stripslashes($param); // Needed for kses to work fine
407 $param = clean_text($param); // Sweep for scripts, etc
408 return addslashes($param); // Restore original request parameter slashes
410 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
411 $param = stripslashes($param); // Remove any slashes
412 $param = clean_text($param); // Sweep for scripts, etc
413 return trim($param);
415 case PARAM_INT:
416 return (int)$param; // Convert to integer
418 case PARAM_NUMBER:
419 return (float)$param; // Convert to integer
421 case PARAM_ALPHA: // Remove everything not a-z
422 return eregi_replace('[^a-zA-Z]', '', $param);
424 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
425 return eregi_replace('[^A-Za-z0-9]', '', $param);
427 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z/_-
428 return eregi_replace('[^a-zA-Z/_-]', '', $param);
430 case PARAM_SEQUENCE: // Remove everything not 0-9,
431 return eregi_replace('[^0-9,]', '', $param);
433 case PARAM_BOOL: // Convert to 1 or 0
434 $tempstr = strtolower($param);
435 if ($tempstr == 'on' or $tempstr == 'yes' ) {
436 $param = 1;
437 } else if ($tempstr == 'off' or $tempstr == 'no') {
438 $param = 0;
439 } else {
440 $param = empty($param) ? 0 : 1;
442 return $param;
444 case PARAM_NOTAGS: // Strip all tags
445 return strip_tags($param);
447 case PARAM_TEXT: // leave only tags needed for multilang
448 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
450 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
451 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
453 case PARAM_CLEANFILE: // allow only safe characters
454 return clean_filename($param);
456 case PARAM_FILE: // Strip all suspicious characters from filename
457 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
458 $param = ereg_replace('\.\.+', '', $param);
459 if($param == '.') {
460 $param = '';
462 return $param;
464 case PARAM_PATH: // Strip all suspicious characters from file path
465 $param = str_replace('\\\'', '\'', $param);
466 $param = str_replace('\\"', '"', $param);
467 $param = str_replace('\\', '/', $param);
468 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
469 $param = ereg_replace('\.\.+', '', $param);
470 $param = ereg_replace('//+', '/', $param);
471 return ereg_replace('/(\./)+', '/', $param);
473 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
474 $param = preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
475 // match ipv4 dotted quad
476 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
477 // confirm values are ok
478 if ( $match[0] > 255
479 || $match[1] > 255
480 || $match[3] > 255
481 || $match[4] > 255 ) {
482 // hmmm, what kind of dotted quad is this?
483 $param = '';
485 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
486 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
487 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
489 // all is ok - $param is respected
490 } else {
491 // all is not ok...
492 $param='';
494 return $param;
496 case PARAM_URL: // allow safe ftp, http, mailto urls
497 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
498 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
499 // all is ok, param is respected
500 } else {
501 $param =''; // not really ok
503 return $param;
505 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
506 $param = clean_param($param, PARAM_URL);
507 if (!empty($param)) {
508 if (preg_match(':^/:', $param)) {
509 // root-relative, ok!
510 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
511 // absolute, and matches our wwwroot
512 } else {
513 // relative - let's make sure there are no tricks
514 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
515 // looks ok.
516 } else {
517 $param = '';
521 return $param;
523 case PARAM_PEM:
524 $param = trim($param);
525 // PEM formatted strings may contain letters/numbers and the symbols
526 // forward slash: /
527 // plus sign: +
528 // equal sign: =
529 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
530 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
531 list($wholething, $body) = $matches;
532 unset($wholething, $matches);
533 $b64 = clean_param($body, PARAM_BASE64);
534 if (!empty($b64)) {
535 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
536 } else {
537 return '';
540 return '';
542 case PARAM_BASE64:
543 if (!empty($param)) {
544 // PEM formatted strings may contain letters/numbers and the symbols
545 // forward slash: /
546 // plus sign: +
547 // equal sign: =
548 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
549 return '';
551 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
552 // Each line of base64 encoded data must be 64 characters in
553 // length, except for the last line which may be less than (or
554 // equal to) 64 characters long.
555 for ($i=0, $j=count($lines); $i < $j; $i++) {
556 if ($i + 1 == $j) {
557 if (64 < strlen($lines[$i])) {
558 return '';
560 continue;
563 if (64 != strlen($lines[$i])) {
564 return '';
567 return implode("\n",$lines);
568 } else {
569 return '';
572 case PARAM_TAG:
573 //as long as magic_quotes_gpc is used, a backslash will be a
574 //problem, so remove *all* backslash.
575 $param = str_replace('\\', '', $param);
576 //convert many whitespace chars into one
577 $param = preg_replace('/\s+/', ' ', $param);
578 $textlib = textlib_get_instance();
579 $param = $textlib->substr(trim($param), 0, TAG_MAX_LENGTH);
580 return $param;
583 case PARAM_TAGLIST:
584 $tags = explode(',', $param);
585 $result = array();
586 foreach ($tags as $tag) {
587 $res = clean_param($tag, PARAM_TAG);
588 if ($res != '') {
589 $result[] = $res;
592 if ($result) {
593 return implode(',', $result);
594 } else {
595 return '';
598 default: // throw error, switched parameters in optional_param or another serious problem
599 error("Unknown parameter type: $type");
606 * Set a key in global configuration
608 * Set a key/value pair in both this session's {@link $CFG} global variable
609 * and in the 'config' database table for future sessions.
611 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
612 * In that case it doesn't affect $CFG.
614 * A NULL value will delete the entry.
616 * @param string $name the key to set
617 * @param string $value the value to set (without magic quotes)
618 * @param string $plugin (optional) the plugin scope
619 * @uses $CFG
620 * @return bool
622 function set_config($name, $value, $plugin=NULL) {
623 /// No need for get_config because they are usually always available in $CFG
625 global $CFG;
627 if (empty($plugin)) {
628 if (!array_key_exists($name, $CFG->config_php_settings)) {
629 // So it's defined for this invocation at least
630 if (is_null($value)) {
631 unset($CFG->$name);
632 } else {
633 $CFG->$name = (string)$value; // settings from db are always strings
637 if (get_field('config', 'name', 'name', $name)) {
638 if ($value===null) {
639 return delete_records('config', 'name', $name);
640 } else {
641 return set_field('config', 'value', addslashes($value), 'name', $name);
643 } else {
644 if ($value===null) {
645 return true;
647 $config = new object();
648 $config->name = $name;
649 $config->value = addslashes($value);
650 return insert_record('config', $config);
652 } else { // plugin scope
653 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
654 if ($value===null) {
655 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
656 } else {
657 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
659 } else {
660 if ($value===null) {
661 return true;
663 $config = new object();
664 $config->plugin = addslashes($plugin);
665 $config->name = $name;
666 $config->value = addslashes($value);
667 return insert_record('config_plugins', $config);
673 * Get configuration values from the global config table
674 * or the config_plugins table.
676 * If called with no parameters it will do the right thing
677 * generating $CFG safely from the database without overwriting
678 * existing values.
680 * If called with 2 parameters it will return a $string single
681 * value or false of the value is not found.
683 * @param string $plugin
684 * @param string $name
685 * @uses $CFG
686 * @return hash-like object or single value
689 function get_config($plugin=NULL, $name=NULL) {
691 global $CFG;
693 if (!empty($name)) { // the user is asking for a specific value
694 if (!empty($plugin)) {
695 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
696 } else {
697 return get_field('config', 'value', 'name', $name);
701 // the user is after a recordset
702 if (!empty($plugin)) {
703 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
704 $configs = (array)$configs;
705 $localcfg = array();
706 foreach ($configs as $config) {
707 $localcfg[$config->name] = $config->value;
709 return (object)$localcfg;
710 } else {
711 return false;
713 } else {
714 // this was originally in setup.php
715 if ($configs = get_records('config')) {
716 $localcfg = (array)$CFG;
717 foreach ($configs as $config) {
718 if (!isset($localcfg[$config->name])) {
719 $localcfg[$config->name] = $config->value;
721 // do not complain anymore if config.php overrides settings from db
724 $localcfg = (object)$localcfg;
725 return $localcfg;
726 } else {
727 // preserve $CFG if DB returns nothing or error
728 return $CFG;
735 * Removes a key from global configuration
737 * @param string $name the key to set
738 * @param string $plugin (optional) the plugin scope
739 * @uses $CFG
740 * @return bool
742 function unset_config($name, $plugin=NULL) {
744 global $CFG;
746 unset($CFG->$name);
748 if (empty($plugin)) {
749 return delete_records('config', 'name', $name);
750 } else {
751 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
756 * Get volatile flags
758 * @param string $type
759 * @param int $changedsince
760 * @return records array
763 function get_cache_flags($type, $changedsince=NULL) {
765 $type = addslashes($type);
767 $sqlwhere = 'flagtype=\'' . $type . '\' AND expiry >= ' . time();
768 if ($changedsince !== NULL) {
769 $changedsince = (int)$changedsince;
770 $sqlwhere .= ' AND timemodified > ' . $changedsince;
772 $cf = array();
773 if ($flags=get_records_select('cache_flags', $sqlwhere, '', 'name,value')) {
774 foreach ($flags as $flag) {
775 $cf[$flag->name] = $flag->value;
778 return $cf;
782 * Get volatile flags
784 * @param string $type
785 * @param string $name
786 * @param int $changedsince
787 * @return records array
790 function get_cache_flag($type, $name, $changedsince=NULL) {
792 $type = addslashes($type);
793 $name = addslashes($name);
795 $sqlwhere = 'flagtype=\'' . $type . '\' AND name=\'' . $name . '\' AND expiry >= ' . time();
796 if ($changedsince !== NULL) {
797 $changedsince = (int)$changedsince;
798 $sqlwhere .= ' AND timemodified > ' . $changedsince;
800 return get_field_select('cache_flags', 'value', $sqlwhere);
804 * Set a volatile flag
806 * @param string $type the "type" namespace for the key
807 * @param string $name the key to set
808 * @param string $value the value to set (without magic quotes) - NULL will remove the flag
809 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
810 * @return bool
812 function set_cache_flag($type, $name, $value, $expiry=NULL) {
815 $timemodified = time();
816 if ($expiry===NULL || $expiry < $timemodified) {
817 $expiry = $timemodified + 24 * 60 * 60;
818 } else {
819 $expiry = (int)$expiry;
822 if ($value === NULL) {
823 return unset_cache_flag($type,$name);
826 $type = addslashes($type);
827 $name = addslashes($name);
828 if ($f = get_record('cache_flags', 'name', $name, 'flagtype', $type)) { // this is a potentail problem in DEBUG_DEVELOPER
829 if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
830 return true; //no need to update; helps rcache too
832 $f->value = addslashes($value);
833 $f->expiry = $expiry;
834 $f->timemodified = $timemodified;
835 return update_record('cache_flags', $f);
836 } else {
837 $f = new object();
838 $f->flagtype = $type;
839 $f->name = $name;
840 $f->value = addslashes($value);
841 $f->expiry = $expiry;
842 $f->timemodified = $timemodified;
843 return (bool)insert_record('cache_flags', $f);
848 * Removes a single volatile flag
850 * @param string $type the "type" namespace for the key
851 * @param string $name the key to set
852 * @uses $CFG
853 * @return bool
855 function unset_cache_flag($type, $name) {
857 return delete_records('cache_flags',
858 'name', addslashes($name),
859 'flagtype', addslashes($type));
863 * Garbage-collect volatile flags
866 function gc_cache_flags() {
867 return delete_records_select('cache_flags', 'expiry < ' . time());
871 * Refresh current $USER session global variable with all their current preferences.
872 * @uses $USER
874 function reload_user_preferences() {
876 global $USER;
878 //reset preference
879 $USER->preference = array();
881 if (!isloggedin() or isguestuser()) {
882 // no permanent storage for not-logged-in user and guest
884 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
885 foreach ($preferences as $preference) {
886 $USER->preference[$preference->name] = $preference->value;
890 return true;
894 * Sets a preference for the current user
895 * Optionally, can set a preference for a different user object
896 * @uses $USER
897 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
899 * @param string $name The key to set as preference for the specified user
900 * @param string $value The value to set forthe $name key in the specified user's record
901 * @param int $otheruserid A moodle user ID
902 * @return bool
904 function set_user_preference($name, $value, $otheruserid=NULL) {
906 global $USER;
908 if (!isset($USER->preference)) {
909 reload_user_preferences();
912 if (empty($name)) {
913 return false;
916 $nostore = false;
918 if (empty($otheruserid)){
919 if (!isloggedin() or isguestuser()) {
920 $nostore = true;
922 $userid = $USER->id;
923 } else {
924 if (isguestuser($otheruserid)) {
925 $nostore = true;
927 $userid = $otheruserid;
930 $return = true;
931 if ($nostore) {
932 // no permanent storage for not-logged-in user and guest
934 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
935 if ($preference->value === $value) {
936 return true;
938 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
939 $return = false;
942 } else {
943 $preference = new object();
944 $preference->userid = $userid;
945 $preference->name = addslashes($name);
946 $preference->value = addslashes((string)$value);
947 if (!insert_record('user_preferences', $preference)) {
948 $return = false;
952 // update value in USER session if needed
953 if ($userid == $USER->id) {
954 $USER->preference[$name] = (string)$value;
957 return $return;
961 * Unsets a preference completely by deleting it from the database
962 * Optionally, can set a preference for a different user id
963 * @uses $USER
964 * @param string $name The key to unset as preference for the specified user
965 * @param int $otheruserid A moodle user ID
967 function unset_user_preference($name, $otheruserid=NULL) {
969 global $USER;
971 if (!isset($USER->preference)) {
972 reload_user_preferences();
975 if (empty($otheruserid)){
976 $userid = $USER->id;
977 } else {
978 $userid = $otheruserid;
981 //Delete the preference from $USER if needed
982 if ($userid == $USER->id) {
983 unset($USER->preference[$name]);
986 //Then from DB
987 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
992 * Sets a whole array of preferences for the current user
993 * @param array $prefarray An array of key/value pairs to be set
994 * @param int $otheruserid A moodle user ID
995 * @return bool
997 function set_user_preferences($prefarray, $otheruserid=NULL) {
999 if (!is_array($prefarray) or empty($prefarray)) {
1000 return false;
1003 $return = true;
1004 foreach ($prefarray as $name => $value) {
1005 // The order is important; test for return is done first
1006 $return = (set_user_preference($name, $value, $otheruserid) && $return);
1008 return $return;
1012 * If no arguments are supplied this function will return
1013 * all of the current user preferences as an array.
1014 * If a name is specified then this function
1015 * attempts to return that particular preference value. If
1016 * none is found, then the optional value $default is returned,
1017 * otherwise NULL.
1018 * @param string $name Name of the key to use in finding a preference value
1019 * @param string $default Value to be returned if the $name key is not set in the user preferences
1020 * @param int $otheruserid A moodle user ID
1021 * @uses $USER
1022 * @return string
1024 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
1025 global $USER;
1027 if (!isset($USER->preference)) {
1028 reload_user_preferences();
1031 if (empty($otheruserid)){
1032 $userid = $USER->id;
1033 } else {
1034 $userid = $otheruserid;
1037 if ($userid == $USER->id) {
1038 $preference = $USER->preference;
1040 } else {
1041 $preference = array();
1042 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
1043 foreach ($prefdata as $pref) {
1044 $preference[$pref->name] = $pref->value;
1049 if (empty($name)) {
1050 return $preference; // All values
1052 } else if (array_key_exists($name, $preference)) {
1053 return $preference[$name]; // The single value
1055 } else {
1056 return $default; // Default value (or NULL)
1061 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
1064 * Given date parts in user time produce a GMT timestamp.
1066 * @param int $year The year part to create timestamp of
1067 * @param int $month The month part to create timestamp of
1068 * @param int $day The day part to create timestamp of
1069 * @param int $hour The hour part to create timestamp of
1070 * @param int $minute The minute part to create timestamp of
1071 * @param int $second The second part to create timestamp of
1072 * @param float $timezone ?
1073 * @param bool $applydst ?
1074 * @return int timestamp
1075 * @todo Finish documenting this function
1077 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1079 $strtimezone = NULL;
1080 if (!is_numeric($timezone)) {
1081 $strtimezone = $timezone;
1084 $timezone = get_user_timezone_offset($timezone);
1086 if (abs($timezone) > 13) {
1087 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1088 } else {
1089 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
1090 $time = usertime($time, $timezone);
1091 if($applydst) {
1092 $time -= dst_offset_on($time, $strtimezone);
1096 return $time;
1101 * Given an amount of time in seconds, returns string
1102 * formatted nicely as weeks, days, hours etc as needed
1104 * @uses MINSECS
1105 * @uses HOURSECS
1106 * @uses DAYSECS
1107 * @uses YEARSECS
1108 * @param int $totalsecs ?
1109 * @param array $str ?
1110 * @return string
1112 function format_time($totalsecs, $str=NULL) {
1114 $totalsecs = abs($totalsecs);
1116 if (!$str) { // Create the str structure the slow way
1117 $str->day = get_string('day');
1118 $str->days = get_string('days');
1119 $str->hour = get_string('hour');
1120 $str->hours = get_string('hours');
1121 $str->min = get_string('min');
1122 $str->mins = get_string('mins');
1123 $str->sec = get_string('sec');
1124 $str->secs = get_string('secs');
1125 $str->year = get_string('year');
1126 $str->years = get_string('years');
1130 $years = floor($totalsecs/YEARSECS);
1131 $remainder = $totalsecs - ($years*YEARSECS);
1132 $days = floor($remainder/DAYSECS);
1133 $remainder = $totalsecs - ($days*DAYSECS);
1134 $hours = floor($remainder/HOURSECS);
1135 $remainder = $remainder - ($hours*HOURSECS);
1136 $mins = floor($remainder/MINSECS);
1137 $secs = $remainder - ($mins*MINSECS);
1139 $ss = ($secs == 1) ? $str->sec : $str->secs;
1140 $sm = ($mins == 1) ? $str->min : $str->mins;
1141 $sh = ($hours == 1) ? $str->hour : $str->hours;
1142 $sd = ($days == 1) ? $str->day : $str->days;
1143 $sy = ($years == 1) ? $str->year : $str->years;
1145 $oyears = '';
1146 $odays = '';
1147 $ohours = '';
1148 $omins = '';
1149 $osecs = '';
1151 if ($years) $oyears = $years .' '. $sy;
1152 if ($days) $odays = $days .' '. $sd;
1153 if ($hours) $ohours = $hours .' '. $sh;
1154 if ($mins) $omins = $mins .' '. $sm;
1155 if ($secs) $osecs = $secs .' '. $ss;
1157 if ($years) return trim($oyears .' '. $odays);
1158 if ($days) return trim($odays .' '. $ohours);
1159 if ($hours) return trim($ohours .' '. $omins);
1160 if ($mins) return trim($omins .' '. $osecs);
1161 if ($secs) return $osecs;
1162 return get_string('now');
1166 * Returns a formatted string that represents a date in user time
1167 * <b>WARNING: note that the format is for strftime(), not date().</b>
1168 * Because of a bug in most Windows time libraries, we can't use
1169 * the nicer %e, so we have to use %d which has leading zeroes.
1170 * A lot of the fuss in the function is just getting rid of these leading
1171 * zeroes as efficiently as possible.
1173 * If parameter fixday = true (default), then take off leading
1174 * zero from %d, else mantain it.
1176 * @uses HOURSECS
1177 * @param int $date timestamp in GMT
1178 * @param string $format strftime format
1179 * @param float $timezone
1180 * @param bool $fixday If true (default) then the leading
1181 * zero from %d is removed. If false then the leading zero is mantained.
1182 * @return string
1184 function userdate($date, $format='', $timezone=99, $fixday = true) {
1186 global $CFG;
1188 $strtimezone = NULL;
1189 if (!is_numeric($timezone)) {
1190 $strtimezone = $timezone;
1193 if (empty($format)) {
1194 $format = get_string('strftimedaydatetime');
1197 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1198 $fixday = false;
1199 } else if ($fixday) {
1200 $formatnoday = str_replace('%d', 'DD', $format);
1201 $fixday = ($formatnoday != $format);
1204 $date += dst_offset_on($date, $strtimezone);
1206 $timezone = get_user_timezone_offset($timezone);
1208 if (abs($timezone) > 13) { /// Server time
1209 if ($fixday) {
1210 $datestring = strftime($formatnoday, $date);
1211 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1212 $datestring = str_replace('DD', $daystring, $datestring);
1213 } else {
1214 $datestring = strftime($format, $date);
1216 } else {
1217 $date += (int)($timezone * 3600);
1218 if ($fixday) {
1219 $datestring = gmstrftime($formatnoday, $date);
1220 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1221 $datestring = str_replace('DD', $daystring, $datestring);
1222 } else {
1223 $datestring = gmstrftime($format, $date);
1227 /// If we are running under Windows convert from windows encoding to UTF-8
1228 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1230 if ($CFG->ostype == 'WINDOWS') {
1231 if ($localewincharset = get_string('localewincharset')) {
1232 $textlib = textlib_get_instance();
1233 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1237 return $datestring;
1241 * Given a $time timestamp in GMT (seconds since epoch),
1242 * returns an array that represents the date in user time
1244 * @uses HOURSECS
1245 * @param int $time Timestamp in GMT
1246 * @param float $timezone ?
1247 * @return array An array that represents the date in user time
1248 * @todo Finish documenting this function
1250 function usergetdate($time, $timezone=99) {
1252 $strtimezone = NULL;
1253 if (!is_numeric($timezone)) {
1254 $strtimezone = $timezone;
1257 $timezone = get_user_timezone_offset($timezone);
1259 if (abs($timezone) > 13) { // Server time
1260 return getdate($time);
1263 // There is no gmgetdate so we use gmdate instead
1264 $time += dst_offset_on($time, $strtimezone);
1265 $time += intval((float)$timezone * HOURSECS);
1267 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1269 list(
1270 $getdate['seconds'],
1271 $getdate['minutes'],
1272 $getdate['hours'],
1273 $getdate['mday'],
1274 $getdate['mon'],
1275 $getdate['year'],
1276 $getdate['wday'],
1277 $getdate['yday'],
1278 $getdate['weekday'],
1279 $getdate['month']
1280 ) = explode('_', $datestring);
1282 return $getdate;
1286 * Given a GMT timestamp (seconds since epoch), offsets it by
1287 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1289 * @uses HOURSECS
1290 * @param int $date Timestamp in GMT
1291 * @param float $timezone
1292 * @return int
1294 function usertime($date, $timezone=99) {
1296 $timezone = get_user_timezone_offset($timezone);
1298 if (abs($timezone) > 13) {
1299 return $date;
1301 return $date - (int)($timezone * HOURSECS);
1305 * Given a time, return the GMT timestamp of the most recent midnight
1306 * for the current user.
1308 * @param int $date Timestamp in GMT
1309 * @param float $timezone ?
1310 * @return ?
1312 function usergetmidnight($date, $timezone=99) {
1314 $userdate = usergetdate($date, $timezone);
1316 // Time of midnight of this user's day, in GMT
1317 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1322 * Returns a string that prints the user's timezone
1324 * @param float $timezone The user's timezone
1325 * @return string
1327 function usertimezone($timezone=99) {
1329 $tz = get_user_timezone($timezone);
1331 if (!is_float($tz)) {
1332 return $tz;
1335 if(abs($tz) > 13) { // Server time
1336 return get_string('serverlocaltime');
1339 if($tz == intval($tz)) {
1340 // Don't show .0 for whole hours
1341 $tz = intval($tz);
1344 if($tz == 0) {
1345 return 'UTC';
1347 else if($tz > 0) {
1348 return 'UTC+'.$tz;
1350 else {
1351 return 'UTC'.$tz;
1357 * Returns a float which represents the user's timezone difference from GMT in hours
1358 * Checks various settings and picks the most dominant of those which have a value
1360 * @uses $CFG
1361 * @uses $USER
1362 * @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
1363 * @return int
1365 function get_user_timezone_offset($tz = 99) {
1367 global $USER, $CFG;
1369 $tz = get_user_timezone($tz);
1371 if (is_float($tz)) {
1372 return $tz;
1373 } else {
1374 $tzrecord = get_timezone_record($tz);
1375 if (empty($tzrecord)) {
1376 return 99.0;
1378 return (float)$tzrecord->gmtoff / HOURMINS;
1383 * Returns an int which represents the systems's timezone difference from GMT in seconds
1384 * @param mixed $tz timezone
1385 * @return int if found, false is timezone 99 or error
1387 function get_timezone_offset($tz) {
1388 global $CFG;
1390 if ($tz == 99) {
1391 return false;
1394 if (is_numeric($tz)) {
1395 return intval($tz * 60*60);
1398 if (!$tzrecord = get_timezone_record($tz)) {
1399 return false;
1401 return intval($tzrecord->gmtoff * 60);
1405 * Returns a float or a string which denotes the user's timezone
1406 * 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)
1407 * means that for this timezone there are also DST rules to be taken into account
1408 * Checks various settings and picks the most dominant of those which have a value
1410 * @uses $USER
1411 * @uses $CFG
1412 * @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
1413 * @return mixed
1415 function get_user_timezone($tz = 99) {
1416 global $USER, $CFG;
1418 $timezones = array(
1419 $tz,
1420 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1421 isset($USER->timezone) ? $USER->timezone : 99,
1422 isset($CFG->timezone) ? $CFG->timezone : 99,
1425 $tz = 99;
1427 while(($tz == '' || $tz == 99 || $tz == NULL) && $next = each($timezones)) {
1428 $tz = $next['value'];
1431 return is_numeric($tz) ? (float) $tz : $tz;
1437 * @uses $CFG
1438 * @uses $db
1439 * @param string $timezonename ?
1440 * @return object
1442 function get_timezone_record($timezonename) {
1443 global $CFG, $db;
1444 static $cache = NULL;
1446 if ($cache === NULL) {
1447 $cache = array();
1450 if (isset($cache[$timezonename])) {
1451 return $cache[$timezonename];
1454 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1455 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1461 * @uses $CFG
1462 * @uses $USER
1463 * @param ? $fromyear ?
1464 * @param ? $to_year ?
1465 * @return bool
1467 function calculate_user_dst_table($from_year = NULL, $to_year = NULL, $strtimezone = NULL) {
1468 global $CFG, $SESSION;
1470 $usertz = get_user_timezone($strtimezone);
1472 if (is_float($usertz)) {
1473 // Trivial timezone, no DST
1474 return false;
1477 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1478 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1479 unset($SESSION->dst_offsets);
1480 unset($SESSION->dst_range);
1483 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1484 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1485 // This will be the return path most of the time, pretty light computationally
1486 return true;
1489 // Reaching here means we either need to extend our table or create it from scratch
1491 // Remember which TZ we calculated these changes for
1492 $SESSION->dst_offsettz = $usertz;
1494 if(empty($SESSION->dst_offsets)) {
1495 // If we 're creating from scratch, put the two guard elements in there
1496 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1498 if(empty($SESSION->dst_range)) {
1499 // If creating from scratch
1500 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1501 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1503 // Fill in the array with the extra years we need to process
1504 $yearstoprocess = array();
1505 for($i = $from; $i <= $to; ++$i) {
1506 $yearstoprocess[] = $i;
1509 // Take note of which years we have processed for future calls
1510 $SESSION->dst_range = array($from, $to);
1512 else {
1513 // If needing to extend the table, do the same
1514 $yearstoprocess = array();
1516 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1517 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1519 if($from < $SESSION->dst_range[0]) {
1520 // Take note of which years we need to process and then note that we have processed them for future calls
1521 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1522 $yearstoprocess[] = $i;
1524 $SESSION->dst_range[0] = $from;
1526 if($to > $SESSION->dst_range[1]) {
1527 // Take note of which years we need to process and then note that we have processed them for future calls
1528 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1529 $yearstoprocess[] = $i;
1531 $SESSION->dst_range[1] = $to;
1535 if(empty($yearstoprocess)) {
1536 // This means that there was a call requesting a SMALLER range than we have already calculated
1537 return true;
1540 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1541 // Also, the array is sorted in descending timestamp order!
1543 // Get DB data
1545 static $presets_cache = array();
1546 if (!isset($presets_cache[$usertz])) {
1547 $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');
1549 if(empty($presets_cache[$usertz])) {
1550 return false;
1553 // Remove ending guard (first element of the array)
1554 reset($SESSION->dst_offsets);
1555 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1557 // Add all required change timestamps
1558 foreach($yearstoprocess as $y) {
1559 // Find the record which is in effect for the year $y
1560 foreach($presets_cache[$usertz] as $year => $preset) {
1561 if($year <= $y) {
1562 break;
1566 $changes = dst_changes_for_year($y, $preset);
1568 if($changes === NULL) {
1569 continue;
1571 if($changes['dst'] != 0) {
1572 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1574 if($changes['std'] != 0) {
1575 $SESSION->dst_offsets[$changes['std']] = 0;
1579 // Put in a guard element at the top
1580 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1581 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1583 // Sort again
1584 krsort($SESSION->dst_offsets);
1586 return true;
1589 function dst_changes_for_year($year, $timezone) {
1591 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1592 return NULL;
1595 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1596 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1598 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1599 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1601 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1602 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1604 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1605 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1606 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1608 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1609 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1611 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1614 // $time must NOT be compensated at all, it has to be a pure timestamp
1615 function dst_offset_on($time, $strtimezone = NULL) {
1616 global $SESSION;
1618 if(!calculate_user_dst_table(NULL, NULL, $strtimezone) || empty($SESSION->dst_offsets)) {
1619 return 0;
1622 reset($SESSION->dst_offsets);
1623 while(list($from, $offset) = each($SESSION->dst_offsets)) {
1624 if($from <= $time) {
1625 break;
1629 // This is the normal return path
1630 if($offset !== NULL) {
1631 return $offset;
1634 // Reaching this point means we haven't calculated far enough, do it now:
1635 // Calculate extra DST changes if needed and recurse. The recursion always
1636 // moves toward the stopping condition, so will always end.
1638 if($from == 0) {
1639 // We need a year smaller than $SESSION->dst_range[0]
1640 if($SESSION->dst_range[0] == 1971) {
1641 return 0;
1643 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL, $strtimezone);
1644 return dst_offset_on($time, $strtimezone);
1646 else {
1647 // We need a year larger than $SESSION->dst_range[1]
1648 if($SESSION->dst_range[1] == 2035) {
1649 return 0;
1651 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5, $strtimezone);
1652 return dst_offset_on($time, $strtimezone);
1656 function find_day_in_month($startday, $weekday, $month, $year) {
1658 $daysinmonth = days_in_month($month, $year);
1660 if($weekday == -1) {
1661 // Don't care about weekday, so return:
1662 // abs($startday) if $startday != -1
1663 // $daysinmonth otherwise
1664 return ($startday == -1) ? $daysinmonth : abs($startday);
1667 // From now on we 're looking for a specific weekday
1669 // Give "end of month" its actual value, since we know it
1670 if($startday == -1) {
1671 $startday = -1 * $daysinmonth;
1674 // Starting from day $startday, the sign is the direction
1676 if($startday < 1) {
1678 $startday = abs($startday);
1679 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1681 // This is the last such weekday of the month
1682 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1683 if($lastinmonth > $daysinmonth) {
1684 $lastinmonth -= 7;
1687 // Find the first such weekday <= $startday
1688 while($lastinmonth > $startday) {
1689 $lastinmonth -= 7;
1692 return $lastinmonth;
1695 else {
1697 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1699 $diff = $weekday - $indexweekday;
1700 if($diff < 0) {
1701 $diff += 7;
1704 // This is the first such weekday of the month equal to or after $startday
1705 $firstfromindex = $startday + $diff;
1707 return $firstfromindex;
1713 * Calculate the number of days in a given month
1715 * @param int $month The month whose day count is sought
1716 * @param int $year The year of the month whose day count is sought
1717 * @return int
1719 function days_in_month($month, $year) {
1720 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1724 * Calculate the position in the week of a specific calendar day
1726 * @param int $day The day of the date whose position in the week is sought
1727 * @param int $month The month of the date whose position in the week is sought
1728 * @param int $year The year of the date whose position in the week is sought
1729 * @return int
1731 function dayofweek($day, $month, $year) {
1732 // I wonder if this is any different from
1733 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1734 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1737 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1740 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1741 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1742 * sesskey string if $USER exists, or boolean false if not.
1744 * @uses $USER
1745 * @return string
1747 function sesskey() {
1748 global $USER;
1750 if(!isset($USER)) {
1751 return false;
1754 if (empty($USER->sesskey)) {
1755 $USER->sesskey = random_string(10);
1758 return $USER->sesskey;
1763 * For security purposes, this function will check that the currently
1764 * given sesskey (passed as a parameter to the script or this function)
1765 * matches that of the current user.
1767 * @param string $sesskey optionally provided sesskey
1768 * @return bool
1770 function confirm_sesskey($sesskey=NULL) {
1771 global $USER;
1773 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1774 return true;
1777 if (empty($sesskey)) {
1778 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
1781 if (!isset($USER->sesskey)) {
1782 return false;
1785 return ($USER->sesskey === $sesskey);
1789 * Setup all global $CFG course variables, set locale and also themes
1790 * This function can be used on pages that do not require login instead of require_login()
1792 * @param mixed $courseorid id of the course or course object
1794 function course_setup($courseorid=0) {
1795 global $COURSE, $CFG, $SITE;
1797 /// Redefine global $COURSE if needed
1798 if (empty($courseorid)) {
1799 // no change in global $COURSE - for backwards compatibiltiy
1800 // if require_rogin() used after require_login($courseid);
1801 } else if (is_object($courseorid)) {
1802 $COURSE = clone($courseorid);
1803 } else {
1804 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1805 if ($courseorid == SITEID) {
1806 $COURSE = clone($SITE);
1807 } else if (!empty($course->id) and $course->id == $courseorid) {
1808 $COURSE = clone($course);
1809 } else {
1810 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1811 error('Invalid course ID');
1816 /// set locale and themes
1817 moodle_setlocale();
1818 theme_setup();
1823 * This function checks that the current user is logged in and has the
1824 * required privileges
1826 * This function checks that the current user is logged in, and optionally
1827 * whether they are allowed to be in a particular course and view a particular
1828 * course module.
1829 * If they are not logged in, then it redirects them to the site login unless
1830 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1831 * case they are automatically logged in as guests.
1832 * If $courseid is given and the user is not enrolled in that course then the
1833 * user is redirected to the course enrolment page.
1834 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1835 * in the course then the user is redirected to the course home page.
1837 * @uses $CFG
1838 * @uses $SESSION
1839 * @uses $USER
1840 * @uses $FULLME
1841 * @uses SITEID
1842 * @uses $COURSE
1843 * @param mixed $courseorid id of the course or course object
1844 * @param bool $autologinguest
1845 * @param object $cm course module object
1846 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
1847 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
1848 * in order to keep redirects working properly. MDL-14495
1850 function require_login($courseorid=0, $autologinguest=true, $cm=null, $setwantsurltome=true) {
1852 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1854 /// setup global $COURSE, themes, language and locale
1855 course_setup($courseorid);
1857 /// If the user is not even logged in yet then make sure they are
1858 if (!isloggedin()) {
1859 //NOTE: $USER->site check was obsoleted by session test cookie,
1860 // $USER->confirmed test is in login/index.php
1861 if ($setwantsurltome) {
1862 $SESSION->wantsurl = $FULLME;
1864 if (!empty($_SERVER['HTTP_REFERER'])) {
1865 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
1867 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
1868 $loginguest = '?loginguest=true';
1869 } else {
1870 $loginguest = '';
1872 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
1873 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
1874 } else {
1875 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1876 redirect($wwwroot .'/login/index.php');
1878 exit;
1881 /// loginas as redirection if needed
1882 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1883 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1884 if ($USER->loginascontext->instanceid != $COURSE->id) {
1885 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
1890 /// check whether the user should be changing password (but only if it is REALLY them)
1891 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
1892 $userauth = get_auth_plugin($USER->auth);
1893 if ($userauth->can_change_password()) {
1894 $SESSION->wantsurl = $FULLME;
1895 if ($changeurl = $userauth->change_password_url()) {
1896 //use plugin custom url
1897 redirect($changeurl);
1898 } else {
1899 //use moodle internal method
1900 if (empty($CFG->loginhttps)) {
1901 redirect($CFG->wwwroot .'/login/change_password.php');
1902 } else {
1903 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1904 redirect($wwwroot .'/login/change_password.php');
1907 } else {
1908 print_error('nopasswordchangeforced', 'auth');
1912 /// Check that the user account is properly set up
1913 if (user_not_fully_set_up($USER)) {
1914 $SESSION->wantsurl = $FULLME;
1915 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
1918 /// Make sure current IP matches the one for this session (if required)
1919 if (!empty($CFG->tracksessionip)) {
1920 if ($USER->sessionIP != md5(getremoteaddr())) {
1921 print_error('sessionipnomatch', 'error');
1925 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1926 sesskey();
1928 // Check that the user has agreed to a site policy if there is one
1929 if (!empty($CFG->sitepolicy)) {
1930 if (!$USER->policyagreed) {
1931 $SESSION->wantsurl = $FULLME;
1932 redirect($CFG->wwwroot .'/user/policy.php');
1936 // Fetch the system context, we are going to use it a lot.
1937 $sysctx = get_context_instance(CONTEXT_SYSTEM);
1939 /// If the site is currently under maintenance, then print a message
1940 if (!has_capability('moodle/site:config', $sysctx)) {
1941 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1942 print_maintenance_message();
1943 exit;
1947 /// groupmembersonly access control
1948 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1949 if (isguestuser() or !groups_has_membership($cm)) {
1950 print_error('groupmembersonlyerror', 'group', $CFG->wwwroot.'/course/view.php?id='.$cm->course);
1954 // Fetch the course context, and prefetch its child contexts
1955 if (!isset($COURSE->context)) {
1956 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
1957 print_error('nocontext');
1960 if ($COURSE->id == SITEID) {
1961 /// Eliminate hidden site activities straight away
1962 if (!empty($cm) && !$cm->visible
1963 && !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
1964 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
1966 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1967 return;
1969 } else {
1971 /// Check if the user can be in a particular course
1972 if (empty($USER->access['rsw'][$COURSE->context->path])) {
1974 // MDL-13900 - If the course or the parent category are hidden
1975 // and the user hasn't the 'course:viewhiddencourses' capability, prevent access
1977 if ( !($COURSE->visible && course_parent_visible($COURSE)) &&
1978 !has_capability('moodle/course:viewhiddencourses', $COURSE->context)) {
1979 print_header_simple();
1980 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1984 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1986 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
1987 if ($COURSE->guest == 1) {
1988 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1989 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
1993 /// If the user is a guest then treat them according to the course policy about guests
1995 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
1996 if (has_capability('moodle/site:doanything', $sysctx)) {
1997 // administrators must be able to access any course - even if somebody gives them guest access
1998 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
1999 return;
2002 switch ($COURSE->guest) { /// Check course policy about guest access
2004 case 1: /// Guests always allowed
2005 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
2006 print_header_simple();
2007 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
2009 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
2010 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
2011 get_string('activityiscurrentlyhidden'));
2014 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2015 return; // User is allowed to see this course
2017 break;
2019 case 2: /// Guests allowed with key
2020 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
2021 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2022 return true;
2024 // otherwise drop through to logic below (--> enrol.php)
2025 break;
2027 default: /// Guests not allowed
2028 $strloggedinasguest = get_string('loggedinasguest');
2029 print_header_simple('', '',
2030 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
2031 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
2032 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
2033 } else {
2034 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
2035 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
2036 print_footer($COURSE);
2037 exit;
2039 break;
2042 /// For non-guests, check if they have course view access
2044 } else if (has_capability('moodle/course:view', $COURSE->context)) {
2045 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
2046 if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
2047 print_header_simple();
2048 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2052 /// Make sure they can read this activity too, if specified
2054 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
2055 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
2057 user_accesstime_log($COURSE->id); /// Access granted, update lastaccess times
2058 return; // User is allowed to see this course
2063 /// Currently not enrolled in the course, so see if they want to enrol
2064 $SESSION->wantsurl = $FULLME;
2065 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
2066 die;
2073 * This function just makes sure a user is logged out.
2075 * @uses $CFG
2076 * @uses $USER
2078 function require_logout() {
2080 global $USER, $CFG, $SESSION;
2082 if (isloggedin()) {
2083 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
2085 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
2086 foreach($authsequence as $authname) {
2087 $authplugin = get_auth_plugin($authname);
2088 $authplugin->prelogout_hook();
2092 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
2093 // This method is just to try to avoid silly warnings from PHP 4.3.0
2094 session_unregister("USER");
2095 session_unregister("SESSION");
2098 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
2099 $file = $line = null;
2100 if (headers_sent($file, $line)) {
2101 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
2102 error_log('Headers were already sent in file: '.$file.' on line '.$line);
2103 } else {
2104 if (check_php_version('5.2.0')) {
2105 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
2106 } else {
2107 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
2111 unset($_SESSION['USER']);
2112 unset($_SESSION['SESSION']);
2114 unset($SESSION);
2115 unset($USER);
2120 * This is a weaker version of {@link require_login()} which only requires login
2121 * when called from within a course rather than the site page, unless
2122 * the forcelogin option is turned on.
2124 * @uses $CFG
2125 * @param mixed $courseorid The course object or id in question
2126 * @param bool $autologinguest Allow autologin guests if that is wanted
2127 * @param object $cm Course activity module if known
2128 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2129 * true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2130 * in order to keep redirects working properly. MDL-14495
2132 function require_course_login($courseorid, $autologinguest=true, $cm=null, $setwantsurltome=true) {
2133 global $CFG;
2134 if (!empty($CFG->forcelogin)) {
2135 // login required for both SITE and courses
2136 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2138 } else if (!empty($cm) and !$cm->visible) {
2139 // always login for hidden activities
2140 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2142 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
2143 or (!is_object($courseorid) and $courseorid == SITEID)) {
2144 //login for SITE not required
2145 user_accesstime_log(SITEID);
2146 return;
2148 } else {
2149 // course login always required
2150 require_login($courseorid, $autologinguest, $cm, $setwantsurltome);
2155 * Require key login. Function terminates with error if key not found or incorrect.
2156 * @param string $script unique script identifier
2157 * @param int $instance optional instance id
2159 function require_user_key_login($script, $instance=null) {
2160 global $nomoodlecookie, $USER, $SESSION, $CFG;
2162 if (empty($nomoodlecookie)) {
2163 error('Incorrect use of require_key_login() - session cookies must be disabled!');
2166 /// extra safety
2167 @session_write_close();
2169 $keyvalue = required_param('key', PARAM_ALPHANUM);
2171 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
2172 error('Incorrect key');
2175 if (!empty($key->validuntil) and $key->validuntil < time()) {
2176 error('Expired key');
2179 if ($key->iprestriction) {
2180 $remoteaddr = getremoteaddr();
2181 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2182 error('Client IP address mismatch');
2186 if (!$user = get_record('user', 'id', $key->userid)) {
2187 error('Incorrect user record');
2190 /// emulate normal session
2191 $SESSION = new object();
2192 $USER = $user;
2194 /// note we are not using normal login
2195 if (!defined('USER_KEY_LOGIN')) {
2196 define('USER_KEY_LOGIN', true);
2199 load_all_capabilities();
2201 /// return isntance id - it might be empty
2202 return $key->instance;
2206 * Creates a new private user access key.
2207 * @param string $script unique target identifier
2208 * @param int $userid
2209 * @param instance $int optional instance id
2210 * @param string $iprestriction optional ip restricted access
2211 * @param timestamp $validuntil key valid only until given data
2212 * @return string access key value
2214 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2215 $key = new object();
2216 $key->script = $script;
2217 $key->userid = $userid;
2218 $key->instance = $instance;
2219 $key->iprestriction = $iprestriction;
2220 $key->validuntil = $validuntil;
2221 $key->timecreated = time();
2223 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2224 while (record_exists('user_private_key', 'value', $key->value)) {
2225 // must be unique
2226 $key->value = md5($userid.'_'.time().random_string(40));
2229 if (!insert_record('user_private_key', $key)) {
2230 error('Can not insert new key');
2233 return $key->value;
2237 * Modify the user table by setting the currently logged in user's
2238 * last login to now.
2240 * @uses $USER
2241 * @return bool
2243 function update_user_login_times() {
2244 global $USER;
2246 $user = new object();
2247 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2248 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2250 $user->id = $USER->id;
2252 return update_record('user', $user);
2256 * Determines if a user has completed setting up their account.
2258 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
2259 * @return bool
2261 function user_not_fully_set_up($user) {
2262 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2265 function over_bounce_threshold($user) {
2267 global $CFG;
2269 if (empty($CFG->handlebounces)) {
2270 return false;
2272 // set sensible defaults
2273 if (empty($CFG->minbounces)) {
2274 $CFG->minbounces = 10;
2276 if (empty($CFG->bounceratio)) {
2277 $CFG->bounceratio = .20;
2279 $bouncecount = 0;
2280 $sendcount = 0;
2281 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2282 $bouncecount = $bounce->value;
2284 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2285 $sendcount = $send->value;
2287 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2291 * @param $user - object containing an id
2292 * @param $reset - will reset the count to 0
2294 function set_send_count($user,$reset=false) {
2295 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2296 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2297 update_record('user_preferences',$pref);
2299 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2300 // make a new one
2301 $pref->name = 'email_send_count';
2302 $pref->value = 1;
2303 $pref->userid = $user->id;
2304 insert_record('user_preferences',$pref, false);
2309 * @param $user - object containing an id
2310 * @param $reset - will reset the count to 0
2312 function set_bounce_count($user,$reset=false) {
2313 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2314 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2315 update_record('user_preferences',$pref);
2317 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2318 // make a new one
2319 $pref->name = 'email_bounce_count';
2320 $pref->value = 1;
2321 $pref->userid = $user->id;
2322 insert_record('user_preferences',$pref, false);
2327 * Keeps track of login attempts
2329 * @uses $SESSION
2331 function update_login_count() {
2333 global $SESSION;
2335 $max_logins = 10;
2337 if (empty($SESSION->logincount)) {
2338 $SESSION->logincount = 1;
2339 } else {
2340 $SESSION->logincount++;
2343 if ($SESSION->logincount > $max_logins) {
2344 unset($SESSION->wantsurl);
2345 print_error('errortoomanylogins');
2350 * Resets login attempts
2352 * @uses $SESSION
2354 function reset_login_count() {
2355 global $SESSION;
2357 $SESSION->logincount = 0;
2360 function sync_metacourses() {
2362 global $CFG;
2364 if (!$courses = get_records('course', 'metacourse', 1)) {
2365 return;
2368 foreach ($courses as $course) {
2369 sync_metacourse($course);
2374 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2376 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2378 function sync_metacourse($course) {
2379 global $CFG;
2381 // Check the course is valid.
2382 if (!is_object($course)) {
2383 if (!$course = get_record('course', 'id', $course)) {
2384 return false; // invalid course id
2388 // Check that we actually have a metacourse.
2389 if (empty($course->metacourse)) {
2390 return false;
2393 // Get a list of roles that should not be synced.
2394 if (!empty($CFG->nonmetacoursesyncroleids)) {
2395 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2396 } else {
2397 $roleexclusions = '';
2400 // Get the context of the metacourse.
2401 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2403 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2404 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2405 $managers = array_keys($users);
2406 } else {
2407 $managers = array();
2410 // Get assignments of a user to a role that exist in a child course, but
2411 // not in the meta coure. That is, get a list of the assignments that need to be made.
2412 if (!$assignments = get_records_sql("
2413 SELECT
2414 ra.id, ra.roleid, ra.userid
2415 FROM
2416 {$CFG->prefix}role_assignments ra,
2417 {$CFG->prefix}context con,
2418 {$CFG->prefix}course_meta cm
2419 WHERE
2420 ra.contextid = con.id AND
2421 con.contextlevel = " . CONTEXT_COURSE . " AND
2422 con.instanceid = cm.child_course AND
2423 cm.parent_course = {$course->id} AND
2424 $roleexclusions
2425 NOT EXISTS (
2426 SELECT 1 FROM
2427 {$CFG->prefix}role_assignments ra2
2428 WHERE
2429 ra2.userid = ra.userid AND
2430 ra2.roleid = ra.roleid AND
2431 ra2.contextid = {$context->id}
2433 ")) {
2434 $assignments = array();
2437 // Get assignments of a user to a role that exist in the meta course, but
2438 // not in any child courses. That is, get a list of the unassignments that need to be made.
2439 if (!$unassignments = get_records_sql("
2440 SELECT
2441 ra.id, ra.roleid, ra.userid
2442 FROM
2443 {$CFG->prefix}role_assignments ra
2444 WHERE
2445 ra.contextid = {$context->id} AND
2446 $roleexclusions
2447 NOT EXISTS (
2448 SELECT 1 FROM
2449 {$CFG->prefix}role_assignments ra2,
2450 {$CFG->prefix}context con2,
2451 {$CFG->prefix}course_meta cm
2452 WHERE
2453 ra2.userid = ra.userid AND
2454 ra2.roleid = ra.roleid AND
2455 ra2.contextid = con2.id AND
2456 con2.contextlevel = " . CONTEXT_COURSE . " AND
2457 con2.instanceid = cm.child_course AND
2458 cm.parent_course = {$course->id}
2460 ")) {
2461 $unassignments = array();
2464 $success = true;
2466 // Make the unassignments, if they are not managers.
2467 foreach ($unassignments as $unassignment) {
2468 if (!in_array($unassignment->userid, $managers)) {
2469 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
2473 // Make the assignments.
2474 foreach ($assignments as $assignment) {
2475 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
2478 return $success;
2480 // TODO: finish timeend and timestart
2481 // maybe we could rely on cron job to do the cleaning from time to time
2485 * Adds a record to the metacourse table and calls sync_metacoures
2487 function add_to_metacourse ($metacourseid, $courseid) {
2489 if (!$metacourse = get_record("course","id",$metacourseid)) {
2490 return false;
2493 if (!$course = get_record("course","id",$courseid)) {
2494 return false;
2497 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2498 $rec = new object();
2499 $rec->parent_course = $metacourseid;
2500 $rec->child_course = $courseid;
2501 if (!insert_record('course_meta',$rec)) {
2502 return false;
2504 return sync_metacourse($metacourseid);
2506 return true;
2511 * Removes the record from the metacourse table and calls sync_metacourse
2513 function remove_from_metacourse($metacourseid, $courseid) {
2515 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2516 return sync_metacourse($metacourseid);
2518 return false;
2523 * Determines if a user is currently logged in
2525 * @uses $USER
2526 * @return bool
2528 function isloggedin() {
2529 global $USER;
2531 return (!empty($USER->id));
2535 * Determines if a user is logged in as real guest user with username 'guest'.
2536 * This function is similar to original isguest() in 1.6 and earlier.
2537 * Current isguest() is deprecated - do not use it anymore.
2539 * @param $user mixed user object or id, $USER if not specified
2540 * @return bool true if user is the real guest user, false if not logged in or other user
2542 function isguestuser($user=NULL) {
2543 global $USER;
2544 if ($user === NULL) {
2545 $user = $USER;
2546 } else if (is_numeric($user)) {
2547 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2550 if (empty($user->id)) {
2551 return false; // not logged in, can not be guest
2554 return ($user->username == 'guest');
2558 * Determines if the currently logged in user is in editing mode.
2559 * Note: originally this function had $userid parameter - it was not usable anyway
2561 * @uses $USER, $PAGE
2562 * @return bool
2564 function isediting() {
2565 global $USER, $PAGE;
2567 if (empty($USER->editing)) {
2568 return false;
2569 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2570 return $PAGE->user_allowed_editing();
2572 return true;//false;
2576 * Determines if the logged in user is currently moving an activity
2578 * @uses $USER
2579 * @param int $courseid The id of the course being tested
2580 * @return bool
2582 function ismoving($courseid) {
2583 global $USER;
2585 if (!empty($USER->activitycopy)) {
2586 return ($USER->activitycopycourse == $courseid);
2588 return false;
2592 * Given an object containing firstname and lastname
2593 * values, this function returns a string with the
2594 * full name of the person.
2595 * The result may depend on system settings
2596 * or language. 'override' will force both names
2597 * to be used even if system settings specify one.
2599 * @uses $CFG
2600 * @uses $SESSION
2601 * @param object $user A {@link $USER} object to get full name of
2602 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2604 function fullname($user, $override=false) {
2606 global $CFG, $SESSION;
2608 if (!isset($user->firstname) and !isset($user->lastname)) {
2609 return '';
2612 if (!$override) {
2613 if (!empty($CFG->forcefirstname)) {
2614 $user->firstname = $CFG->forcefirstname;
2616 if (!empty($CFG->forcelastname)) {
2617 $user->lastname = $CFG->forcelastname;
2621 if (!empty($SESSION->fullnamedisplay)) {
2622 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2625 if ($CFG->fullnamedisplay == 'firstname lastname') {
2626 return $user->firstname .' '. $user->lastname;
2628 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
2629 return $user->lastname .' '. $user->firstname;
2631 } else if ($CFG->fullnamedisplay == 'firstname') {
2632 if ($override) {
2633 return get_string('fullnamedisplay', '', $user);
2634 } else {
2635 return $user->firstname;
2639 return get_string('fullnamedisplay', '', $user);
2643 * Sets a moodle cookie with an encrypted string
2645 * @uses $CFG
2646 * @uses DAYSECS
2647 * @uses HOURSECS
2648 * @param string $thing The string to encrypt and place in a cookie
2650 function set_moodle_cookie($thing) {
2651 global $CFG;
2653 if ($thing == 'guest') { // Ignore guest account
2654 return;
2657 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2659 $days = 60;
2660 $seconds = DAYSECS*$days;
2662 // no need to set secure or http cookie only here - it is not secret
2663 setCookie($cookiename, '', time() - HOURSECS, $CFG->sessioncookiepath);
2664 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, $CFG->sessioncookiepath);
2668 * Gets a moodle cookie with an encrypted string
2670 * @uses $CFG
2671 * @return string
2673 function get_moodle_cookie() {
2674 global $CFG;
2676 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2678 if (empty($_COOKIE[$cookiename])) {
2679 return '';
2680 } else {
2681 $thing = rc4decrypt($_COOKIE[$cookiename]);
2682 return ($thing == 'guest') ? '': $thing; // Ignore guest account
2687 * Returns whether a given authentication plugin exists.
2689 * @uses $CFG
2690 * @param string $auth Form of authentication to check for. Defaults to the
2691 * global setting in {@link $CFG}.
2692 * @return boolean Whether the plugin is available.
2694 function exists_auth_plugin($auth) {
2695 global $CFG;
2697 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2698 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2700 return false;
2704 * Checks if a given plugin is in the list of enabled authentication plugins.
2706 * @param string $auth Authentication plugin.
2707 * @return boolean Whether the plugin is enabled.
2709 function is_enabled_auth($auth) {
2710 if (empty($auth)) {
2711 return false;
2714 $enabled = get_enabled_auth_plugins();
2716 return in_array($auth, $enabled);
2720 * Returns an authentication plugin instance.
2722 * @uses $CFG
2723 * @param string $auth name of authentication plugin
2724 * @return object An instance of the required authentication plugin.
2726 function get_auth_plugin($auth) {
2727 global $CFG;
2729 // check the plugin exists first
2730 if (! exists_auth_plugin($auth)) {
2731 error("Authentication plugin '$auth' not found.");
2734 // return auth plugin instance
2735 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2736 $class = "auth_plugin_$auth";
2737 return new $class;
2741 * Returns array of active auth plugins.
2743 * @param bool $fix fix $CFG->auth if needed
2744 * @return array
2746 function get_enabled_auth_plugins($fix=false) {
2747 global $CFG;
2749 $default = array('manual', 'nologin');
2751 if (empty($CFG->auth)) {
2752 $auths = array();
2753 } else {
2754 $auths = explode(',', $CFG->auth);
2757 if ($fix) {
2758 $auths = array_unique($auths);
2759 foreach($auths as $k=>$authname) {
2760 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2761 unset($auths[$k]);
2764 $newconfig = implode(',', $auths);
2765 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2766 set_config('auth', $newconfig);
2770 return (array_merge($default, $auths));
2774 * Returns true if an internal authentication method is being used.
2775 * if method not specified then, global default is assumed
2777 * @uses $CFG
2778 * @param string $auth Form of authentication required
2779 * @return bool
2781 function is_internal_auth($auth) {
2782 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2783 return $authplugin->is_internal();
2787 * Returns an array of user fields
2789 * @uses $CFG
2790 * @uses $db
2791 * @return array User field/column names
2793 function get_user_fieldnames() {
2795 global $CFG, $db;
2797 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2798 unset($fieldarray['ID']);
2800 return $fieldarray;
2804 * Creates the default "guest" user. Used both from
2805 * admin/index.php and login/index.php
2806 * @return mixed user object created or boolean false if the creation has failed
2808 function create_guest_record() {
2810 global $CFG;
2812 $guest = new stdClass();
2813 $guest->auth = 'manual';
2814 $guest->username = 'guest';
2815 $guest->password = hash_internal_user_password('guest');
2816 $guest->firstname = addslashes(get_string('guestuser'));
2817 $guest->lastname = ' ';
2818 $guest->email = 'root@localhost';
2819 $guest->description = addslashes(get_string('guestuserinfo'));
2820 $guest->mnethostid = $CFG->mnet_localhost_id;
2821 $guest->confirmed = 1;
2822 $guest->lang = $CFG->lang;
2823 $guest->timemodified= time();
2825 if (! $guest->id = insert_record("user", $guest)) {
2826 return false;
2829 return $guest;
2833 * Creates a bare-bones user record
2835 * @uses $CFG
2836 * @param string $username New user's username to add to record
2837 * @param string $password New user's password to add to record
2838 * @param string $auth Form of authentication required
2839 * @return object A {@link $USER} object
2840 * @todo Outline auth types and provide code example
2842 function create_user_record($username, $password, $auth='manual') {
2843 global $CFG;
2845 //just in case check text case
2846 $username = trim(moodle_strtolower($username));
2848 $authplugin = get_auth_plugin($auth);
2850 if ($newinfo = $authplugin->get_userinfo($username)) {
2851 $newinfo = truncate_userinfo($newinfo);
2852 foreach ($newinfo as $key => $value){
2853 $newuser->$key = addslashes($value);
2857 if (!empty($newuser->email)) {
2858 if (email_is_not_allowed($newuser->email)) {
2859 unset($newuser->email);
2863 $newuser->auth = $auth;
2864 $newuser->username = $username;
2866 // fix for MDL-8480
2867 // user CFG lang for user if $newuser->lang is empty
2868 // or $user->lang is not an installed language
2869 $sitelangs = array_keys(get_list_of_languages());
2870 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2871 $newuser -> lang = $CFG->lang;
2873 $newuser->confirmed = 1;
2874 $newuser->lastip = getremoteaddr();
2875 $newuser->timemodified = time();
2876 $newuser->mnethostid = $CFG->mnet_localhost_id;
2878 if (insert_record('user', $newuser)) {
2879 $user = get_complete_user_data('username', $newuser->username);
2880 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
2881 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2883 update_internal_user_password($user, $password);
2884 return $user;
2886 return false;
2890 * Will update a local user record from an external source
2892 * @uses $CFG
2893 * @param string $username New user's username to add to record
2894 * @return user A {@link $USER} object
2896 function update_user_record($username, $authplugin) {
2897 $username = trim(moodle_strtolower($username)); /// just in case check text case
2899 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2900 $userauth = get_auth_plugin($oldinfo->auth);
2902 if ($newinfo = $userauth->get_userinfo($username)) {
2903 $newinfo = truncate_userinfo($newinfo);
2904 foreach ($newinfo as $key => $value){
2905 $confval = $userauth->config->{'field_updatelocal_' . $key};
2906 $lockval = $userauth->config->{'field_lock_' . $key};
2907 if (empty($confval) || empty($lockval)) {
2908 continue;
2910 if ($confval === 'onlogin') {
2911 $value = addslashes(stripslashes($value)); // Just in case
2912 // MDL-4207 Don't overwrite modified user profile values with
2913 // empty LDAP values when 'unlocked if empty' is set. The purpose
2914 // of the setting 'unlocked if empty' is to allow the user to fill
2915 // in a value for the selected field _if LDAP is giving
2916 // nothing_ for this field. Thus it makes sense to let this value
2917 // stand in until LDAP is giving a value for this field.
2918 if (!(empty($value) && $lockval === 'unlockedifempty')) {
2919 set_field('user', $key, $value, 'username', $username)
2920 || error_log("Error updating $key for $username");
2926 return get_complete_user_data('username', $username);
2929 function truncate_userinfo($info) {
2930 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2931 /// which may have large fields
2933 // define the limits
2934 $limit = array(
2935 'username' => 100,
2936 'idnumber' => 255,
2937 'firstname' => 100,
2938 'lastname' => 100,
2939 'email' => 100,
2940 'icq' => 15,
2941 'phone1' => 20,
2942 'phone2' => 20,
2943 'institution' => 40,
2944 'department' => 30,
2945 'address' => 70,
2946 'city' => 20,
2947 'country' => 2,
2948 'url' => 255,
2951 // apply where needed
2952 foreach (array_keys($info) as $key) {
2953 if (!empty($limit[$key])) {
2954 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2958 return $info;
2962 * Marks user deleted in internal user database and notifies the auth plugin.
2963 * Also unenrols user from all roles and does other cleanup.
2964 * @param object $user Userobject before delete (without system magic quotes)
2965 * @return boolean success
2967 function delete_user($user) {
2968 global $CFG;
2969 require_once($CFG->libdir.'/grouplib.php');
2970 require_once($CFG->libdir.'/gradelib.php');
2972 begin_sql();
2974 // delete all grades - backup is kept in grade_grades_history table
2975 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
2976 foreach ($grades as $grade) {
2977 $grade->delete('userdelete');
2981 // remove from all groups
2982 delete_records('groups_members', 'userid', $user->id);
2984 // unenrol from all roles in all contexts
2985 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
2987 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2988 delete_context(CONTEXT_USER, $user->id);
2990 require_once($CFG->dirroot.'/tag/lib.php');
2991 tag_set('user', $user->id, array());
2993 // workaround for bulk deletes of users with the same email address
2994 $delname = addslashes("$user->email.".time());
2995 while (record_exists('user', 'username', $delname)) { // no need to use mnethostid here
2996 $delname++;
2999 // mark internal user record as "deleted"
3000 $updateuser = new object();
3001 $updateuser->id = $user->id;
3002 $updateuser->deleted = 1;
3003 $updateuser->username = $delname; // Remember it just in case
3004 $updateuser->email = ''; // Clear this field to free it up
3005 $updateuser->idnumber = ''; // Clear this field to free it up
3006 $updateuser->timemodified = time();
3008 if (update_record('user', $updateuser)) {
3009 commit_sql();
3010 // notify auth plugin - do not block the delete even when plugin fails
3011 $authplugin = get_auth_plugin($user->auth);
3012 $authplugin->user_delete($user);
3014 events_trigger('user_deleted', $user);
3015 return true;
3017 } else {
3018 rollback_sql();
3019 return false;
3024 * Retrieve the guest user object
3026 * @uses $CFG
3027 * @return user A {@link $USER} object
3029 function guest_user() {
3030 global $CFG;
3032 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
3033 $newuser->confirmed = 1;
3034 $newuser->lang = $CFG->lang;
3035 $newuser->lastip = getremoteaddr();
3038 return $newuser;
3042 * Given a username and password, this function looks them
3043 * up using the currently selected authentication mechanism,
3044 * and if the authentication is successful, it returns a
3045 * valid $user object from the 'user' table.
3047 * Uses auth_ functions from the currently active auth module
3049 * After authenticate_user_login() returns success, you will need to
3050 * log that the user has logged in, and call complete_user_login() to set
3051 * the session up.
3053 * @uses $CFG
3054 * @param string $username User's username (with system magic quotes)
3055 * @param string $password User's password (with system magic quotes)
3056 * @return user|flase A {@link $USER} object or false if error
3058 function authenticate_user_login($username, $password) {
3060 global $CFG;
3062 $authsenabled = get_enabled_auth_plugins();
3064 if ($user = get_complete_user_data('username', $username)) {
3065 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3066 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3067 add_to_log(0, 'login', 'error', 'index.php', $username);
3068 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3069 return false;
3071 if (!empty($user->deleted)) {
3072 add_to_log(0, 'login', 'error', 'index.php', $username);
3073 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3074 return false;
3076 $auths = array($auth);
3078 } else {
3079 $auths = $authsenabled;
3080 $user = new object();
3081 $user->id = 0; // User does not exist
3084 foreach ($auths as $auth) {
3085 $authplugin = get_auth_plugin($auth);
3087 // on auth fail fall through to the next plugin
3088 if (!$authplugin->user_login($username, $password)) {
3089 continue;
3092 // successful authentication
3093 if ($user->id) { // User already exists in database
3094 if (empty($user->auth)) { // For some reason auth isn't set yet
3095 set_field('user', 'auth', $auth, 'username', $username);
3096 $user->auth = $auth;
3099 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3101 if (!$authplugin->is_internal()) { // update user record from external DB
3102 $user = update_user_record($username, get_auth_plugin($user->auth));
3104 } else {
3105 // if user not found, create him
3106 $user = create_user_record($username, $password, $auth);
3109 $authplugin->sync_roles($user);
3111 foreach ($authsenabled as $hau) {
3112 $hauth = get_auth_plugin($hau);
3113 $hauth->user_authenticated_hook($user, $username, $password);
3116 /// Log in to a second system if necessary
3117 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
3118 if (!empty($CFG->sso)) {
3119 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
3120 if (function_exists('sso_user_login')) {
3121 if (!sso_user_login($username, $password)) { // Perform the signon process
3122 notify('Second sign-on failed');
3127 if ($user->id===0) {
3128 return false;
3130 return $user;
3133 // failed if all the plugins have failed
3134 add_to_log(0, 'login', 'error', 'index.php', $username);
3135 if (debugging('', DEBUG_ALL)) {
3136 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3138 return false;
3142 * Call to complete the user login process after authenticate_user_login()
3143 * has succeeded. It will setup the $USER variable and other required bits
3144 * and pieces.
3146 * NOTE:
3147 * - It will NOT log anything -- up to the caller to decide what to log.
3151 * @uses $CFG, $USER
3152 * @param string $user obj
3153 * @return user|flase A {@link $USER} object or false if error
3155 function complete_user_login($user) {
3156 global $CFG, $USER;
3158 $USER = $user; // this is required because we need to access preferences here!
3160 reload_user_preferences();
3162 update_user_login_times();
3163 if (empty($CFG->nolastloggedin)) {
3164 set_moodle_cookie($USER->username);
3165 } else {
3166 // do not store last logged in user in cookie
3167 // auth plugins can temporarily override this from loginpage_hook()
3168 // do not save $CFG->nolastloggedin in database!
3169 set_moodle_cookie('nobody');
3171 set_login_session_preferences();
3173 // Call enrolment plugins
3174 check_enrolment_plugins($user);
3176 /// This is what lets the user do anything on the site :-)
3177 load_all_capabilities();
3179 /// Select password change url
3180 $userauth = get_auth_plugin($USER->auth);
3182 /// check whether the user should be changing password
3183 if (get_user_preferences('auth_forcepasswordchange', false)){
3184 if ($userauth->can_change_password()) {
3185 if ($changeurl = $userauth->change_password_url()) {
3186 redirect($changeurl);
3187 } else {
3188 redirect($CFG->httpswwwroot.'/login/change_password.php');
3190 } else {
3191 print_error('nopasswordchangeforced', 'auth');
3194 return $USER;
3198 * Compare password against hash stored in internal user table.
3199 * If necessary it also updates the stored hash to new format.
3201 * @param object user
3202 * @param string plain text password
3203 * @return bool is password valid?
3205 function validate_internal_user_password(&$user, $password) {
3206 global $CFG;
3208 if (!isset($CFG->passwordsaltmain)) {
3209 $CFG->passwordsaltmain = '';
3212 $validated = false;
3214 // get password original encoding in case it was not updated to unicode yet
3215 $textlib = textlib_get_instance();
3216 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
3218 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
3219 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
3220 $validated = true;
3221 } else {
3222 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
3223 $alt = 'passwordsaltalt'.$i;
3224 if (!empty($CFG->$alt)) {
3225 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
3226 $validated = true;
3227 break;
3233 if ($validated) {
3234 // force update of password hash using latest main password salt and encoding if needed
3235 update_internal_user_password($user, $password);
3238 return $validated;
3242 * Calculate hashed value from password using current hash mechanism.
3244 * @param string password
3245 * @return string password hash
3247 function hash_internal_user_password($password) {
3248 global $CFG;
3250 if (isset($CFG->passwordsaltmain)) {
3251 return md5($password.$CFG->passwordsaltmain);
3252 } else {
3253 return md5($password);
3258 * Update pssword hash in user object.
3260 * @param object user
3261 * @param string plain text password
3262 * @param bool store changes also in db, default true
3263 * @return true if hash changed
3265 function update_internal_user_password(&$user, $password) {
3266 global $CFG;
3268 $authplugin = get_auth_plugin($user->auth);
3269 if (!empty($authplugin->config->preventpassindb)) {
3270 $hashedpassword = 'not cached';
3271 } else {
3272 $hashedpassword = hash_internal_user_password($password);
3275 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
3279 * Get a complete user record, which includes all the info
3280 * in the user record
3281 * Intended for setting as $USER session variable
3283 * @uses $CFG
3284 * @uses SITEID
3285 * @param string $field The user field to be checked for a given value.
3286 * @param string $value The value to match for $field.
3287 * @return user A {@link $USER} object.
3289 function get_complete_user_data($field, $value, $mnethostid=null) {
3291 global $CFG;
3293 if (!$field || !$value) {
3294 return false;
3297 /// Build the WHERE clause for an SQL query
3299 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
3301 if (is_null($mnethostid)) {
3302 // if null, we restrict to local users
3303 // ** testing for local user can be done with
3304 // mnethostid = $CFG->mnet_localhost_id
3305 // or with
3306 // auth != 'mnet'
3307 // but the first one is FAST with our indexes
3308 $mnethostid = $CFG->mnet_localhost_id;
3310 $mnethostid = (int)$mnethostid;
3311 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
3313 /// Get all the basic user data
3315 if (! $user = get_record_select('user', $constraints)) {
3316 return false;
3319 /// Get various settings and preferences
3321 if ($displays = get_records('course_display', 'userid', $user->id)) {
3322 foreach ($displays as $display) {
3323 $user->display[$display->course] = $display->display;
3327 $user->preference = get_user_preferences(null, null, $user->id);
3329 $user->lastcourseaccess = array(); // during last session
3330 $user->currentcourseaccess = array(); // during current session
3331 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
3332 foreach ($lastaccesses as $lastaccess) {
3333 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
3337 $sql = "SELECT g.id, g.courseid
3338 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
3339 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
3341 // this is a special hack to speedup calendar display
3342 $user->groupmember = array();
3343 if ($groups = get_records_sql($sql)) {
3344 foreach ($groups as $group) {
3345 if (!array_key_exists($group->courseid, $user->groupmember)) {
3346 $user->groupmember[$group->courseid] = array();
3348 $user->groupmember[$group->courseid][$group->id] = $group->id;
3352 /// Add the custom profile fields to the user record
3353 include_once($CFG->dirroot.'/user/profile/lib.php');
3354 $customfields = (array)profile_user_record($user->id);
3355 foreach ($customfields as $cname=>$cvalue) {
3356 if (!isset($user->$cname)) { // Don't overwrite any standard fields
3357 $user->$cname = $cvalue;
3361 /// Rewrite some variables if necessary
3362 if (!empty($user->description)) {
3363 $user->description = true; // No need to cart all of it around
3365 if ($user->username == 'guest') {
3366 $user->lang = $CFG->lang; // Guest language always same as site
3367 $user->firstname = get_string('guestuser'); // Name always in current language
3368 $user->lastname = ' ';
3371 $user->sesskey = random_string(10);
3372 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
3374 return $user;
3378 * @uses $CFG
3379 * @param string $password the password to be checked agains the password policy
3380 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
3381 * @return bool true if the password is valid according to the policy. false otherwise.
3383 function check_password_policy($password, &$errmsg) {
3384 global $CFG;
3386 if (empty($CFG->passwordpolicy)) {
3387 return true;
3390 $textlib = textlib_get_instance();
3391 $errmsg = '';
3392 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
3393 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
3395 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
3396 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
3398 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
3399 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
3401 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
3402 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
3404 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
3405 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3407 } else if ($password == 'admin' or $password == 'password') {
3408 $errmsg = get_string('unsafepassword');
3411 if ($errmsg == '') {
3412 return true;
3413 } else {
3414 return false;
3420 * When logging in, this function is run to set certain preferences
3421 * for the current SESSION
3423 function set_login_session_preferences() {
3424 global $SESSION, $CFG;
3426 $SESSION->justloggedin = true;
3428 unset($SESSION->lang);
3430 // Restore the calendar filters, if saved
3431 if (intval(get_user_preferences('calendar_persistflt', 0))) {
3432 include_once($CFG->dirroot.'/calendar/lib.php');
3433 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
3439 * Delete a course, including all related data from the database,
3440 * and any associated files from the moodledata folder.
3442 * @param mixed $courseorid The id of the course or course object to delete.
3443 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3444 * @return bool true if all the removals succeeded. false if there were any failures. If this
3445 * method returns false, some of the removals will probably have succeeded, and others
3446 * failed, but you have no way of knowing which.
3448 function delete_course($courseorid, $showfeedback = true) {
3449 global $CFG;
3450 $result = true;
3452 if (is_object($courseorid)) {
3453 $courseid = $courseorid->id;
3454 $course = $courseorid;
3455 } else {
3456 $courseid = $courseorid;
3457 if (!$course = get_record('course', 'id', $courseid)) {
3458 return false;
3462 // frontpage course can not be deleted!!
3463 if ($courseid == SITEID) {
3464 return false;
3467 if (!remove_course_contents($courseid, $showfeedback)) {
3468 if ($showfeedback) {
3469 notify("An error occurred while deleting some of the course contents.");
3471 $result = false;
3474 if (!delete_records("course", "id", $courseid)) {
3475 if ($showfeedback) {
3476 notify("An error occurred while deleting the main course record.");
3478 $result = false;
3481 /// Delete all roles and overiddes in the course context
3482 if (!delete_context(CONTEXT_COURSE, $courseid)) {
3483 if ($showfeedback) {
3484 notify("An error occurred while deleting the main course context.");
3486 $result = false;
3489 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
3490 if ($showfeedback) {
3491 notify("An error occurred while deleting the course files.");
3493 $result = false;
3496 if ($result) {
3497 //trigger events
3498 events_trigger('course_deleted', $course);
3501 return $result;
3505 * Clear a course out completely, deleting all content
3506 * but don't delete the course itself
3508 * @uses $CFG
3509 * @param int $courseid The id of the course that is being deleted
3510 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3511 * @return bool true if all the removals succeeded. false if there were any failures. If this
3512 * method returns false, some of the removals will probably have succeeded, and others
3513 * failed, but you have no way of knowing which.
3515 function remove_course_contents($courseid, $showfeedback=true) {
3517 global $CFG;
3518 require_once($CFG->libdir.'/questionlib.php');
3519 require_once($CFG->libdir.'/gradelib.php');
3521 $result = true;
3523 if (! $course = get_record('course', 'id', $courseid)) {
3524 error('Course ID was incorrect (can\'t find it)');
3527 $strdeleted = get_string('deleted');
3529 /// First delete every instance of every module
3531 if ($allmods = get_records('modules') ) {
3532 foreach ($allmods as $mod) {
3533 $modname = $mod->name;
3534 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3535 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3536 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3537 $count=0;
3538 if (file_exists($modfile)) {
3539 include_once($modfile);
3540 if (function_exists($moddelete)) {
3541 if ($instances = get_records($modname, 'course', $course->id)) {
3542 foreach ($instances as $instance) {
3543 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
3544 /// Delete activity context questions and question categories
3545 question_delete_activity($cm, $showfeedback);
3547 if ($moddelete($instance->id)) {
3548 $count++;
3550 } else {
3551 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
3552 $result = false;
3554 if ($cm) {
3555 // delete cm and its context in correct order
3556 delete_records('course_modules', 'id', $cm->id);
3557 delete_context(CONTEXT_MODULE, $cm->id);
3561 } else {
3562 notify('Function '.$moddelete.'() doesn\'t exist!');
3563 $result = false;
3566 if (function_exists($moddeletecourse)) {
3567 $moddeletecourse($course, $showfeedback);
3570 if ($showfeedback) {
3571 notify($strdeleted .' '. $count .' x '. $modname);
3574 } else {
3575 error('No modules are installed!');
3578 /// Give local code a chance to delete its references to this course.
3579 require_once('locallib.php');
3580 notify_local_delete_course($courseid, $showfeedback);
3582 /// Delete course blocks
3584 if ($blocks = get_records_sql("SELECT *
3585 FROM {$CFG->prefix}block_instance
3586 WHERE pagetype = '".PAGE_COURSE_VIEW."'
3587 AND pageid = $course->id")) {
3588 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
3589 if ($showfeedback) {
3590 notify($strdeleted .' block_instance');
3593 require_once($CFG->libdir.'/blocklib.php');
3594 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3596 delete_context(CONTEXT_BLOCK, $block->id);
3598 // fix for MDL-7164
3599 // Get the block object and call instance_delete()
3600 if (!$record = blocks_get_record($block->blockid)) {
3601 $result = false;
3602 continue;
3604 if (!$obj = block_instance($record->name, $block)) {
3605 $result = false;
3606 continue;
3608 // Return value ignored, in core mods this does not do anything, but just in case
3609 // third party blocks might have stuff to clean up
3610 // we execute this anyway
3611 $obj->instance_delete();
3614 } else {
3615 $result = false;
3619 /// Delete any groups, removing members and grouping/course links first.
3620 require_once($CFG->dirroot.'/group/lib.php');
3621 groups_delete_groupings($courseid, $showfeedback);
3622 groups_delete_groups($courseid, $showfeedback);
3624 /// Delete all related records in other tables that may have a courseid
3625 /// This array stores the tables that need to be cleared, as
3626 /// table_name => column_name that contains the course id.
3628 $tablestoclear = array(
3629 'event' => 'courseid', // Delete events
3630 'log' => 'course', // Delete logs
3631 'course_sections' => 'course', // Delete any course stuff
3632 'course_modules' => 'course',
3633 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3634 'user_lastaccess' => 'courseid',
3635 'backup_log' => 'courseid'
3637 foreach ($tablestoclear as $table => $col) {
3638 if (delete_records($table, $col, $course->id)) {
3639 if ($showfeedback) {
3640 notify($strdeleted . ' ' . $table);
3642 } else {
3643 $result = false;
3648 /// Clean up metacourse stuff
3650 if ($course->metacourse) {
3651 delete_records("course_meta","parent_course",$course->id);
3652 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3653 if ($showfeedback) {
3654 notify("$strdeleted course_meta");
3656 } else {
3657 if ($parents = get_records("course_meta","child_course",$course->id)) {
3658 foreach ($parents as $parent) {
3659 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3661 if ($showfeedback) {
3662 notify("$strdeleted course_meta");
3667 /// Delete questions and question categories
3668 question_delete_course($course, $showfeedback);
3670 /// Remove all data from gradebook
3671 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3672 remove_course_grades($courseid, $showfeedback);
3673 remove_grade_letters($context, $showfeedback);
3675 return $result;
3679 * Change dates in module - used from course reset.
3680 * @param strin $modname forum, assignent, etc
3681 * @param array $fields array of date fields from mod table
3682 * @param int $timeshift time difference
3683 * @return success
3685 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
3686 global $CFG;
3687 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
3689 $return = true;
3690 foreach ($fields as $field) {
3691 $updatesql = "UPDATE {$CFG->prefix}$modname
3692 SET $field = $field + ($timeshift)
3693 WHERE course=$courseid AND $field<>0 AND $field<>0";
3694 $return = execute_sql($updatesql, false) && $return;
3697 $refreshfunction = $modname.'_refresh_events';
3698 if (function_exists($refreshfunction)) {
3699 $refreshfunction($courseid);
3702 return $return;
3706 * This function will empty a course of user data.
3707 * It will retain the activities and the structure of the course.
3708 * @param object $data an object containing all the settings including courseid (without magic quotes)
3709 * @return array status array of array component, item, error
3711 function reset_course_userdata($data) {
3712 global $CFG, $USER;
3713 require_once($CFG->libdir.'/gradelib.php');
3714 require_once($CFG->dirroot.'/group/lib.php');
3716 $data->courseid = $data->id;
3717 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
3719 // calculate the time shift of dates
3720 if (!empty($data->reset_start_date)) {
3721 // time part of course startdate should be zero
3722 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
3723 } else {
3724 $data->timeshift = 0;
3727 // result array: component, item, error
3728 $status = array();
3730 // start the resetting
3731 $componentstr = get_string('general');
3733 // move the course start time
3734 if (!empty($data->reset_start_date) and $data->timeshift) {
3735 // change course start data
3736 set_field('course', 'startdate', $data->reset_start_date, 'id', $data->courseid);
3737 // update all course and group events - do not move activity events
3738 $updatesql = "UPDATE {$CFG->prefix}event
3739 SET timestart = timestart + ({$data->timeshift})
3740 WHERE courseid={$data->courseid} AND instance=0";
3741 execute_sql($updatesql, false);
3743 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
3746 if (!empty($data->reset_logs)) {
3747 delete_records('log', 'course', $data->courseid);
3748 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelogs'), 'error'=>false);
3751 if (!empty($data->reset_events)) {
3752 delete_records('event', 'courseid', $data->courseid);
3753 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteevents', 'calendar'), 'error'=>false);
3756 if (!empty($data->reset_notes)) {
3757 require_once($CFG->dirroot.'/notes/lib.php');
3758 note_delete_all($data->courseid);
3759 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotes', 'notes'), 'error'=>false);
3762 $componentstr = get_string('roles');
3764 if (!empty($data->reset_roles_overrides)) {
3765 $children = get_child_contexts($context);
3766 foreach ($children as $child) {
3767 delete_records('role_capabilities', 'contextid', $child->id);
3769 delete_records('role_capabilities', 'contextid', $context->id);
3770 //force refresh for logged in users
3771 mark_context_dirty($context->path);
3772 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecourseoverrides', 'role'), 'error'=>false);
3775 if (!empty($data->reset_roles_local)) {
3776 $children = get_child_contexts($context);
3777 foreach ($children as $child) {
3778 role_unassign(0, 0, 0, $child->id);
3780 //force refresh for logged in users
3781 mark_context_dirty($context->path);
3782 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelocalroles', 'role'), 'error'=>false);
3785 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
3786 $data->unenrolled = array();
3787 if (!empty($data->reset_roles)) {
3788 foreach($data->reset_roles as $roleid) {
3789 if ($users = get_role_users($roleid, $context, false, 'u.id', 'u.id ASC')) {
3790 foreach ($users as $user) {
3791 role_unassign($roleid, $user->id, 0, $context->id);
3792 if (!has_capability('moodle/course:view', $context, $user->id)) {
3793 $data->unenrolled[$user->id] = $user->id;
3799 if (!empty($data->unenrolled)) {
3800 $status[] = array('component'=>$componentstr, 'item'=>get_string('unenrol').' ('.count($data->unenrolled).')', 'error'=>false);
3804 $componentstr = get_string('groups');
3806 // remove all group members
3807 if (!empty($data->reset_groups_members)) {
3808 groups_delete_group_members($data->courseid);
3809 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupsmembers', 'group'), 'error'=>false);
3812 // remove all groups
3813 if (!empty($data->reset_groups_remove)) {
3814 groups_delete_groups($data->courseid, false);
3815 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroups', 'group'), 'error'=>false);
3818 // remove all grouping members
3819 if (!empty($data->reset_groupings_members)) {
3820 groups_delete_groupings_groups($data->courseid, false);
3821 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupingsmembers', 'group'), 'error'=>false);
3824 // remove all groupings
3825 if (!empty($data->reset_groupings_remove)) {
3826 groups_delete_groupings($data->courseid, false);
3827 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroupings', 'group'), 'error'=>false);
3830 // Look in every instance of every module for data to delete
3831 $unsupported_mods = array();
3832 if ($allmods = get_records('modules') ) {
3833 foreach ($allmods as $mod) {
3834 $modname = $mod->name;
3835 if (!count_records($modname, 'course', $data->courseid)) {
3836 continue; // skip mods with no instances
3838 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
3839 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data
3840 if (file_exists($modfile)) {
3841 include_once($modfile);
3842 if (function_exists($moddeleteuserdata)) {
3843 $modstatus = $moddeleteuserdata($data);
3844 if (is_array($modstatus)) {
3845 $status = array_merge($status, $modstatus);
3846 } else {
3847 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
3849 } else {
3850 $unsupported_mods[] = $mod;
3852 } else {
3853 debugging('Missing lib.php in '.$modname.' module!');
3858 // mention unsupported mods
3859 if (!empty($unsupported_mods)) {
3860 foreach($unsupported_mods as $mod) {
3861 $status[] = array('component'=>get_string('modulenameplural', $mod->name), 'item'=>'', 'error'=>get_string('resetnotimplemented'));
3866 $componentstr = get_string('gradebook', 'grades');
3867 // reset gradebook
3868 if (!empty($data->reset_gradebook_items)) {
3869 remove_course_grades($data->courseid, false);
3870 grade_grab_course_grades($data->courseid);
3871 grade_regrade_final_grades($data->courseid);
3872 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcourseitems', 'grades'), 'error'=>false);
3874 } else if (!empty($data->reset_gradebook_grades)) {
3875 grade_course_reset($data->courseid);
3876 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcoursegrades', 'grades'), 'error'=>false);
3879 return $status;
3882 function generate_email_processing_address($modid,$modargs) {
3883 global $CFG;
3885 if (empty($CFG->siteidentifier)) { // Unique site identification code
3886 set_config('siteidentifier', random_string(32));
3889 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3890 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
3894 function moodle_process_email($modargs,$body) {
3895 // the first char should be an unencoded letter. We'll take this as an action
3896 switch ($modargs{0}) {
3897 case 'B': { // bounce
3898 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3899 if ($user = get_record_select("user","id=$userid","id,email")) {
3900 // check the half md5 of their email
3901 $md5check = substr(md5($user->email),0,16);
3902 if ($md5check == substr($modargs, -16)) {
3903 set_bounce_count($user);
3905 // else maybe they've already changed it?
3908 break;
3909 // maybe more later?
3913 /// CORRESPONDENCE ////////////////////////////////////////////////
3916 * Get mailer instance, enable buffering, flush buffer or disable buffering.
3917 * @param $action string 'get', 'buffer', 'close' or 'flush'
3918 * @return reference to mailer instance if 'get' used or nothing
3920 function &get_mailer($action='get') {
3921 global $CFG;
3923 static $mailer = null;
3924 static $counter = 0;
3926 if (!isset($CFG->smtpmaxbulk)) {
3927 $CFG->smtpmaxbulk = 1;
3930 if ($action == 'get') {
3931 $prevkeepalive = false;
3933 if (isset($mailer) and $mailer->Mailer == 'smtp') {
3934 if ($counter < $CFG->smtpmaxbulk and empty($mailer->error_count)) {
3935 $counter++;
3936 // reset the mailer
3937 $mailer->Priority = 3;
3938 $mailer->CharSet = 'UTF-8'; // our default
3939 $mailer->ContentType = "text/plain";
3940 $mailer->Encoding = "8bit";
3941 $mailer->From = "root@localhost";
3942 $mailer->FromName = "Root User";
3943 $mailer->Sender = "";
3944 $mailer->Subject = "";
3945 $mailer->Body = "";
3946 $mailer->AltBody = "";
3947 $mailer->ConfirmReadingTo = "";
3949 $mailer->ClearAllRecipients();
3950 $mailer->ClearReplyTos();
3951 $mailer->ClearAttachments();
3952 $mailer->ClearCustomHeaders();
3953 return $mailer;
3956 $prevkeepalive = $mailer->SMTPKeepAlive;
3957 get_mailer('flush');
3960 include_once($CFG->libdir.'/phpmailer/class.phpmailer.php');
3961 $mailer = new phpmailer();
3963 $counter = 1;
3965 $mailer->Version = 'Moodle '.$CFG->version; // mailer version
3966 $mailer->PluginDir = $CFG->libdir.'/phpmailer/'; // plugin directory (eg smtp plugin)
3967 $mailer->CharSet = 'UTF-8';
3969 // some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis
3970 // hmm, this is a bit hacky because LE should be private
3971 if (isset($CFG->mailnewline) and $CFG->mailnewline == 'CRLF') {
3972 $mailer->LE = "\r\n";
3973 } else {
3974 $mailer->LE = "\n";
3977 if ($CFG->smtphosts == 'qmail') {
3978 $mailer->IsQmail(); // use Qmail system
3980 } else if (empty($CFG->smtphosts)) {
3981 $mailer->IsMail(); // use PHP mail() = sendmail
3983 } else {
3984 $mailer->IsSMTP(); // use SMTP directly
3985 if (!empty($CFG->debugsmtp)) {
3986 $mailer->SMTPDebug = true;
3988 $mailer->Host = $CFG->smtphosts; // specify main and backup servers
3989 $mailer->SMTPKeepAlive = $prevkeepalive; // use previous keepalive
3991 if ($CFG->smtpuser) { // Use SMTP authentication
3992 $mailer->SMTPAuth = true;
3993 $mailer->Username = $CFG->smtpuser;
3994 $mailer->Password = $CFG->smtppass;
3998 return $mailer;
4001 $nothing = null;
4003 // keep smtp session open after sending
4004 if ($action == 'buffer') {
4005 if (!empty($CFG->smtpmaxbulk)) {
4006 get_mailer('flush');
4007 $m =& get_mailer();
4008 if ($m->Mailer == 'smtp') {
4009 $m->SMTPKeepAlive = true;
4012 return $nothing;
4015 // close smtp session, but continue buffering
4016 if ($action == 'flush') {
4017 if (isset($mailer) and $mailer->Mailer == 'smtp') {
4018 if (!empty($mailer->SMTPDebug)) {
4019 echo '<pre>'."\n";
4021 $mailer->SmtpClose();
4022 if (!empty($mailer->SMTPDebug)) {
4023 echo '</pre>';
4026 return $nothing;
4029 // close smtp session, do not buffer anymore
4030 if ($action == 'close') {
4031 if (isset($mailer) and $mailer->Mailer == 'smtp') {
4032 get_mailer('flush');
4033 $mailer->SMTPKeepAlive = false;
4035 $mailer = null; // better force new instance
4036 return $nothing;
4041 * Send an email to a specified user
4043 * @uses $CFG
4044 * @uses $FULLME
4045 * @uses SITEID
4046 * @param user $user A {@link $USER} object
4047 * @param user $from A {@link $USER} object
4048 * @param string $subject plain text subject line of the email
4049 * @param string $messagetext plain text version of the message
4050 * @param string $messagehtml complete html version of the message (optional)
4051 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
4052 * @param string $attachname the name of the file (extension indicates MIME)
4053 * @param bool $usetrueaddress determines whether $from email address should
4054 * be sent out. Will be overruled by user profile setting for maildisplay
4055 * @param int $wordwrapwidth custom word wrap width
4056 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4057 * was blocked by user and "false" if there was another sort of error.
4059 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='', $wordwrapwidth=79) {
4061 global $CFG, $FULLME;
4063 if (empty($user)) {
4064 return false;
4067 if (!empty($CFG->noemailever)) {
4068 // hidden setting for development sites, set in config.php if needed
4069 return true;
4072 // skip mail to suspended users
4073 if (isset($user->auth) && $user->auth=='nologin') {
4074 return true;
4077 if (!empty($user->emailstop)) {
4078 return 'emailstop';
4081 if (over_bounce_threshold($user)) {
4082 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
4083 return false;
4086 $mail =& get_mailer();
4088 if (!empty($mail->SMTPDebug)) {
4089 echo '<pre>' . "\n";
4092 /// We are going to use textlib services here
4093 $textlib = textlib_get_instance();
4095 $supportuser = generate_email_supportuser();
4097 // make up an email address for handling bounces
4098 if (!empty($CFG->handlebounces)) {
4099 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
4100 $mail->Sender = generate_email_processing_address(0,$modargs);
4101 } else {
4102 $mail->Sender = $supportuser->email;
4105 if (is_string($from)) { // So we can pass whatever we want if there is need
4106 $mail->From = $CFG->noreplyaddress;
4107 $mail->FromName = $from;
4108 } else if ($usetrueaddress and $from->maildisplay) {
4109 $mail->From = $from->email;
4110 $mail->FromName = fullname($from);
4111 } else {
4112 $mail->From = $CFG->noreplyaddress;
4113 $mail->FromName = fullname($from);
4114 if (empty($replyto)) {
4115 $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
4119 if (!empty($replyto)) {
4120 $mail->AddReplyTo($replyto,$replytoname);
4123 $mail->Subject = substr(stripslashes($subject), 0, 900);
4125 $mail->AddAddress($user->email, fullname($user) );
4127 $mail->WordWrap = $wordwrapwidth; // set word wrap
4129 if (!empty($from->customheaders)) { // Add custom headers
4130 if (is_array($from->customheaders)) {
4131 foreach ($from->customheaders as $customheader) {
4132 $mail->AddCustomHeader($customheader);
4134 } else {
4135 $mail->AddCustomHeader($from->customheaders);
4139 if (!empty($from->priority)) {
4140 $mail->Priority = $from->priority;
4143 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
4144 $mail->IsHTML(true);
4145 $mail->Encoding = 'quoted-printable'; // Encoding to use
4146 $mail->Body = $messagehtml;
4147 $mail->AltBody = "\n$messagetext\n";
4148 } else {
4149 $mail->IsHTML(false);
4150 $mail->Body = "\n$messagetext\n";
4153 if ($attachment && $attachname) {
4154 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
4155 $mail->AddAddress($supportuser->email, fullname($supportuser, true) );
4156 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
4157 } else {
4158 require_once($CFG->libdir.'/filelib.php');
4159 $mimetype = mimeinfo('type', $attachname);
4160 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
4166 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
4167 /// encoding to the specified one
4168 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
4169 /// Set it to site mail charset
4170 $charset = $CFG->sitemailcharset;
4171 /// Overwrite it with the user mail charset
4172 if (!empty($CFG->allowusermailcharset)) {
4173 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
4174 $charset = $useremailcharset;
4177 /// If it has changed, convert all the necessary strings
4178 $charsets = get_list_of_charsets();
4179 unset($charsets['UTF-8']);
4180 if (in_array($charset, $charsets)) {
4181 /// Save the new mail charset
4182 $mail->CharSet = $charset;
4183 /// And convert some strings
4184 $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
4185 foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names
4186 $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet);
4188 $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject
4189 foreach ($mail->to as $key => $to) {
4190 $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet); //To Names
4192 $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body
4193 $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject
4197 if ($mail->Send()) {
4198 set_send_count($user);
4199 $mail->IsSMTP(); // use SMTP directly
4200 if (!empty($mail->SMTPDebug)) {
4201 echo '</pre>';
4203 return true;
4204 } else {
4205 mtrace('ERROR: '. $mail->ErrorInfo);
4206 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
4207 if (!empty($mail->SMTPDebug)) {
4208 echo '</pre>';
4210 return false;
4215 * Generate a signoff for emails based on support settings
4218 function generate_email_signoff() {
4219 global $CFG;
4221 $signoff = "\n";
4222 if (!empty($CFG->supportname)) {
4223 $signoff .= $CFG->supportname."\n";
4225 if (!empty($CFG->supportemail)) {
4226 $signoff .= $CFG->supportemail."\n";
4228 if (!empty($CFG->supportpage)) {
4229 $signoff .= $CFG->supportpage."\n";
4231 return $signoff;
4235 * Generate a fake user for emails based on support settings
4238 function generate_email_supportuser() {
4240 global $CFG;
4242 static $supportuser;
4244 if (!empty($supportuser)) {
4245 return $supportuser;
4248 $supportuser = new object;
4249 $supportuser->email = $CFG->supportemail ? $CFG->supportemail : $CFG->noreplyaddress;
4250 $supportuser->firstname = $CFG->supportname ? $CFG->supportname : get_string('noreplyname');
4251 $supportuser->lastname = '';
4252 $supportuser->maildisplay = true;
4254 return $supportuser;
4259 * Sets specified user's password and send the new password to the user via email.
4261 * @uses $CFG
4262 * @param user $user A {@link $USER} object
4263 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
4264 * was blocked by user and "false" if there was another sort of error.
4266 function setnew_password_and_mail($user) {
4268 global $CFG;
4270 $site = get_site();
4272 $supportuser = generate_email_supportuser();
4274 $newpassword = generate_password();
4276 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
4277 trigger_error('Could not set user password!');
4278 return false;
4281 $a = new object();
4282 $a->firstname = fullname($user, true);
4283 $a->sitename = format_string($site->fullname);
4284 $a->username = $user->username;
4285 $a->newpassword = $newpassword;
4286 $a->link = $CFG->wwwroot .'/login/';
4287 $a->signoff = generate_email_signoff();
4289 $message = get_string('newusernewpasswordtext', '', $a);
4291 $subject = format_string($site->fullname) .': '. get_string('newusernewpasswordsubj');
4293 return email_to_user($user, $supportuser, $subject, $message);
4298 * Resets specified user's password and send the new password to the user via email.
4300 * @uses $CFG
4301 * @param user $user A {@link $USER} object
4302 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4303 * was blocked by user and "false" if there was another sort of error.
4305 function reset_password_and_mail($user) {
4307 global $CFG;
4309 $site = get_site();
4310 $supportuser = generate_email_supportuser();
4312 $userauth = get_auth_plugin($user->auth);
4313 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
4314 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
4315 return false;
4318 $newpassword = generate_password();
4320 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
4321 error("Could not set user password!");
4324 $a = new object();
4325 $a->firstname = $user->firstname;
4326 $a->sitename = format_string($site->fullname);
4327 $a->username = $user->username;
4328 $a->newpassword = $newpassword;
4329 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
4330 $a->signoff = generate_email_signoff();
4332 $message = get_string('newpasswordtext', '', $a);
4334 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
4336 return email_to_user($user, $supportuser, $subject, $message);
4341 * Send email to specified user with confirmation text and activation link.
4343 * @uses $CFG
4344 * @param user $user A {@link $USER} object
4345 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4346 * was blocked by user and "false" if there was another sort of error.
4348 function send_confirmation_email($user) {
4350 global $CFG;
4352 $site = get_site();
4353 $supportuser = generate_email_supportuser();
4355 $data = new object();
4356 $data->firstname = fullname($user);
4357 $data->sitename = format_string($site->fullname);
4358 $data->admin = generate_email_signoff();
4360 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
4362 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. urlencode($user->username);
4363 $message = get_string('emailconfirmation', '', $data);
4364 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
4366 $user->mailformat = 1; // Always send HTML version as well
4368 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
4373 * send_password_change_confirmation_email.
4375 * @uses $CFG
4376 * @param user $user A {@link $USER} object
4377 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4378 * was blocked by user and "false" if there was another sort of error.
4380 function send_password_change_confirmation_email($user) {
4382 global $CFG;
4384 $site = get_site();
4385 $supportuser = generate_email_supportuser();
4387 $data = new object();
4388 $data->firstname = $user->firstname;
4389 $data->sitename = format_string($site->fullname);
4390 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
4391 $data->admin = generate_email_signoff();
4393 $message = get_string('emailpasswordconfirmation', '', $data);
4394 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
4396 return email_to_user($user, $supportuser, $subject, $message);
4401 * send_password_change_info.
4403 * @uses $CFG
4404 * @param user $user A {@link $USER} object
4405 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4406 * was blocked by user and "false" if there was another sort of error.
4408 function send_password_change_info($user) {
4410 global $CFG;
4412 $site = get_site();
4413 $supportuser = generate_email_supportuser();
4414 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
4416 $data = new object();
4417 $data->firstname = $user->firstname;
4418 $data->sitename = format_string($site->fullname);
4419 $data->admin = generate_email_signoff();
4421 $userauth = get_auth_plugin($user->auth);
4423 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
4424 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
4425 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
4426 return email_to_user($user, $supportuser, $subject, $message);
4429 if ($userauth->can_change_password() and $userauth->change_password_url()) {
4430 // we have some external url for password changing
4431 $data->link .= $userauth->change_password_url();
4433 } else {
4434 //no way to change password, sorry
4435 $data->link = '';
4438 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
4439 $message = get_string('emailpasswordchangeinfo', '', $data);
4440 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
4441 } else {
4442 $message = get_string('emailpasswordchangeinfofail', '', $data);
4443 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
4446 return email_to_user($user, $supportuser, $subject, $message);
4451 * Check that an email is allowed. It returns an error message if there
4452 * was a problem.
4454 * @uses $CFG
4455 * @param string $email Content of email
4456 * @return string|false
4458 function email_is_not_allowed($email) {
4460 global $CFG;
4462 if (!empty($CFG->allowemailaddresses)) {
4463 $allowed = explode(' ', $CFG->allowemailaddresses);
4464 foreach ($allowed as $allowedpattern) {
4465 $allowedpattern = trim($allowedpattern);
4466 if (!$allowedpattern) {
4467 continue;
4469 if (strpos($allowedpattern, '.') === 0) {
4470 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
4471 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
4472 return false;
4475 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
4476 return false;
4479 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
4481 } else if (!empty($CFG->denyemailaddresses)) {
4482 $denied = explode(' ', $CFG->denyemailaddresses);
4483 foreach ($denied as $deniedpattern) {
4484 $deniedpattern = trim($deniedpattern);
4485 if (!$deniedpattern) {
4486 continue;
4488 if (strpos($deniedpattern, '.') === 0) {
4489 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
4490 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
4491 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
4494 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
4495 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
4500 return false;
4503 function email_welcome_message_to_user($course, $user=NULL) {
4504 global $CFG, $USER;
4506 if (empty($user)) {
4507 if (!isloggedin()) {
4508 return false;
4510 $user = $USER;
4513 if (!empty($course->welcomemessage)) {
4514 $message = $course->welcomemessage;
4515 } else {
4516 $a = new Object();
4517 $a->coursename = $course->fullname;
4518 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
4519 $message = get_string("welcometocoursetext", "", $a);
4522 /// If you don't want a welcome message sent, then make the message string blank.
4523 if (!empty($message)) {
4524 $subject = get_string('welcometocourse', '', format_string($course->fullname));
4526 if (! $teacher = get_teacher($course->id)) {
4527 $teacher = get_admin();
4529 email_to_user($user, $teacher, $subject, $message);
4533 /// FILE HANDLING /////////////////////////////////////////////
4537 * Makes an upload directory for a particular module.
4539 * @uses $CFG
4540 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
4541 * @return string|false Returns full path to directory if successful, false if not
4543 function make_mod_upload_directory($courseid) {
4544 global $CFG;
4546 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
4547 return false;
4550 $strreadme = get_string('readme');
4552 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
4553 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4554 } else {
4555 copy($CFG->dirroot .'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4557 return $moddata;
4561 * Makes a directory for a particular user.
4563 * @uses $CFG
4564 * @param int $userid The id of the user in question - maps to id field of 'user' table.
4565 * @param bool $test Whether we are only testing the return value (do not create the directory)
4566 * @return string|false Returns full path to directory if successful, false if not
4568 function make_user_directory($userid, $test=false) {
4569 global $CFG;
4571 if (is_bool($userid) || $userid < 0 || !ereg('^[0-9]{1,10}$', $userid) || $userid > 2147483647) {
4572 if (!$test) {
4573 notify("Given userid was not a valid integer! (" . gettype($userid) . " $userid)");
4575 return false;
4578 // Generate a two-level path for the userid. First level groups them by slices of 1000 users, second level is userid
4579 $level1 = floor($userid / 1000) * 1000;
4581 $userdir = "user/$level1/$userid";
4582 if ($test) {
4583 return $CFG->dataroot . '/' . $userdir;
4584 } else {
4585 return make_upload_directory($userdir);
4590 * Returns an array of full paths to user directories, indexed by their userids.
4592 * @param bool $only_non_empty Only return directories that contain files
4593 * @param bool $legacy Search for user directories in legacy location (dataroot/users/userid) instead of (dataroot/user/section/userid)
4594 * @return array An associative array: userid=>array(basedir => $basedir, userfolder => $userfolder)
4596 function get_user_directories($only_non_empty=true, $legacy=false) {
4597 global $CFG;
4599 $rootdir = $CFG->dataroot."/user";
4601 if ($legacy) {
4602 $rootdir = $CFG->dataroot."/users";
4604 $dirlist = array();
4606 //Check if directory exists
4607 if (check_dir_exists($rootdir, true)) {
4608 if ($legacy) {
4609 if ($userlist = get_directory_list($rootdir, '', true, true, false)) {
4610 foreach ($userlist as $userid) {
4611 $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $userid);
4613 } else {
4614 notify("no directories found under $rootdir");
4616 } else {
4617 if ($grouplist =get_directory_list($rootdir, '', true, true, false)) { // directories will be in the form 0, 1000, 2000 etc...
4618 foreach ($grouplist as $group) {
4619 if ($userlist = get_directory_list("$rootdir/$group", '', true, true, false)) {
4620 foreach ($userlist as $userid) {
4621 $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $group . '/' . $userid);
4627 } else {
4628 notify("$rootdir does not exist!");
4629 return false;
4631 return $dirlist;
4635 * Returns current name of file on disk if it exists.
4637 * @param string $newfile File to be verified
4638 * @return string Current name of file on disk if true
4640 function valid_uploaded_file($newfile) {
4641 if (empty($newfile)) {
4642 return '';
4644 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
4645 return $newfile['tmp_name'];
4646 } else {
4647 return '';
4652 * Returns the maximum size for uploading files.
4654 * There are seven possible upload limits:
4655 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
4656 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
4657 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
4658 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
4659 * 5. by the Moodle admin in $CFG->maxbytes
4660 * 6. by the teacher in the current course $course->maxbytes
4661 * 7. by the teacher for the current module, eg $assignment->maxbytes
4663 * These last two are passed to this function as arguments (in bytes).
4664 * Anything defined as 0 is ignored.
4665 * The smallest of all the non-zero numbers is returned.
4667 * @param int $sizebytes ?
4668 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4669 * @param int $modulebytes Current module ->maxbytes (in bytes)
4670 * @return int The maximum size for uploading files.
4671 * @todo Finish documenting this function
4673 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4675 if (! $filesize = ini_get('upload_max_filesize')) {
4676 $filesize = '5M';
4678 $minimumsize = get_real_size($filesize);
4680 if ($postsize = ini_get('post_max_size')) {
4681 $postsize = get_real_size($postsize);
4682 if ($postsize < $minimumsize) {
4683 $minimumsize = $postsize;
4687 if ($sitebytes and $sitebytes < $minimumsize) {
4688 $minimumsize = $sitebytes;
4691 if ($coursebytes and $coursebytes < $minimumsize) {
4692 $minimumsize = $coursebytes;
4695 if ($modulebytes and $modulebytes < $minimumsize) {
4696 $minimumsize = $modulebytes;
4699 return $minimumsize;
4703 * Related to {@link get_max_upload_file_size()} - this function returns an
4704 * array of possible sizes in an array, translated to the
4705 * local language.
4707 * @uses SORT_NUMERIC
4708 * @param int $sizebytes ?
4709 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4710 * @param int $modulebytes Current module ->maxbytes (in bytes)
4711 * @return int
4712 * @todo Finish documenting this function
4714 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4715 global $CFG;
4717 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
4718 return array();
4721 $filesize[$maxsize] = display_size($maxsize);
4723 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4724 5242880, 10485760, 20971520, 52428800, 104857600);
4726 // Allow maxbytes to be selected if it falls outside the above boundaries
4727 if( isset($CFG->maxbytes) && !in_array($CFG->maxbytes, $sizelist) ){
4728 $sizelist[] = $CFG->maxbytes;
4731 foreach ($sizelist as $sizebytes) {
4732 if ($sizebytes < $maxsize) {
4733 $filesize[$sizebytes] = display_size($sizebytes);
4737 krsort($filesize, SORT_NUMERIC);
4739 return $filesize;
4743 * If there has been an error uploading a file, print the appropriate error message
4744 * Numerical constants used as constant definitions not added until PHP version 4.2.0
4746 * $filearray is a 1-dimensional sub-array of the $_FILES array
4747 * eg $filearray = $_FILES['userfile1']
4748 * If left empty then the first element of the $_FILES array will be used
4750 * @uses $_FILES
4751 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
4752 * @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.
4753 * @return bool|string
4755 function print_file_upload_error($filearray = '', $returnerror = false) {
4757 if ($filearray == '' or !isset($filearray['error'])) {
4759 if (empty($_FILES)) return false;
4761 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
4762 $filearray = array_shift($files); /// use first element of array
4765 switch ($filearray['error']) {
4767 case 0: // UPLOAD_ERR_OK
4768 if ($filearray['size'] > 0) {
4769 $errmessage = get_string('uploadproblem', $filearray['name']);
4770 } else {
4771 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
4773 break;
4775 case 1: // UPLOAD_ERR_INI_SIZE
4776 $errmessage = get_string('uploadserverlimit');
4777 break;
4779 case 2: // UPLOAD_ERR_FORM_SIZE
4780 $errmessage = get_string('uploadformlimit');
4781 break;
4783 case 3: // UPLOAD_ERR_PARTIAL
4784 $errmessage = get_string('uploadpartialfile');
4785 break;
4787 case 4: // UPLOAD_ERR_NO_FILE
4788 $errmessage = get_string('uploadnofilefound');
4789 break;
4791 default:
4792 $errmessage = get_string('uploadproblem', $filearray['name']);
4795 if ($returnerror) {
4796 return $errmessage;
4797 } else {
4798 notify($errmessage);
4799 return true;
4805 * handy function to loop through an array of files and resolve any filename conflicts
4806 * both in the array of filenames and for what is already on disk.
4807 * not really compatible with the similar function in uploadlib.php
4808 * but this could be used for files/index.php for moving files around.
4811 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4812 foreach ($files as $k => $f) {
4813 if (check_potential_filename($destination,$f,$files)) {
4814 $bits = explode('.', $f);
4815 for ($i = 1; true; $i++) {
4816 $try = sprintf($format, $bits[0], $i, $bits[1]);
4817 if (!check_potential_filename($destination,$try,$files)) {
4818 $files[$k] = $try;
4819 break;
4824 return $files;
4828 * @used by resolve_filename_collisions
4830 function check_potential_filename($destination,$filename,$files) {
4831 if (file_exists($destination.'/'.$filename)) {
4832 return true;
4834 if (count(array_keys($files,$filename)) > 1) {
4835 return true;
4837 return false;
4842 * Returns an array with all the filenames in
4843 * all subdirectories, relative to the given rootdir.
4844 * If excludefile is defined, then that file/directory is ignored
4845 * If getdirs is true, then (sub)directories are included in the output
4846 * If getfiles is true, then files are included in the output
4847 * (at least one of these must be true!)
4849 * @param string $rootdir ?
4850 * @param string $excludefile If defined then the specified file/directory is ignored
4851 * @param bool $descend ?
4852 * @param bool $getdirs If true then (sub)directories are included in the output
4853 * @param bool $getfiles If true then files are included in the output
4854 * @return array An array with all the filenames in
4855 * all subdirectories, relative to the given rootdir
4856 * @todo Finish documenting this function. Add examples of $excludefile usage.
4858 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4860 $dirs = array();
4862 if (!$getdirs and !$getfiles) { // Nothing to show
4863 return $dirs;
4866 if (!is_dir($rootdir)) { // Must be a directory
4867 return $dirs;
4870 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4871 return $dirs;
4874 if (!is_array($excludefiles)) {
4875 $excludefiles = array($excludefiles);
4878 while (false !== ($file = readdir($dir))) {
4879 $firstchar = substr($file, 0, 1);
4880 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4881 continue;
4883 $fullfile = $rootdir .'/'. $file;
4884 if (filetype($fullfile) == 'dir') {
4885 if ($getdirs) {
4886 $dirs[] = $file;
4888 if ($descend) {
4889 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4890 foreach ($subdirs as $subdir) {
4891 $dirs[] = $file .'/'. $subdir;
4894 } else if ($getfiles) {
4895 $dirs[] = $file;
4898 closedir($dir);
4900 asort($dirs);
4902 return $dirs;
4907 * Adds up all the files in a directory and works out the size.
4909 * @param string $rootdir ?
4910 * @param string $excludefile ?
4911 * @return array
4912 * @todo Finish documenting this function
4914 function get_directory_size($rootdir, $excludefile='') {
4916 global $CFG;
4918 // do it this way if we can, it's much faster
4919 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
4920 $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
4921 $output = null;
4922 $return = null;
4923 exec($command,$output,$return);
4924 if (is_array($output)) {
4925 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4929 if (!is_dir($rootdir)) { // Must be a directory
4930 return 0;
4933 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
4934 return 0;
4937 $size = 0;
4939 while (false !== ($file = readdir($dir))) {
4940 $firstchar = substr($file, 0, 1);
4941 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4942 continue;
4944 $fullfile = $rootdir .'/'. $file;
4945 if (filetype($fullfile) == 'dir') {
4946 $size += get_directory_size($fullfile, $excludefile);
4947 } else {
4948 $size += filesize($fullfile);
4951 closedir($dir);
4953 return $size;
4957 * Converts bytes into display form
4959 * @param string $size ?
4960 * @return string
4961 * @staticvar string $gb Localized string for size in gigabytes
4962 * @staticvar string $mb Localized string for size in megabytes
4963 * @staticvar string $kb Localized string for size in kilobytes
4964 * @staticvar string $b Localized string for size in bytes
4965 * @todo Finish documenting this function. Verify return type.
4967 function display_size($size) {
4969 static $gb, $mb, $kb, $b;
4971 if (empty($gb)) {
4972 $gb = get_string('sizegb');
4973 $mb = get_string('sizemb');
4974 $kb = get_string('sizekb');
4975 $b = get_string('sizeb');
4978 if ($size >= 1073741824) {
4979 $size = round($size / 1073741824 * 10) / 10 . $gb;
4980 } else if ($size >= 1048576) {
4981 $size = round($size / 1048576 * 10) / 10 . $mb;
4982 } else if ($size >= 1024) {
4983 $size = round($size / 1024 * 10) / 10 . $kb;
4984 } else {
4985 $size = $size .' '. $b;
4987 return $size;
4991 * Cleans a given filename by removing suspicious or troublesome characters
4992 * Only these are allowed: alphanumeric _ - .
4993 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4995 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4996 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4998 * @param string $string file name
4999 * @return string cleaned file name
5001 function clean_filename($string) {
5002 global $CFG;
5003 if (empty($CFG->unicodecleanfilename)) {
5004 $textlib = textlib_get_instance();
5005 $string = $textlib->specialtoascii($string);
5006 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
5007 } else {
5008 //clean only ascii range
5009 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
5011 $string = preg_replace("/_+/", '_', $string);
5012 $string = preg_replace("/\.\.+/", '.', $string);
5013 return $string;
5017 /// STRING TRANSLATION ////////////////////////////////////////
5020 * Returns the code for the current language
5022 * @uses $CFG
5023 * @param $USER
5024 * @param $SESSION
5025 * @return string
5027 function current_language() {
5028 global $CFG, $USER, $SESSION, $COURSE;
5030 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
5031 $return = $COURSE->lang;
5033 } else if (!empty($SESSION->lang)) { // Session language can override other settings
5034 $return = $SESSION->lang;
5036 } else if (!empty($USER->lang)) {
5037 $return = $USER->lang;
5039 } else {
5040 $return = $CFG->lang;
5043 if ($return == 'en') {
5044 $return = 'en_utf8';
5047 return $return;
5051 * Prints out a translated string.
5053 * Prints out a translated string using the return value from the {@link get_string()} function.
5055 * Example usage of this function when the string is in the moodle.php file:<br/>
5056 * <code>
5057 * echo '<strong>';
5058 * print_string('wordforstudent');
5059 * echo '</strong>';
5060 * </code>
5062 * Example usage of this function when the string is not in the moodle.php file:<br/>
5063 * <code>
5064 * echo '<h1>';
5065 * print_string('typecourse', 'calendar');
5066 * echo '</h1>';
5067 * </code>
5069 * @param string $identifier The key identifier for the localized string
5070 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
5071 * @param mixed $a An object, string or number that can be used
5072 * within translation strings
5074 function print_string($identifier, $module='', $a=NULL) {
5075 echo get_string($identifier, $module, $a);
5079 * fix up the optional data in get_string()/print_string() etc
5080 * ensure possible sprintf() format characters are escaped correctly
5081 * needs to handle arbitrary strings and objects
5082 * @param mixed $a An object, string or number that can be used
5083 * @return mixed the supplied parameter 'cleaned'
5085 function clean_getstring_data( $a ) {
5086 if (is_string($a)) {
5087 return str_replace( '%','%%',$a );
5089 elseif (is_object($a)) {
5090 $a_vars = get_object_vars( $a );
5091 $new_a_vars = array();
5092 foreach ($a_vars as $fname => $a_var) {
5093 $new_a_vars[$fname] = clean_getstring_data( $a_var );
5095 return (object)$new_a_vars;
5097 else {
5098 return $a;
5103 * @return array places to look for lang strings based on the prefix to the
5104 * module name. For example qtype_ in question/type. Used by get_string and
5105 * help.php.
5107 function places_to_search_for_lang_strings() {
5108 global $CFG;
5110 return array(
5111 '__exceptions' => array('moodle', 'langconfig'),
5112 'assignment_' => array('mod/assignment/type'),
5113 'auth_' => array('auth'),
5114 'block_' => array('blocks'),
5115 'datafield_' => array('mod/data/field'),
5116 'datapreset_' => array('mod/data/preset'),
5117 'enrol_' => array('enrol'),
5118 'filter_' => array('filter'),
5119 'format_' => array('course/format'),
5120 'qtype_' => array('question/type'),
5121 'report_' => array($CFG->admin.'/report', 'course/report', 'mod/quiz/report'),
5122 'resource_' => array('mod/resource/type'),
5123 'gradereport_' => array('grade/report'),
5124 'gradeimport_' => array('grade/import'),
5125 'gradeexport_' => array('grade/export'),
5126 'profilefield_' => array('user/profile/field'),
5127 '' => array('mod')
5132 * Returns a localized string.
5134 * Returns the translated string specified by $identifier as
5135 * for $module. Uses the same format files as STphp.
5136 * $a is an object, string or number that can be used
5137 * within translation strings
5139 * eg "hello \$a->firstname \$a->lastname"
5140 * or "hello \$a"
5142 * If you would like to directly echo the localized string use
5143 * the function {@link print_string()}
5145 * Example usage of this function involves finding the string you would
5146 * like a local equivalent of and using its identifier and module information
5147 * to retrive it.<br/>
5148 * If you open moodle/lang/en/moodle.php and look near line 1031
5149 * you will find a string to prompt a user for their word for student
5150 * <code>
5151 * $string['wordforstudent'] = 'Your word for Student';
5152 * </code>
5153 * So if you want to display the string 'Your word for student'
5154 * in any language that supports it on your site
5155 * you just need to use the identifier 'wordforstudent'
5156 * <code>
5157 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
5159 * </code>
5160 * If the string you want is in another file you'd take a slightly
5161 * different approach. Looking in moodle/lang/en/calendar.php you find
5162 * around line 75:
5163 * <code>
5164 * $string['typecourse'] = 'Course event';
5165 * </code>
5166 * If you want to display the string "Course event" in any language
5167 * supported you would use the identifier 'typecourse' and the module 'calendar'
5168 * (because it is in the file calendar.php):
5169 * <code>
5170 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
5171 * </code>
5173 * As a last resort, should the identifier fail to map to a string
5174 * the returned string will be [[ $identifier ]]
5176 * @uses $CFG
5177 * @param string $identifier The key identifier for the localized string
5178 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
5179 * @param mixed $a An object, string or number that can be used
5180 * within translation strings
5181 * @param array $extralocations An array of strings with other locations to look for string files
5182 * @return string The localized string.
5184 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
5186 global $CFG;
5188 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
5189 $langconfigstrs = array('alphabet', 'backupnameformat', 'decsep', 'firstdayofweek', 'listsep', 'locale',
5190 'localewin', 'localewincharset', 'oldcharset',
5191 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
5192 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
5193 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
5194 'thischarset', 'thisdirection', 'thislanguage', 'strftimedatetimeshort');
5196 $filetocheck = 'langconfig.php';
5197 $defaultlang = 'en_utf8';
5198 if (in_array($identifier, $langconfigstrs)) {
5199 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
5202 $lang = current_language();
5204 if ($module == '') {
5205 $module = 'moodle';
5208 // if $a happens to have % in it, double it so sprintf() doesn't break
5209 if ($a) {
5210 $a = clean_getstring_data( $a );
5213 /// Define the two or three major locations of language strings for this module
5214 $locations = array();
5216 if (!empty($extralocations)) { // Calling code has a good idea where to look
5217 if (is_array($extralocations)) {
5218 $locations += $extralocations;
5219 } else if (is_string($extralocations)) {
5220 $locations[] = $extralocations;
5221 } else {
5222 debugging('Bad lang path provided');
5226 if (isset($CFG->running_installer)) {
5227 $module = 'installer';
5228 $filetocheck = 'installer.php';
5229 $locations[] = $CFG->dirroot.'/install/lang/';
5230 $locations[] = $CFG->dataroot.'/lang/';
5231 $locations[] = $CFG->dirroot.'/lang/';
5232 $defaultlang = 'en_utf8';
5233 } else {
5234 $locations[] = $CFG->dataroot.'/lang/';
5235 $locations[] = $CFG->dirroot.'/lang/';
5236 $locations[] = $CFG->dirroot.'/local/lang/';
5239 /// Add extra places to look for strings for particular plugin types.
5240 $rules = places_to_search_for_lang_strings();
5241 $exceptions = $rules['__exceptions'];
5242 unset($rules['__exceptions']);
5244 if (!in_array($module, $exceptions)) {
5245 $dividerpos = strpos($module, '_');
5246 if ($dividerpos === false) {
5247 $type = '';
5248 $plugin = $module;
5249 } else {
5250 $type = substr($module, 0, $dividerpos + 1);
5251 $plugin = substr($module, $dividerpos + 1);
5253 if (!empty($rules[$type])) {
5254 foreach ($rules[$type] as $location) {
5255 $locations[] = $CFG->dirroot . "/$location/$plugin/lang/";
5260 /// First check all the normal locations for the string in the current language
5261 $resultstring = '';
5262 foreach ($locations as $location) {
5263 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
5264 if (file_exists($locallangfile)) {
5265 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5266 if (eval($result) === FALSE) {
5267 trigger_error('Lang error: '.$identifier.':'.$locallangfile, E_USER_NOTICE);
5269 return $resultstring;
5272 //if local directory not found, or particular string does not exist in local direcotry
5273 $langfile = $location.$lang.'/'.$module.'.php';
5274 if (file_exists($langfile)) {
5275 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5276 if (eval($result) === FALSE) {
5277 trigger_error('Lang error: '.$identifier.':'.$langfile, E_USER_NOTICE);
5279 return $resultstring;
5284 /// If the preferred language was English (utf8) we can abort now
5285 /// saving some checks beacuse it's the only "root" lang
5286 if ($lang == 'en_utf8') {
5287 return '[['. $identifier .']]';
5290 /// Is a parent language defined? If so, try to find this string in a parent language file
5292 foreach ($locations as $location) {
5293 $langfile = $location.$lang.'/'.$filetocheck;
5294 if (file_exists($langfile)) {
5295 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
5296 eval($result);
5297 if (!empty($parentlang)) { // found it!
5299 //first, see if there's a local file for parent
5300 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
5301 if (file_exists($locallangfile)) {
5302 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5303 eval($result);
5304 return $resultstring;
5308 //if local directory not found, or particular string does not exist in local direcotry
5309 $langfile = $location.$parentlang.'/'.$module.'.php';
5310 if (file_exists($langfile)) {
5311 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5312 eval($result);
5313 return $resultstring;
5321 /// Our only remaining option is to try English
5323 foreach ($locations as $location) {
5324 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
5325 if (file_exists($locallangfile)) {
5326 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5327 eval($result);
5328 return $resultstring;
5332 //if local_en not found, or string not found in local_en
5333 $langfile = $location.$defaultlang.'/'.$module.'.php';
5335 if (file_exists($langfile)) {
5336 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5337 eval($result);
5338 return $resultstring;
5343 /// And, because under 1.6 en is defined as en_utf8 child, me must try
5344 /// if it hasn't been queried before.
5345 if ($defaultlang == 'en') {
5346 $defaultlang = 'en_utf8';
5347 foreach ($locations as $location) {
5348 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
5349 if (file_exists($locallangfile)) {
5350 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5351 eval($result);
5352 return $resultstring;
5356 //if local_en not found, or string not found in local_en
5357 $langfile = $location.$defaultlang.'/'.$module.'.php';
5359 if (file_exists($langfile)) {
5360 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5361 eval($result);
5362 return $resultstring;
5368 return '[['.$identifier.']]'; // Last resort
5372 * This function is only used from {@link get_string()}.
5374 * @internal Only used from get_string, not meant to be public API
5375 * @param string $identifier ?
5376 * @param string $langfile ?
5377 * @param string $destination ?
5378 * @return string|false ?
5379 * @staticvar array $strings Localized strings
5380 * @access private
5381 * @todo Finish documenting this function.
5383 function get_string_from_file($identifier, $langfile, $destination) {
5385 static $strings; // Keep the strings cached in memory.
5387 if (empty($strings[$langfile])) {
5388 $string = array();
5389 include ($langfile);
5390 $strings[$langfile] = $string;
5391 } else {
5392 $string = &$strings[$langfile];
5395 if (!isset ($string[$identifier])) {
5396 return false;
5399 return $destination .'= sprintf("'. $string[$identifier] .'");';
5403 * Converts an array of strings to their localized value.
5405 * @param array $array An array of strings
5406 * @param string $module The language module that these strings can be found in.
5407 * @return string
5409 function get_strings($array, $module='') {
5411 $string = NULL;
5412 foreach ($array as $item) {
5413 $string->$item = get_string($item, $module);
5415 return $string;
5419 * Returns a list of language codes and their full names
5420 * hides the _local files from everyone.
5421 * @param bool refreshcache force refreshing of lang cache
5422 * @param bool returnall ignore langlist, return all languages available
5423 * @return array An associative array with contents in the form of LanguageCode => LanguageName
5425 function get_list_of_languages($refreshcache=false, $returnall=false) {
5427 global $CFG;
5429 $languages = array();
5431 $filetocheck = 'langconfig.php';
5433 if (!$refreshcache && !$returnall && !empty($CFG->langcache) && file_exists($CFG->dataroot .'/cache/languages')) {
5434 /// read available langs from cache
5436 $lines = file($CFG->dataroot .'/cache/languages');
5437 foreach ($lines as $line) {
5438 $line = trim($line);
5439 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
5440 $languages[$matches[1]] = $matches[2];
5443 unset($lines); unset($line); unset($matches);
5444 return $languages;
5447 if (!$returnall && !empty($CFG->langlist)) {
5448 /// return only languages allowed in langlist admin setting
5450 $langlist = explode(',', $CFG->langlist);
5451 // fix short lang names first - non existing langs are skipped anyway...
5452 foreach ($langlist as $lang) {
5453 if (strpos($lang, '_utf8') === false) {
5454 $langlist[] = $lang.'_utf8';
5457 // find existing langs from langlist
5458 foreach ($langlist as $lang) {
5459 $lang = trim($lang); //Just trim spaces to be a bit more permissive
5460 if (strstr($lang, '_local')!==false) {
5461 continue;
5463 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
5464 $shortlang = substr($lang, 0, -5);
5465 } else {
5466 $shortlang = $lang;
5468 /// Search under dirroot/lang
5469 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
5470 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
5471 if (!empty($string['thislanguage'])) {
5472 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
5474 unset($string);
5476 /// And moodledata/lang
5477 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
5478 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
5479 if (!empty($string['thislanguage'])) {
5480 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
5482 unset($string);
5486 } else {
5487 /// return all languages available in system
5488 /// Fetch langs from moodle/lang directory
5489 $langdirs = get_list_of_plugins('lang');
5490 /// Fetch langs from moodledata/lang directory
5491 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot);
5492 /// Merge both lists of langs
5493 $langdirs = array_merge($langdirs, $langdirs2);
5494 /// Sort all
5495 asort($langdirs);
5496 /// Get some info from each lang (first from moodledata, then from moodle)
5497 foreach ($langdirs as $lang) {
5498 if (strstr($lang, '_local')!==false) {
5499 continue;
5501 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
5502 $shortlang = substr($lang, 0, -5);
5503 } else {
5504 $shortlang = $lang;
5506 /// Search under moodledata/lang
5507 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
5508 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
5509 if (!empty($string['thislanguage'])) {
5510 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
5512 unset($string);
5514 /// And dirroot/lang
5515 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
5516 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
5517 if (!empty($string['thislanguage'])) {
5518 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
5520 unset($string);
5525 if ($refreshcache && !empty($CFG->langcache)) {
5526 if ($returnall) {
5527 // we have a list of all langs only, just delete old cache
5528 @unlink($CFG->dataroot.'/cache/languages');
5530 } else {
5531 // store the list of allowed languages
5532 if ($file = fopen($CFG->dataroot .'/cache/languages', 'w')) {
5533 foreach ($languages as $key => $value) {
5534 fwrite($file, "$key $value\n");
5536 fclose($file);
5541 return $languages;
5545 * Returns a list of charset codes. It's hardcoded, so they should be added manually
5546 * (cheking that such charset is supported by the texlib library!)
5548 * @return array And associative array with contents in the form of charset => charset
5550 function get_list_of_charsets() {
5552 $charsets = array(
5553 'EUC-JP' => 'EUC-JP',
5554 'ISO-2022-JP'=> 'ISO-2022-JP',
5555 'ISO-8859-1' => 'ISO-8859-1',
5556 'SHIFT-JIS' => 'SHIFT-JIS',
5557 'GB2312' => 'GB2312',
5558 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
5559 'UTF-8' => 'UTF-8');
5561 asort($charsets);
5563 return $charsets;
5567 * Returns a list of country names in the current language
5569 * @uses $CFG
5570 * @uses $USER
5571 * @return array
5573 function get_list_of_countries() {
5574 global $CFG, $USER;
5576 $lang = current_language();
5578 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php') &&
5579 !file_exists($CFG->dataroot.'/lang/'. $lang .'/countries.php')) {
5580 if ($parentlang = get_string('parentlanguage')) {
5581 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/countries.php') ||
5582 file_exists($CFG->dataroot.'/lang/'. $parentlang .'/countries.php')) {
5583 $lang = $parentlang;
5584 } else {
5585 $lang = 'en_utf8'; // countries.php must exist in this pack
5587 } else {
5588 $lang = 'en_utf8'; // countries.php must exist in this pack
5592 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/countries.php')) {
5593 include($CFG->dataroot .'/lang/'. $lang .'/countries.php');
5594 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
5595 include($CFG->dirroot .'/lang/'. $lang .'/countries.php');
5598 if (!empty($string)) {
5599 uasort($string, 'strcoll');
5602 return $string;
5606 * Returns a list of valid and compatible themes
5608 * @uses $CFG
5609 * @return array
5611 function get_list_of_themes() {
5613 global $CFG;
5615 $themes = array();
5617 if (!empty($CFG->themelist)) { // use admin's list of themes
5618 $themelist = explode(',', $CFG->themelist);
5619 } else {
5620 $themelist = get_list_of_plugins("theme");
5623 foreach ($themelist as $key => $theme) {
5624 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
5625 continue;
5627 $THEME = new object(); // Note this is not the global one!! :-)
5628 include("$CFG->themedir/$theme/config.php");
5629 if (!isset($THEME->sheets)) { // Not a valid 1.5 theme
5630 continue;
5632 $themes[$theme] = $theme;
5634 asort($themes);
5636 return $themes;
5641 * Returns a list of picture names in the current or specified language
5643 * @uses $CFG
5644 * @return array
5646 function get_list_of_pixnames($lang = '') {
5647 global $CFG;
5649 if (empty($lang)) {
5650 $lang = current_language();
5653 $string = array();
5655 $path = $CFG->dirroot .'/lang/en_utf8/pix.php'; // always exists
5657 if (file_exists($CFG->dataroot .'/lang/'. $lang .'_local/pix.php')) {
5658 $path = $CFG->dataroot .'/lang/'. $lang .'_local/pix.php';
5660 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
5661 $path = $CFG->dirroot .'/lang/'. $lang .'/pix.php';
5663 } else if (file_exists($CFG->dataroot .'/lang/'. $lang .'/pix.php')) {
5664 $path = $CFG->dataroot .'/lang/'. $lang .'/pix.php';
5666 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
5667 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
5670 include($path);
5672 return $string;
5676 * Returns a list of timezones in the current language
5678 * @uses $CFG
5679 * @return array
5681 function get_list_of_timezones() {
5682 global $CFG;
5684 static $timezones;
5686 if (!empty($timezones)) { // This function has been called recently
5687 return $timezones;
5690 $timezones = array();
5692 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix.'timezone GROUP BY name')) {
5693 foreach($rawtimezones as $timezone) {
5694 if (!empty($timezone->name)) {
5695 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
5696 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
5697 $timezones[$timezone->name] = $timezone->name;
5703 asort($timezones);
5705 for ($i = -13; $i <= 13; $i += .5) {
5706 $tzstring = 'UTC';
5707 if ($i < 0) {
5708 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
5709 } else if ($i > 0) {
5710 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
5711 } else {
5712 $timezones[sprintf("%.1f", $i)] = $tzstring;
5716 return $timezones;
5720 * Returns a list of currencies in the current language
5722 * @uses $CFG
5723 * @uses $USER
5724 * @return array
5726 function get_list_of_currencies() {
5727 global $CFG, $USER;
5729 $lang = current_language();
5731 if (!file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
5732 if ($parentlang = get_string('parentlanguage')) {
5733 if (file_exists($CFG->dataroot .'/lang/'. $parentlang .'/currencies.php')) {
5734 $lang = $parentlang;
5735 } else {
5736 $lang = 'en_utf8'; // currencies.php must exist in this pack
5738 } else {
5739 $lang = 'en_utf8'; // currencies.php must exist in this pack
5743 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
5744 include_once($CFG->dataroot .'/lang/'. $lang .'/currencies.php');
5745 } else { //if en_utf8 is not installed in dataroot
5746 include_once($CFG->dirroot .'/lang/'. $lang .'/currencies.php');
5749 if (!empty($string)) {
5750 asort($string);
5753 return $string;
5757 /// ENCRYPTION ////////////////////////////////////////////////
5760 * rc4encrypt
5762 * @param string $data ?
5763 * @return string
5764 * @todo Finish documenting this function
5766 function rc4encrypt($data) {
5767 $password = 'nfgjeingjk';
5768 return endecrypt($password, $data, '');
5772 * rc4decrypt
5774 * @param string $data ?
5775 * @return string
5776 * @todo Finish documenting this function
5778 function rc4decrypt($data) {
5779 $password = 'nfgjeingjk';
5780 return endecrypt($password, $data, 'de');
5784 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5786 * @param string $pwd ?
5787 * @param string $data ?
5788 * @param string $case ?
5789 * @return string
5790 * @todo Finish documenting this function
5792 function endecrypt ($pwd, $data, $case) {
5794 if ($case == 'de') {
5795 $data = urldecode($data);
5798 $key[] = '';
5799 $box[] = '';
5800 $temp_swap = '';
5801 $pwd_length = 0;
5803 $pwd_length = strlen($pwd);
5805 for ($i = 0; $i <= 255; $i++) {
5806 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
5807 $box[$i] = $i;
5810 $x = 0;
5812 for ($i = 0; $i <= 255; $i++) {
5813 $x = ($x + $box[$i] + $key[$i]) % 256;
5814 $temp_swap = $box[$i];
5815 $box[$i] = $box[$x];
5816 $box[$x] = $temp_swap;
5819 $temp = '';
5820 $k = '';
5822 $cipherby = '';
5823 $cipher = '';
5825 $a = 0;
5826 $j = 0;
5828 for ($i = 0; $i < strlen($data); $i++) {
5829 $a = ($a + 1) % 256;
5830 $j = ($j + $box[$a]) % 256;
5831 $temp = $box[$a];
5832 $box[$a] = $box[$j];
5833 $box[$j] = $temp;
5834 $k = $box[(($box[$a] + $box[$j]) % 256)];
5835 $cipherby = ord(substr($data, $i, 1)) ^ $k;
5836 $cipher .= chr($cipherby);
5839 if ($case == 'de') {
5840 $cipher = urldecode(urlencode($cipher));
5841 } else {
5842 $cipher = urlencode($cipher);
5845 return $cipher;
5849 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5853 * Call this function to add an event to the calendar table
5854 * and to call any calendar plugins
5856 * @uses $CFG
5857 * @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:
5858 * <ul>
5859 * <li><b>$event->name</b> - Name for the event
5860 * <li><b>$event->description</b> - Description of the event (defaults to '')
5861 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5862 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5863 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5864 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5865 * <li><b>$event->modulename</b> - Name of the module that creates this event
5866 * <li><b>$event->instance</b> - Instance of the module that owns this event
5867 * <li><b>$event->eventtype</b> - The type info together with the module info could
5868 * be used by calendar plugins to decide how to display event
5869 * <li><b>$event->timestart</b>- Timestamp for start of event
5870 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5871 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5872 * </ul>
5873 * @return int The id number of the resulting record
5875 function add_event($event) {
5877 global $CFG;
5879 $event->timemodified = time();
5881 if (!$event->id = insert_record('event', $event)) {
5882 return false;
5885 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
5886 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5887 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5888 $calendar_add_event = $CFG->calendar.'_add_event';
5889 if (function_exists($calendar_add_event)) {
5890 $calendar_add_event($event);
5895 return $event->id;
5899 * Call this function to update an event in the calendar table
5900 * the event will be identified by the id field of the $event object.
5902 * @uses $CFG
5903 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5904 * @return bool
5906 function update_event($event) {
5908 global $CFG;
5910 $event->timemodified = time();
5912 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5913 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5914 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5915 $calendar_update_event = $CFG->calendar.'_update_event';
5916 if (function_exists($calendar_update_event)) {
5917 $calendar_update_event($event);
5921 return update_record('event', $event);
5925 * Call this function to delete the event with id $id from calendar table.
5927 * @uses $CFG
5928 * @param int $id The id of an event from the 'calendar' table.
5929 * @return array An associative array with the results from the SQL call.
5930 * @todo Verify return type
5932 function delete_event($id) {
5934 global $CFG;
5936 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
5937 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5938 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5939 $calendar_delete_event = $CFG->calendar.'_delete_event';
5940 if (function_exists($calendar_delete_event)) {
5941 $calendar_delete_event($id);
5945 return delete_records('event', 'id', $id);
5949 * Call this function to hide an event in the calendar table
5950 * the event will be identified by the id field of the $event object.
5952 * @uses $CFG
5953 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5954 * @return array An associative array with the results from the SQL call.
5955 * @todo Verify return type
5957 function hide_event($event) {
5958 global $CFG;
5960 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5961 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5962 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5963 $calendar_hide_event = $CFG->calendar.'_hide_event';
5964 if (function_exists($calendar_hide_event)) {
5965 $calendar_hide_event($event);
5969 return set_field('event', 'visible', 0, 'id', $event->id);
5973 * Call this function to unhide an event in the calendar table
5974 * the event will be identified by the id field of the $event object.
5976 * @uses $CFG
5977 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5978 * @return array An associative array with the results from the SQL call.
5979 * @todo Verify return type
5981 function show_event($event) {
5982 global $CFG;
5984 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5985 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5986 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5987 $calendar_show_event = $CFG->calendar.'_show_event';
5988 if (function_exists($calendar_show_event)) {
5989 $calendar_show_event($event);
5993 return set_field('event', 'visible', 1, 'id', $event->id);
5997 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
6000 * Lists plugin directories within some directory
6002 * @uses $CFG
6003 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
6004 * @param string $exclude dir name to exclude from the list (defaults to none)
6005 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
6006 * @return array of plugins found under the requested parameters
6008 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
6010 global $CFG;
6012 $plugins = array();
6014 if (empty($basedir)) {
6016 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
6017 switch ($plugin) {
6018 case "theme":
6019 $basedir = $CFG->themedir;
6020 break;
6022 default:
6023 $basedir = $CFG->dirroot .'/'. $plugin;
6026 } else {
6027 $basedir = $basedir .'/'. $plugin;
6030 if (file_exists($basedir) && filetype($basedir) == 'dir') {
6031 $dirhandle = opendir($basedir);
6032 while (false !== ($dir = readdir($dirhandle))) {
6033 $firstchar = substr($dir, 0, 1);
6034 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
6035 continue;
6037 if (filetype($basedir .'/'. $dir) != 'dir') {
6038 continue;
6040 $plugins[] = $dir;
6042 closedir($dirhandle);
6044 if ($plugins) {
6045 asort($plugins);
6047 return $plugins;
6051 * Returns true if the current version of PHP is greater that the specified one.
6053 * @param string $version The version of php being tested.
6054 * @return bool
6056 function check_php_version($version='4.1.0') {
6057 return (version_compare(phpversion(), $version) >= 0);
6061 * Checks to see if is the browser operating system matches the specified
6062 * brand.
6064 * Known brand: 'Windows','Linux','Macintosh','SGI','SunOS','HP-UX'
6066 * @uses $_SERVER
6067 * @param string $brand The operating system identifier being tested
6068 * @return bool true if the given brand below to the detected operating system
6070 function check_browser_operating_system($brand) {
6071 if (empty($_SERVER['HTTP_USER_AGENT'])) {
6072 return false;
6075 if (preg_match("/$brand/i", $_SERVER['HTTP_USER_AGENT'])) {
6076 return true;
6079 return false;
6083 * Checks to see if is a browser matches the specified
6084 * brand and is equal or better version.
6086 * @uses $_SERVER
6087 * @param string $brand The browser identifier being tested
6088 * @param int $version The version of the browser
6089 * @return bool true if the given version is below that of the detected browser
6091 function check_browser_version($brand='MSIE', $version=5.5) {
6092 if (empty($_SERVER['HTTP_USER_AGENT'])) {
6093 return false;
6096 $agent = $_SERVER['HTTP_USER_AGENT'];
6098 switch ($brand) {
6100 case 'Camino': /// Mozilla Firefox browsers
6102 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
6103 if (version_compare($match[1], $version) >= 0) {
6104 return true;
6107 break;
6110 case 'Firefox': /// Mozilla Firefox browsers
6112 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
6113 if (version_compare($match[1], $version) >= 0) {
6114 return true;
6117 break;
6120 case 'Gecko': /// Gecko based browsers
6122 if (substr_count($agent, 'Camino')) {
6123 // MacOS X Camino support
6124 $version = 20041110;
6127 // the proper string - Gecko/CCYYMMDD Vendor/Version
6128 // Faster version and work-a-round No IDN problem.
6129 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
6130 if ($match[1] > $version) {
6131 return true;
6134 break;
6137 case 'MSIE': /// Internet Explorer
6139 if (strpos($agent, 'Opera')) { // Reject Opera
6140 return false;
6142 $string = explode(';', $agent);
6143 if (!isset($string[1])) {
6144 return false;
6146 $string = explode(' ', trim($string[1]));
6147 if (!isset($string[0]) and !isset($string[1])) {
6148 return false;
6150 if ($string[0] == $brand and (float)$string[1] >= $version ) {
6151 return true;
6153 break;
6155 case 'Opera': /// Opera
6157 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
6158 if (version_compare($match[1], $version) >= 0) {
6159 return true;
6162 break;
6164 case 'Safari': /// Safari
6165 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
6166 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
6167 return false;
6168 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
6169 return false;
6170 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
6171 return false;
6174 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
6175 if (version_compare($match[1], $version) >= 0) {
6176 return true;
6180 break;
6184 return false;
6188 * This function makes the return value of ini_get consistent if you are
6189 * setting server directives through the .htaccess file in apache.
6190 * Current behavior for value set from php.ini On = 1, Off = [blank]
6191 * Current behavior for value set from .htaccess On = On, Off = Off
6192 * Contributed by jdell @ unr.edu
6194 * @param string $ini_get_arg ?
6195 * @return bool
6196 * @todo Finish documenting this function
6198 function ini_get_bool($ini_get_arg) {
6199 $temp = ini_get($ini_get_arg);
6201 if ($temp == '1' or strtolower($temp) == 'on') {
6202 return true;
6204 return false;
6208 * Compatibility stub to provide backward compatibility
6210 * Determines if the HTML editor is enabled.
6211 * @deprecated Use {@link can_use_html_editor()} instead.
6213 function can_use_richtext_editor() {
6214 return can_use_html_editor();
6218 * Determines if the HTML editor is enabled.
6220 * This depends on site and user
6221 * settings, as well as the current browser being used.
6223 * @return string|false Returns false if editor is not being used, otherwise
6224 * returns 'MSIE' or 'Gecko'.
6226 function can_use_html_editor() {
6227 global $USER, $CFG;
6229 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
6230 if (check_browser_version('MSIE', 5.5)) {
6231 return 'MSIE';
6232 } else if (check_browser_version('Gecko', 20030516)) {
6233 return 'Gecko';
6236 return false;
6240 * Hack to find out the GD version by parsing phpinfo output
6242 * @return int GD version (1, 2, or 0)
6244 function check_gd_version() {
6245 $gdversion = 0;
6247 if (function_exists('gd_info')){
6248 $gd_info = gd_info();
6249 if (substr_count($gd_info['GD Version'], '2.')) {
6250 $gdversion = 2;
6251 } else if (substr_count($gd_info['GD Version'], '1.')) {
6252 $gdversion = 1;
6255 } else {
6256 ob_start();
6257 phpinfo(INFO_MODULES);
6258 $phpinfo = ob_get_contents();
6259 ob_end_clean();
6261 $phpinfo = explode("\n", $phpinfo);
6264 foreach ($phpinfo as $text) {
6265 $parts = explode('</td>', $text);
6266 foreach ($parts as $key => $val) {
6267 $parts[$key] = trim(strip_tags($val));
6269 if ($parts[0] == 'GD Version') {
6270 if (substr_count($parts[1], '2.0')) {
6271 $parts[1] = '2.0';
6273 $gdversion = intval($parts[1]);
6278 return $gdversion; // 1, 2 or 0
6282 * Determine if moodle installation requires update
6284 * Checks version numbers of main code and all modules to see
6285 * if there are any mismatches
6287 * @uses $CFG
6288 * @return bool
6290 function moodle_needs_upgrading() {
6291 global $CFG;
6293 $version = null;
6294 include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
6295 if ($CFG->version) {
6296 if ($version > $CFG->version) {
6297 return true;
6299 if ($mods = get_list_of_plugins('mod')) {
6300 foreach ($mods as $mod) {
6301 $fullmod = $CFG->dirroot .'/mod/'. $mod;
6302 $module = new object();
6303 if (!is_readable($fullmod .'/version.php')) {
6304 notify('Module "'. $mod .'" is not readable - check permissions');
6305 continue;
6307 include_once($fullmod .'/version.php'); # defines $module with version etc
6308 if ($currmodule = get_record('modules', 'name', $mod)) {
6309 if ($module->version > $currmodule->version) {
6310 return true;
6315 } else {
6316 return true;
6318 return false;
6322 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
6325 * Notify admin users or admin user of any failed logins (since last notification).
6327 * Note that this function must be only executed from the cron script
6328 * It uses the cache_flags system to store temporary records, deleting them
6329 * by name before finishing
6331 * @uses $CFG
6332 * @uses $db
6333 * @uses HOURSECS
6335 function notify_login_failures() {
6336 global $CFG, $db;
6338 switch ($CFG->notifyloginfailures) {
6339 case 'mainadmin' :
6340 $recip = array(get_admin());
6341 break;
6342 case 'alladmins':
6343 $recip = get_admins();
6344 break;
6347 if (empty($CFG->lastnotifyfailure)) {
6348 $CFG->lastnotifyfailure=0;
6351 // we need to deal with the threshold stuff first.
6352 if (empty($CFG->notifyloginthreshold)) {
6353 $CFG->notifyloginthreshold = 10; // default to something sensible.
6356 /// Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
6357 /// and insert them into the cache_flags temp table
6358 $iprs = get_recordset_sql("SELECT ip, count(*)
6359 FROM {$CFG->prefix}log
6360 WHERE module = 'login'
6361 AND action = 'error'
6362 AND time > $CFG->lastnotifyfailure
6363 GROUP BY ip
6364 HAVING count(*) >= $CFG->notifyloginthreshold");
6365 while ($iprec = rs_fetch_next_record($iprs)) {
6366 if (!empty($iprec->ip)) {
6367 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
6370 rs_close($iprs);
6372 /// Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
6373 /// and insert them into the cache_flags temp table
6374 $infors = get_recordset_sql("SELECT info, count(*)
6375 FROM {$CFG->prefix}log
6376 WHERE module = 'login'
6377 AND action = 'error'
6378 AND time > $CFG->lastnotifyfailure
6379 GROUP BY info
6380 HAVING count(*) >= $CFG->notifyloginthreshold");
6381 while ($inforec = rs_fetch_next_record($infors)) {
6382 if (!empty($inforec->info)) {
6383 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
6386 rs_close($infors);
6388 /// Now, select all the login error logged records belonging to the ips and infos
6389 /// since lastnotifyfailure, that we have stored in the cache_flags table
6390 $logsrs = get_recordset_sql("SELECT l.*, u.firstname, u.lastname
6391 FROM {$CFG->prefix}log l
6392 JOIN {$CFG->prefix}cache_flags cf ON (l.ip = cf.name)
6393 LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
6394 WHERE l.module = 'login'
6395 AND l.action = 'error'
6396 AND l.time > $CFG->lastnotifyfailure
6397 AND cf.flagtype = 'login_failure_by_ip'
6398 UNION ALL
6399 SELECT l.*, u.firstname, u.lastname
6400 FROM {$CFG->prefix}log l
6401 JOIN {$CFG->prefix}cache_flags cf ON (l.info = cf.name)
6402 LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
6403 WHERE l.module = 'login'
6404 AND l.action = 'error'
6405 AND l.time > $CFG->lastnotifyfailure
6406 AND cf.flagtype = 'login_failure_by_info'
6407 ORDER BY time DESC");
6409 /// Init some variables
6410 $count = 0;
6411 $messages = '';
6412 /// Iterate over the logs recordset
6413 while ($log = rs_fetch_next_record($logsrs)) {
6414 $log->time = userdate($log->time);
6415 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
6416 $count++;
6418 rs_close($logsrs);
6420 /// If we haven't run in the last hour and
6421 /// we have something useful to report and we
6422 /// are actually supposed to be reporting to somebody
6423 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
6424 $site = get_site();
6425 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
6426 /// Calculate the complete body of notification (start + messages + end)
6427 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
6428 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
6429 $messages .
6430 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
6432 /// For each destination, send mail
6433 foreach ($recip as $admin) {
6434 mtrace('Emailing '. $admin->username .' about '. $count .' failed login attempts');
6435 email_to_user($admin,get_admin(), $subject, $body);
6438 /// Update lastnotifyfailure with current time
6439 set_config('lastnotifyfailure', time());
6442 /// Finally, delete all the temp records we have created in cache_flags
6443 delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
6447 * moodle_setlocale
6449 * @uses $CFG
6450 * @param string $locale ?
6451 * @todo Finish documenting this function
6453 function moodle_setlocale($locale='') {
6455 global $CFG;
6457 static $currentlocale = ''; // last locale caching
6459 $oldlocale = $currentlocale;
6461 /// Fetch the correct locale based on ostype
6462 if($CFG->ostype == 'WINDOWS') {
6463 $stringtofetch = 'localewin';
6464 } else {
6465 $stringtofetch = 'locale';
6468 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
6469 if (!empty($locale)) {
6470 $currentlocale = $locale;
6471 } else if (!empty($CFG->locale)) { // override locale for all language packs
6472 $currentlocale = $CFG->locale;
6473 } else {
6474 $currentlocale = get_string($stringtofetch);
6477 /// do nothing if locale already set up
6478 if ($oldlocale == $currentlocale) {
6479 return;
6482 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
6483 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
6484 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
6486 /// Get current values
6487 $monetary= setlocale (LC_MONETARY, 0);
6488 $numeric = setlocale (LC_NUMERIC, 0);
6489 $ctype = setlocale (LC_CTYPE, 0);
6490 if ($CFG->ostype != 'WINDOWS') {
6491 $messages= setlocale (LC_MESSAGES, 0);
6493 /// Set locale to all
6494 setlocale (LC_ALL, $currentlocale);
6495 /// Set old values
6496 setlocale (LC_MONETARY, $monetary);
6497 setlocale (LC_NUMERIC, $numeric);
6498 if ($CFG->ostype != 'WINDOWS') {
6499 setlocale (LC_MESSAGES, $messages);
6501 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
6502 setlocale (LC_CTYPE, $ctype);
6507 * Converts string to lowercase using most compatible function available.
6509 * @param string $string The string to convert to all lowercase characters.
6510 * @param string $encoding The encoding on the string.
6511 * @return string
6512 * @todo Add examples of calling this function with/without encoding types
6513 * @deprecated Use textlib->strtolower($text) instead.
6515 function moodle_strtolower ($string, $encoding='') {
6517 //If not specified use utf8
6518 if (empty($encoding)) {
6519 $encoding = 'UTF-8';
6521 //Use text services
6522 $textlib = textlib_get_instance();
6524 return $textlib->strtolower($string, $encoding);
6528 * Count words in a string.
6530 * Words are defined as things between whitespace.
6532 * @param string $string The text to be searched for words.
6533 * @return int The count of words in the specified string
6535 function count_words($string) {
6536 $string = strip_tags($string);
6537 return count(preg_split("/\w\b/", $string)) - 1;
6540 /** Count letters in a string.
6542 * Letters are defined as chars not in tags and different from whitespace.
6544 * @param string $string The text to be searched for letters.
6545 * @return int The count of letters in the specified text.
6547 function count_letters($string) {
6548 /// Loading the textlib singleton instance. We are going to need it.
6549 $textlib = textlib_get_instance();
6551 $string = strip_tags($string); // Tags are out now
6552 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
6554 return $textlib->strlen($string);
6558 * Generate and return a random string of the specified length.
6560 * @param int $length The length of the string to be created.
6561 * @return string
6563 function random_string ($length=15) {
6564 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
6565 $pool .= 'abcdefghijklmnopqrstuvwxyz';
6566 $pool .= '0123456789';
6567 $poollen = strlen($pool);
6568 mt_srand ((double) microtime() * 1000000);
6569 $string = '';
6570 for ($i = 0; $i < $length; $i++) {
6571 $string .= substr($pool, (mt_rand()%($poollen)), 1);
6573 return $string;
6577 * Given some text (which may contain HTML) and an ideal length,
6578 * this function truncates the text neatly on a word boundary if possible
6579 * @param string $text - text to be shortened
6580 * @param int $ideal - ideal string length
6581 * @param boolean $exact if false, $text will not be cut mid-word
6582 * @return string $truncate - shortened string
6585 function shorten_text($text, $ideal=30, $exact = false) {
6587 global $CFG;
6588 $ending = '...';
6590 // if the plain text is shorter than the maximum length, return the whole text
6591 if (strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
6592 return $text;
6595 // splits all html-tags to scanable lines
6596 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
6598 $total_length = strlen($ending);
6599 $open_tags = array();
6600 $truncate = '';
6602 foreach ($lines as $line_matchings) {
6603 // if there is any html-tag in this line, handle it and add it (uncounted) to the output
6604 if (!empty($line_matchings[1])) {
6605 // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
6606 if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
6607 // do nothing
6608 // if tag is a closing tag (f.e. </b>)
6609 } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
6610 // delete tag from $open_tags list
6611 $pos = array_search($tag_matchings[1], array_reverse($open_tags, true)); // can have multiple exact same open tags, close the last one
6612 if ($pos !== false) {
6613 unset($open_tags[$pos]);
6615 // if tag is an opening tag (f.e. <b>)
6616 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
6617 // add tag to the beginning of $open_tags list
6618 array_unshift($open_tags, strtolower($tag_matchings[1]));
6620 // add html-tag to $truncate'd text
6621 $truncate .= $line_matchings[1];
6624 // calculate the length of the plain text part of the line; handle entities as one character
6625 $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
6626 if ($total_length+$content_length > $ideal) {
6627 // the number of characters which are left
6628 $left = $ideal - $total_length;
6629 $entities_length = 0;
6630 // search for html entities
6631 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)) {
6632 // calculate the real length of all entities in the legal range
6633 foreach ($entities[0] as $entity) {
6634 if ($entity[1]+1-$entities_length <= $left) {
6635 $left--;
6636 $entities_length += strlen($entity[0]);
6637 } else {
6638 // no more characters left
6639 break;
6643 $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
6644 // maximum lenght is reached, so get off the loop
6645 break;
6646 } else {
6647 $truncate .= $line_matchings[2];
6648 $total_length += $content_length;
6651 // if the maximum length is reached, get off the loop
6652 if($total_length >= $ideal) {
6653 break;
6657 // if the words shouldn't be cut in the middle...
6658 if (!$exact) {
6659 // ...search the last occurance of a space...
6660 for ($k=strlen($truncate);$k>0;$k--) {
6661 if (!empty($truncate[$k]) && ($char = $truncate[$k])) {
6662 if ($char == '.' or $char == ' ') {
6663 $breakpos = $k+1;
6664 break;
6665 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
6666 $breakpos = $k; // can be truncated at any UTF-8
6667 break; // character boundary.
6672 if (isset($breakpos)) {
6673 // ...and cut the text in this position
6674 $truncate = substr($truncate, 0, $breakpos);
6678 // add the defined ending to the text
6679 $truncate .= $ending;
6681 // close all unclosed html-tags
6682 foreach ($open_tags as $tag) {
6683 $truncate .= '</' . $tag . '>';
6686 return $truncate;
6691 * Given dates in seconds, how many weeks is the date from startdate
6692 * The first week is 1, the second 2 etc ...
6694 * @uses WEEKSECS
6695 * @param ? $startdate ?
6696 * @param ? $thedate ?
6697 * @return string
6698 * @todo Finish documenting this function
6700 function getweek ($startdate, $thedate) {
6701 if ($thedate < $startdate) { // error
6702 return 0;
6705 return floor(($thedate - $startdate) / WEEKSECS) + 1;
6709 * returns a randomly generated password of length $maxlen. inspired by
6710 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
6711 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
6713 * @param int $maxlen The maximum size of the password being generated.
6714 * @return string
6716 function generate_password($maxlen=10) {
6717 global $CFG;
6719 if (empty($CFG->passwordpolicy)) {
6720 $fillers = PASSWORD_DIGITS;
6721 $wordlist = file($CFG->wordlist);
6722 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6723 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6724 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
6725 $password = $word1 . $filler1 . $word2;
6726 } else {
6727 $maxlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
6728 $digits = $CFG->minpassworddigits;
6729 $lower = $CFG->minpasswordlower;
6730 $upper = $CFG->minpasswordupper;
6731 $nonalphanum = $CFG->minpasswordnonalphanum;
6732 $additional = $maxlen - ($lower + $upper + $digits + $nonalphanum);
6734 // Make sure we have enough characters to fulfill
6735 // complexity requirements
6736 $passworddigits = PASSWORD_DIGITS;
6737 while ($digits > strlen($passworddigits)) {
6738 $passworddigits .= PASSWORD_DIGITS;
6740 $passwordlower = PASSWORD_LOWER;
6741 while ($lower > strlen($passwordlower)) {
6742 $passwordlower .= PASSWORD_LOWER;
6744 $passwordupper = PASSWORD_UPPER;
6745 while ($upper > strlen($passwordupper)) {
6746 $passwordupper .= PASSWORD_UPPER;
6748 $passwordnonalphanum = PASSWORD_NONALPHANUM;
6749 while ($nonalphanum > strlen($passwordnonalphanum)) {
6750 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
6753 // Now mix and shuffle it all
6754 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
6755 substr(str_shuffle ($passwordupper), 0, $upper) .
6756 substr(str_shuffle ($passworddigits), 0, $digits) .
6757 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
6758 substr(str_shuffle ($passwordlower .
6759 $passwordupper .
6760 $passworddigits .
6761 $passwordnonalphanum), 0 , $additional));
6764 return substr ($password, 0, $maxlen);
6768 * Given a float, prints it nicely.
6769 * Localized floats must not be used in calculations!
6771 * @param float $flaot The float to print
6772 * @param int $places The number of decimal places to print.
6773 * @param bool $localized use localized decimal separator
6774 * @return string locale float
6776 function format_float($float, $decimalpoints=1, $localized=true) {
6777 if (is_null($float)) {
6778 return '';
6780 if ($localized) {
6781 return number_format($float, $decimalpoints, get_string('decsep'), '');
6782 } else {
6783 return number_format($float, $decimalpoints, '.', '');
6788 * Converts locale specific floating point/comma number back to standard PHP float value
6789 * Do NOT try to do any math operations before this conversion on any user submitted floats!
6791 * @param string $locale_float locale aware float representation
6793 function unformat_float($locale_float) {
6794 $locale_float = trim($locale_float);
6796 if ($locale_float == '') {
6797 return null;
6800 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
6802 return (float)str_replace(get_string('decsep'), '.', $locale_float);
6806 * Given a simple array, this shuffles it up just like shuffle()
6807 * Unlike PHP's shuffle() this function works on any machine.
6809 * @param array $array The array to be rearranged
6810 * @return array
6812 function swapshuffle($array) {
6814 srand ((double) microtime() * 10000000);
6815 $last = count($array) - 1;
6816 for ($i=0;$i<=$last;$i++) {
6817 $from = rand(0,$last);
6818 $curr = $array[$i];
6819 $array[$i] = $array[$from];
6820 $array[$from] = $curr;
6822 return $array;
6826 * Like {@link swapshuffle()}, but works on associative arrays
6828 * @param array $array The associative array to be rearranged
6829 * @return array
6831 function swapshuffle_assoc($array) {
6833 $newarray = array();
6834 $newkeys = swapshuffle(array_keys($array));
6836 foreach ($newkeys as $newkey) {
6837 $newarray[$newkey] = $array[$newkey];
6839 return $newarray;
6843 * Given an arbitrary array, and a number of draws,
6844 * this function returns an array with that amount
6845 * of items. The indexes are retained.
6847 * @param array $array ?
6848 * @param ? $draws ?
6849 * @return ?
6850 * @todo Finish documenting this function
6852 function draw_rand_array($array, $draws) {
6853 srand ((double) microtime() * 10000000);
6855 $return = array();
6857 $last = count($array);
6859 if ($draws > $last) {
6860 $draws = $last;
6863 while ($draws > 0) {
6864 $last--;
6866 $keys = array_keys($array);
6867 $rand = rand(0, $last);
6869 $return[$keys[$rand]] = $array[$keys[$rand]];
6870 unset($array[$keys[$rand]]);
6872 $draws--;
6875 return $return;
6879 * microtime_diff
6881 * @param string $a ?
6882 * @param string $b ?
6883 * @return string
6884 * @todo Finish documenting this function
6886 function microtime_diff($a, $b) {
6887 list($a_dec, $a_sec) = explode(' ', $a);
6888 list($b_dec, $b_sec) = explode(' ', $b);
6889 return $b_sec - $a_sec + $b_dec - $a_dec;
6893 * Given a list (eg a,b,c,d,e) this function returns
6894 * an array of 1->a, 2->b, 3->c etc
6896 * @param array $list ?
6897 * @param string $separator ?
6898 * @todo Finish documenting this function
6900 function make_menu_from_list($list, $separator=',') {
6902 $array = array_reverse(explode($separator, $list), true);
6903 foreach ($array as $key => $item) {
6904 $outarray[$key+1] = trim($item);
6906 return $outarray;
6910 * Creates an array that represents all the current grades that
6911 * can be chosen using the given grading type. Negative numbers
6912 * are scales, zero is no grade, and positive numbers are maximum
6913 * grades.
6915 * @param int $gradingtype ?
6916 * return int
6917 * @todo Finish documenting this function
6919 function make_grades_menu($gradingtype) {
6920 $grades = array();
6921 if ($gradingtype < 0) {
6922 if ($scale = get_record('scale', 'id', - $gradingtype)) {
6923 return make_menu_from_list($scale->scale);
6925 } else if ($gradingtype > 0) {
6926 for ($i=$gradingtype; $i>=0; $i--) {
6927 $grades[$i] = $i .' / '. $gradingtype;
6929 return $grades;
6931 return $grades;
6935 * This function returns the nummber of activities
6936 * using scaleid in a courseid
6938 * @param int $courseid ?
6939 * @param int $scaleid ?
6940 * @return int
6941 * @todo Finish documenting this function
6943 function course_scale_used($courseid, $scaleid) {
6945 global $CFG;
6947 $return = 0;
6949 if (!empty($scaleid)) {
6950 if ($cms = get_course_mods($courseid)) {
6951 foreach ($cms as $cm) {
6952 //Check cm->name/lib.php exists
6953 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
6954 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
6955 $function_name = $cm->modname.'_scale_used';
6956 if (function_exists($function_name)) {
6957 if ($function_name($cm->instance,$scaleid)) {
6958 $return++;
6965 // check if any course grade item makes use of the scale
6966 $return += count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
6968 // check if any outcome in the course makes use of the scale
6969 $return += count_records_sql("SELECT COUNT(*)
6970 FROM {$CFG->prefix}grade_outcomes_courses goc,
6971 {$CFG->prefix}grade_outcomes go
6972 WHERE go.id = goc.outcomeid
6973 AND go.scaleid = $scaleid
6974 AND goc.courseid = $courseid");
6976 return $return;
6980 * This function returns the nummber of activities
6981 * using scaleid in the entire site
6983 * @param int $scaleid ?
6984 * @return int
6985 * @todo Finish documenting this function. Is return type correct?
6987 function site_scale_used($scaleid,&$courses) {
6989 global $CFG;
6991 $return = 0;
6993 if (!is_array($courses) || count($courses) == 0) {
6994 $courses = get_courses("all",false,"c.id,c.shortname");
6997 if (!empty($scaleid)) {
6998 if (is_array($courses) && count($courses) > 0) {
6999 foreach ($courses as $course) {
7000 $return += course_scale_used($course->id,$scaleid);
7004 return $return;
7008 * make_unique_id_code
7010 * @param string $extra ?
7011 * @return string
7012 * @todo Finish documenting this function
7014 function make_unique_id_code($extra='') {
7016 $hostname = 'unknownhost';
7017 if (!empty($_SERVER['HTTP_HOST'])) {
7018 $hostname = $_SERVER['HTTP_HOST'];
7019 } else if (!empty($_ENV['HTTP_HOST'])) {
7020 $hostname = $_ENV['HTTP_HOST'];
7021 } else if (!empty($_SERVER['SERVER_NAME'])) {
7022 $hostname = $_SERVER['SERVER_NAME'];
7023 } else if (!empty($_ENV['SERVER_NAME'])) {
7024 $hostname = $_ENV['SERVER_NAME'];
7027 $date = gmdate("ymdHis");
7029 $random = random_string(6);
7031 if ($extra) {
7032 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
7033 } else {
7034 return $hostname .'+'. $date .'+'. $random;
7040 * Function to check the passed address is within the passed subnet
7042 * The parameter is a comma separated string of subnet definitions.
7043 * Subnet strings can be in one of three formats:
7044 * 1: xxx.xxx.xxx.xxx/xx
7045 * 2: xxx.xxx
7046 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
7047 * Code for type 1 modified from user posted comments by mediator at
7048 * {@link http://au.php.net/manual/en/function.ip2long.php}
7050 * @param string $addr The address you are checking
7051 * @param string $subnetstr The string of subnet addresses
7052 * @return bool
7054 function address_in_subnet($addr, $subnetstr) {
7056 $subnets = explode(',', $subnetstr);
7057 $found = false;
7058 $addr = trim($addr);
7060 foreach ($subnets as $subnet) {
7061 $subnet = trim($subnet);
7062 if (strpos($subnet, '/') !== false) { /// type 1
7063 list($ip, $mask) = explode('/', $subnet);
7064 $mask = 0xffffffff << (32 - $mask);
7065 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
7066 } else if (strpos($subnet, '-') !== false) {/// type 3
7067 $subnetparts = explode('.', $subnet);
7068 $addrparts = explode('.', $addr);
7069 $subnetrange = explode('-', array_pop($subnetparts));
7070 if (count($subnetrange) == 2) {
7071 $lastaddrpart = array_pop($addrparts);
7072 $found = ($subnetparts == $addrparts &&
7073 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
7075 } else { /// type 2
7076 $found = (strpos($addr, $subnet) === 0);
7079 if ($found) {
7080 break;
7083 return $found;
7087 * This function sets the $HTTPSPAGEREQUIRED global
7088 * (used in some parts of moodle to change some links)
7089 * and calculate the proper wwwroot to be used
7091 * By using this function properly, we can ensure 100% https-ized pages
7092 * at our entire discretion (login, forgot_password, change_password)
7094 function httpsrequired() {
7096 global $CFG, $HTTPSPAGEREQUIRED;
7098 if (!empty($CFG->loginhttps)) {
7099 $HTTPSPAGEREQUIRED = true;
7100 $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
7101 $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
7103 // change theme URLs to https
7104 theme_setup();
7106 } else {
7107 $CFG->httpswwwroot = $CFG->wwwroot;
7108 $CFG->httpsthemewww = $CFG->themewww;
7113 * For outputting debugging info
7115 * @uses STDOUT
7116 * @param string $string ?
7117 * @param string $eol ?
7118 * @todo Finish documenting this function
7120 function mtrace($string, $eol="\n", $sleep=0) {
7122 if (defined('STDOUT')) {
7123 fwrite(STDOUT, $string.$eol);
7124 } else {
7125 echo $string . $eol;
7128 flush();
7130 //delay to keep message on user's screen in case of subsequent redirect
7131 if ($sleep) {
7132 sleep($sleep);
7136 //Replace 1 or more slashes or backslashes to 1 slash
7137 function cleardoubleslashes ($path) {
7138 return preg_replace('/(\/|\\\){1,}/','/',$path);
7141 function zip_files ($originalfiles, $destination) {
7142 //Zip an array of files/dirs to a destination zip file
7143 //Both parameters must be FULL paths to the files/dirs
7145 global $CFG;
7147 //Extract everything from destination
7148 $path_parts = pathinfo(cleardoubleslashes($destination));
7149 $destpath = $path_parts["dirname"]; //The path of the zip file
7150 $destfilename = $path_parts["basename"]; //The name of the zip file
7151 $extension = $path_parts["extension"]; //The extension of the file
7153 //If no file, error
7154 if (empty($destfilename)) {
7155 return false;
7158 //If no extension, add it
7159 if (empty($extension)) {
7160 $extension = 'zip';
7161 $destfilename = $destfilename.'.'.$extension;
7164 //Check destination path exists
7165 if (!is_dir($destpath)) {
7166 return false;
7169 //Check destination path is writable. TODO!!
7171 //Clean destination filename
7172 $destfilename = clean_filename($destfilename);
7174 //Now check and prepare every file
7175 $files = array();
7176 $origpath = NULL;
7178 foreach ($originalfiles as $file) { //Iterate over each file
7179 //Check for every file
7180 $tempfile = cleardoubleslashes($file); // no doubleslashes!
7181 //Calculate the base path for all files if it isn't set
7182 if ($origpath === NULL) {
7183 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
7185 //See if the file is readable
7186 if (!is_readable($tempfile)) { //Is readable
7187 continue;
7189 //See if the file/dir is in the same directory than the rest
7190 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
7191 continue;
7193 //Add the file to the array
7194 $files[] = $tempfile;
7197 //Everything is ready:
7198 // -$origpath is the path where ALL the files to be compressed reside (dir).
7199 // -$destpath is the destination path where the zip file will go (dir).
7200 // -$files is an array of files/dirs to compress (fullpath)
7201 // -$destfilename is the name of the zip file (without path)
7203 //print_object($files); //Debug
7205 if (empty($CFG->zip)) { // Use built-in php-based zip function
7207 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
7208 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
7209 $zipfiles = array();
7210 $start = strlen($origpath)+1;
7211 foreach($files as $file) {
7212 $tf = array();
7213 $tf[PCLZIP_ATT_FILE_NAME] = $file;
7214 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME] = substr($file, $start);
7215 $zipfiles[] = $tf;
7217 //create the archive
7218 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
7219 if (($list = $archive->create($zipfiles) == 0)) {
7220 notice($archive->errorInfo(true));
7221 return false;
7224 } else { // Use external zip program
7226 $filestozip = "";
7227 foreach ($files as $filetozip) {
7228 $filestozip .= escapeshellarg(basename($filetozip));
7229 $filestozip .= " ";
7231 //Construct the command
7232 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
7233 $command = 'cd '.escapeshellarg($origpath).$separator.
7234 escapeshellarg($CFG->zip).' -r '.
7235 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
7236 //All converted to backslashes in WIN
7237 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
7238 $command = str_replace('/','\\',$command);
7240 Exec($command);
7242 return true;
7245 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
7246 //Unzip one zip file to a destination dir
7247 //Both parameters must be FULL paths
7248 //If destination isn't specified, it will be the
7249 //SAME directory where the zip file resides.
7251 global $CFG;
7253 //Extract everything from zipfile
7254 $path_parts = pathinfo(cleardoubleslashes($zipfile));
7255 $zippath = $path_parts["dirname"]; //The path of the zip file
7256 $zipfilename = $path_parts["basename"]; //The name of the zip file
7257 $extension = $path_parts["extension"]; //The extension of the file
7259 //If no file, error
7260 if (empty($zipfilename)) {
7261 return false;
7264 //If no extension, error
7265 if (empty($extension)) {
7266 return false;
7269 //Clear $zipfile
7270 $zipfile = cleardoubleslashes($zipfile);
7272 //Check zipfile exists
7273 if (!file_exists($zipfile)) {
7274 return false;
7277 //If no destination, passed let's go with the same directory
7278 if (empty($destination)) {
7279 $destination = $zippath;
7282 //Clear $destination
7283 $destpath = rtrim(cleardoubleslashes($destination), "/");
7285 //Check destination path exists
7286 if (!is_dir($destpath)) {
7287 return false;
7290 //Check destination path is writable. TODO!!
7292 //Everything is ready:
7293 // -$zippath is the path where the zip file resides (dir)
7294 // -$zipfilename is the name of the zip file (without path)
7295 // -$destpath is the destination path where the zip file will uncompressed (dir)
7297 $list = null;
7299 if (empty($CFG->unzip)) { // Use built-in php-based unzip function
7301 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
7302 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
7303 if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
7304 PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename',
7305 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $destpath)) {
7306 if (!empty($showstatus)) {
7307 notice($archive->errorInfo(true));
7309 return false;
7312 } else { // Use external unzip program
7314 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
7315 $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
7317 $command = 'cd '.escapeshellarg($zippath).$separator.
7318 escapeshellarg($CFG->unzip).' -o '.
7319 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
7320 escapeshellarg($destpath).$redirection;
7321 //All converted to backslashes in WIN
7322 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
7323 $command = str_replace('/','\\',$command);
7325 Exec($command,$list);
7328 //Display some info about the unzip execution
7329 if ($showstatus) {
7330 unzip_show_status($list,$destpath);
7333 return true;
7336 function unzip_cleanfilename ($p_event, &$p_header) {
7337 //This function is used as callback in unzip_file() function
7338 //to clean illegal characters for given platform and to prevent directory traversal.
7339 //Produces the same result as info-zip unzip.
7340 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
7341 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
7342 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
7343 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
7344 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
7345 } else {
7346 //Add filtering for other systems here
7347 // BSD: none (tested)
7348 // Linux: ??
7349 // MacosX: ??
7351 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
7352 return 1;
7355 function unzip_show_status ($list,$removepath) {
7356 //This function shows the results of the unzip execution
7357 //depending of the value of the $CFG->zip, results will be
7358 //text or an array of files.
7360 global $CFG;
7362 if (empty($CFG->unzip)) { // Use built-in php-based zip function
7363 $strname = get_string("name");
7364 $strsize = get_string("size");
7365 $strmodified = get_string("modified");
7366 $strstatus = get_string("status");
7367 echo "<table width=\"640\">";
7368 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
7369 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
7370 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
7371 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
7372 foreach ($list as $item) {
7373 echo "<tr>";
7374 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
7375 print_cell("left", s($item['filename']));
7376 if (! $item['folder']) {
7377 print_cell("right", display_size($item['size']));
7378 } else {
7379 echo "<td>&nbsp;</td>";
7381 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
7382 print_cell("right", $filedate);
7383 print_cell("right", $item['status']);
7384 echo "</tr>";
7386 echo "</table>";
7388 } else { // Use external zip program
7389 print_simple_box_start("center");
7390 echo "<pre>";
7391 foreach ($list as $item) {
7392 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
7394 echo "</pre>";
7395 print_simple_box_end();
7400 * Returns most reliable client address
7402 * @return string The remote IP address
7404 function getremoteaddr() {
7405 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
7406 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
7408 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
7409 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
7411 if (!empty($_SERVER['REMOTE_ADDR'])) {
7412 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
7414 return '';
7418 * Cleans a remote address ready to put into the log table
7420 function cleanremoteaddr($addr) {
7421 $originaladdr = $addr;
7422 $matches = array();
7423 // first get all things that look like IP addresses.
7424 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER)) {
7425 return '';
7427 $goodmatches = array();
7428 $lanmatches = array();
7429 foreach ($matches as $match) {
7430 // print_r($match);
7431 // check to make sure it's not an internal address.
7432 // the following are reserved for private lans...
7433 // 10.0.0.0 - 10.255.255.255
7434 // 172.16.0.0 - 172.31.255.255
7435 // 192.168.0.0 - 192.168.255.255
7436 // 169.254.0.0 -169.254.255.255
7437 $bits = explode('.',$match[0]);
7438 if (count($bits) != 4) {
7439 // weird, preg match shouldn't give us it.
7440 continue;
7442 if (($bits[0] == 10)
7443 || ($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
7444 || ($bits[0] == 192 && $bits[1] == 168)
7445 || ($bits[0] == 169 && $bits[1] == 254)) {
7446 $lanmatches[] = $match[0];
7447 continue;
7449 // finally, it's ok
7450 $goodmatches[] = $match[0];
7452 if (!count($goodmatches)) {
7453 // perhaps we have a lan match, it's probably better to return that.
7454 if (!count($lanmatches)) {
7455 return '';
7456 } else {
7457 return array_pop($lanmatches);
7460 if (count($goodmatches) == 1) {
7461 return $goodmatches[0];
7463 //Commented out following because there are so many, and it clogs the logs MDL-13544
7464 //error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
7466 // We need to return something, so return the first
7467 return array_pop($goodmatches);
7471 * file_put_contents is only supported by php 5.0 and higher
7472 * so if it is not predefined, define it here
7474 * @param $file full path of the file to write
7475 * @param $contents contents to be sent
7476 * @return number of bytes written (false on error)
7478 if(!function_exists('file_put_contents')) {
7479 function file_put_contents($file, $contents) {
7480 $result = false;
7481 if ($f = fopen($file, 'w')) {
7482 $result = fwrite($f, $contents);
7483 fclose($f);
7485 return $result;
7490 * The clone keyword is only supported from PHP 5 onwards.
7491 * The behaviour of $obj2 = $obj1 differs fundamentally
7492 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
7493 * created, in PHP 5 $obj1 is referenced. To create a copy
7494 * in PHP 5 the clone keyword was introduced. This function
7495 * simulates this behaviour for PHP < 5.0.0.
7496 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
7498 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
7499 * Found a better implementation (more checks and possibilities) from PEAR:
7500 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
7502 * @param object $obj
7503 * @return object
7505 if(!check_php_version('5.0.0')) {
7506 // the eval is needed to prevent PHP 5 from getting a parse error!
7507 eval('
7508 function clone($obj) {
7509 /// Sanity check
7510 if (!is_object($obj)) {
7511 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
7512 return;
7515 /// Use serialize/unserialize trick to deep copy the object
7516 $obj = unserialize(serialize($obj));
7518 /// If there is a __clone method call it on the "new" class
7519 if (method_exists($obj, \'__clone\')) {
7520 $obj->__clone();
7523 return $obj;
7526 // Supply the PHP5 function scandir() to older versions.
7527 function scandir($directory) {
7528 $files = array();
7529 if ($dh = opendir($directory)) {
7530 while (($file = readdir($dh)) !== false) {
7531 $files[] = $file;
7533 closedir($dh);
7535 return $files;
7538 // Supply the PHP5 function array_combine() to older versions.
7539 function array_combine($keys, $values) {
7540 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
7541 return false;
7543 reset($values);
7544 $result = array();
7545 foreach ($keys as $key) {
7546 $result[$key] = current($values);
7547 next($values);
7549 return $result;
7555 * This function will make a complete copy of anything it's given,
7556 * regardless of whether it's an object or not.
7557 * @param mixed $thing
7558 * @return mixed
7560 function fullclone($thing) {
7561 return unserialize(serialize($thing));
7566 * This function expects to called during shutdown
7567 * should be set via register_shutdown_function()
7568 * in lib/setup.php .
7570 * Right now we do it only if we are under apache, to
7571 * make sure apache children that hog too much mem are
7572 * killed.
7575 function moodle_request_shutdown() {
7577 global $CFG;
7579 // initially, we are only ever called under apache
7580 // but check just in case
7581 if (function_exists('apache_child_terminate')
7582 && function_exists('memory_get_usage')
7583 && ini_get_bool('child_terminate')) {
7584 if (empty($CFG->apachemaxmem)) {
7585 $CFG->apachemaxmem = 25000000; // default 25MiB
7587 if (memory_get_usage() > (int)$CFG->apachemaxmem) {
7588 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
7589 @apache_child_terminate();
7592 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
7593 if (defined('MDL_PERFTOLOG')) {
7594 $perf = get_performance_info();
7595 error_log("PERF: " . $perf['txt']);
7597 if (defined('MDL_PERFINC')) {
7598 $inc = get_included_files();
7599 $ts = 0;
7600 foreach($inc as $f) {
7601 if (preg_match(':^/:', $f)) {
7602 $fs = filesize($f);
7603 $ts += $fs;
7604 $hfs = display_size($fs);
7605 error_log(substr($f,strlen($CFG->dirroot)) . " size: $fs ($hfs)"
7606 , NULL, NULL, 0);
7607 } else {
7608 error_log($f , NULL, NULL, 0);
7611 if ($ts > 0 ) {
7612 $hts = display_size($ts);
7613 error_log("Total size of files included: $ts ($hts)");
7620 * If new messages are waiting for the current user, then return
7621 * Javascript code to create a popup window
7623 * @return string Javascript code
7625 function message_popup_window() {
7626 global $USER;
7628 $popuplimit = 30; // Minimum seconds between popups
7630 if (!defined('MESSAGE_WINDOW')) {
7631 if (isset($USER->id) and !isguestuser()) {
7632 if (!isset($USER->message_lastpopup)) {
7633 $USER->message_lastpopup = 0;
7635 if ((time() - $USER->message_lastpopup) > $popuplimit) { /// It's been long enough
7636 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
7637 if (count_records_select('message', 'useridto = \''.$USER->id.'\' AND timecreated > \''.$USER->message_lastpopup.'\'')) {
7638 $USER->message_lastpopup = time();
7639 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
7640 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
7647 return '';
7650 // Used to make sure that $min <= $value <= $max
7651 function bounded_number($min, $value, $max) {
7652 if($value < $min) {
7653 return $min;
7655 if($value > $max) {
7656 return $max;
7658 return $value;
7661 function array_is_nested($array) {
7662 foreach ($array as $value) {
7663 if (is_array($value)) {
7664 return true;
7667 return false;
7671 *** get_performance_info() pairs up with init_performance_info()
7672 *** loaded in setup.php. Returns an array with 'html' and 'txt'
7673 *** values ready for use, and each of the individual stats provided
7674 *** separately as well.
7677 function get_performance_info() {
7678 global $CFG, $PERF, $rcache;
7680 $info = array();
7681 $info['html'] = ''; // holds userfriendly HTML representation
7682 $info['txt'] = me() . ' '; // holds log-friendly representation
7684 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
7686 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
7687 $info['txt'] .= 'time: '.$info['realtime'].'s ';
7689 if (function_exists('memory_get_usage')) {
7690 $info['memory_total'] = memory_get_usage();
7691 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
7692 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
7693 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
7696 if (function_exists('memory_get_peak_usage')) {
7697 $info['memory_peak'] = memory_get_peak_usage();
7698 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
7699 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
7702 $inc = get_included_files();
7703 //error_log(print_r($inc,1));
7704 $info['includecount'] = count($inc);
7705 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
7706 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
7708 if (!empty($PERF->dbqueries)) {
7709 $info['dbqueries'] = $PERF->dbqueries;
7710 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
7711 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
7714 if (!empty($PERF->logwrites)) {
7715 $info['logwrites'] = $PERF->logwrites;
7716 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
7717 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
7720 if (!empty($PERF->profiling) && $PERF->profiling) {
7721 require_once($CFG->dirroot .'/lib/profilerlib.php');
7722 $info['html'] .= '<span class="profilinginfo">'.Profiler::get_profiling(array('-R')).'</span>';
7725 if (function_exists('posix_times')) {
7726 $ptimes = posix_times();
7727 if (is_array($ptimes)) {
7728 foreach ($ptimes as $key => $val) {
7729 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
7731 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
7732 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
7736 // Grab the load average for the last minute
7737 // /proc will only work under some linux configurations
7738 // while uptime is there under MacOSX/Darwin and other unices
7739 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
7740 list($server_load) = explode(' ', $loadavg[0]);
7741 unset($loadavg);
7742 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
7743 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
7744 $server_load = $matches[1];
7745 } else {
7746 trigger_error('Could not parse uptime output!');
7749 if (!empty($server_load)) {
7750 $info['serverload'] = $server_load;
7751 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
7752 $info['txt'] .= "serverload: {$info['serverload']} ";
7755 if (isset($rcache->hits) && isset($rcache->misses)) {
7756 $info['rcachehits'] = $rcache->hits;
7757 $info['rcachemisses'] = $rcache->misses;
7758 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
7759 "{$rcache->hits}/{$rcache->misses}</span> ";
7760 $info['txt'] .= 'rcache: '.
7761 "{$rcache->hits}/{$rcache->misses} ";
7763 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
7764 return $info;
7767 function apd_get_profiling() {
7768 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
7772 * Delete directory or only it's content
7773 * @param string $dir directory path
7774 * @param bool $content_only
7775 * @return bool success, true also if dir does not exist
7777 function remove_dir($dir, $content_only=false) {
7778 if (!file_exists($dir)) {
7779 // nothing to do
7780 return true;
7782 $handle = opendir($dir);
7783 $result = true;
7784 while (false!==($item = readdir($handle))) {
7785 if($item != '.' && $item != '..') {
7786 if(is_dir($dir.'/'.$item)) {
7787 $result = remove_dir($dir.'/'.$item) && $result;
7788 }else{
7789 $result = unlink($dir.'/'.$item) && $result;
7793 closedir($handle);
7794 if ($content_only) {
7795 return $result;
7797 return rmdir($dir); // if anything left the result will be false, noo need for && $result
7801 * Function to check if a directory exists and optionally create it.
7803 * @param string absolute directory path (must be under $CFG->dataroot)
7804 * @param boolean create directory if does not exist
7805 * @param boolean create directory recursively
7807 * @return boolean true if directory exists or created
7809 function check_dir_exists($dir, $create=false, $recursive=false) {
7811 global $CFG;
7813 if (strstr($dir, $CFG->dataroot.'/') === false) {
7814 debugging('Warning. Wrong call to check_dir_exists(). $dir must be an absolute path under $CFG->dataroot ("' . $dir . '" is incorrect)', DEBUG_DEVELOPER);
7817 $status = true;
7819 if(!is_dir($dir)) {
7820 if (!$create) {
7821 $status = false;
7822 } else {
7823 umask(0000);
7824 if ($recursive) {
7825 /// PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
7826 $dir = str_replace('\\', '/', $dir); //windows compatibility
7827 /// We are going to make it recursive under $CFG->dataroot only
7828 /// (will help sites running open_basedir security and others)
7829 $dir = str_replace($CFG->dataroot . '/', '', $dir);
7830 $dirs = explode('/', $dir); /// Extract path parts
7831 /// Iterate over each part with start point $CFG->dataroot
7832 $dir = $CFG->dataroot . '/';
7833 foreach ($dirs as $part) {
7834 if ($part == '') {
7835 continue;
7837 $dir .= $part.'/';
7838 if (!is_dir($dir)) {
7839 if (!mkdir($dir, $CFG->directorypermissions)) {
7840 $status = false;
7841 break;
7845 } else {
7846 $status = mkdir($dir, $CFG->directorypermissions);
7850 return $status;
7853 function report_session_error() {
7854 global $CFG, $FULLME;
7856 if (empty($CFG->lang)) {
7857 $CFG->lang = "en";
7859 // Set up default theme and locale
7860 theme_setup();
7861 moodle_setlocale();
7863 //clear session cookies
7864 if (check_php_version('5.2.0')) {
7865 //PHP 5.2.0
7866 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
7867 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
7868 } else {
7869 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
7870 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
7872 //increment database error counters
7873 if (isset($CFG->session_error_counter)) {
7874 set_config('session_error_counter', 1 + $CFG->session_error_counter);
7875 } else {
7876 set_config('session_error_counter', 1);
7878 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
7883 * Detect if an object or a class contains a given property
7884 * will take an actual object or the name of a class
7885 * @param mix $obj Name of class or real object to test
7886 * @param string $property name of property to find
7887 * @return bool true if property exists
7889 function object_property_exists( $obj, $property ) {
7890 if (is_string( $obj )) {
7891 $properties = get_class_vars( $obj );
7893 else {
7894 $properties = get_object_vars( $obj );
7896 return array_key_exists( $property, $properties );
7901 * Detect a custom script replacement in the data directory that will
7902 * replace an existing moodle script
7903 * @param string $urlpath path to the original script
7904 * @return string full path name if a custom script exists
7905 * @return bool false if no custom script exists
7907 function custom_script_path($urlpath='') {
7908 global $CFG;
7910 // set default $urlpath, if necessary
7911 if (empty($urlpath)) {
7912 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
7915 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
7916 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot) === false )) {
7917 return false;
7920 // replace wwwroot with the path to the customscripts folder and clean path
7921 $scriptpath = $CFG->customscripts . clean_param(substr($urlpath, strlen($CFG->wwwroot)), PARAM_PATH);
7923 // remove the query string, if any
7924 if (($strpos = strpos($scriptpath, '?')) !== false) {
7925 $scriptpath = substr($scriptpath, 0, $strpos);
7928 // remove trailing slashes, if any
7929 $scriptpath = rtrim($scriptpath, '/\\');
7931 // append index.php, if necessary
7932 if (is_dir($scriptpath)) {
7933 $scriptpath .= '/index.php';
7936 // check the custom script exists
7937 if (file_exists($scriptpath)) {
7938 return $scriptpath;
7939 } else {
7940 return false;
7945 * Wrapper function to load necessary editor scripts
7946 * to $CFG->editorsrc array. Params can be coursei id
7947 * or associative array('courseid' => value, 'name' => 'editorname').
7948 * @uses $CFG
7949 * @param mixed $args Courseid or associative array.
7951 function loadeditor($args) {
7952 global $CFG;
7953 include($CFG->libdir .'/editorlib.php');
7954 return editorObject::loadeditor($args);
7958 * Returns whether or not the user object is a remote MNET user. This function
7959 * is in moodlelib because it does not rely on loading any of the MNET code.
7961 * @param object $user A valid user object
7962 * @return bool True if the user is from a remote Moodle.
7964 function is_mnet_remote_user($user) {
7965 global $CFG;
7967 if (!isset($CFG->mnet_localhost_id)) {
7968 include_once $CFG->dirroot . '/mnet/lib.php';
7969 $env = new mnet_environment();
7970 $env->init();
7971 unset($env);
7974 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
7978 * Checks if a given plugin is in the list of enabled enrolment plugins.
7980 * @param string $auth Enrolment plugin.
7981 * @return boolean Whether the plugin is enabled.
7983 function is_enabled_enrol($enrol='') {
7984 global $CFG;
7986 // use the global default if not specified
7987 if ($enrol == '') {
7988 $enrol = $CFG->enrol;
7990 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
7994 * This function will search for browser prefereed languages, setting Moodle
7995 * to use the best one available if $SESSION->lang is undefined
7997 function setup_lang_from_browser() {
7999 global $CFG, $SESSION, $USER;
8001 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
8002 // Lang is defined in session or user profile, nothing to do
8003 return;
8006 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
8007 return;
8010 /// Extract and clean langs from headers
8011 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
8012 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
8013 $rawlangs = explode(',', $rawlangs); // Convert to array
8014 $langs = array();
8016 $order = 1.0;
8017 foreach ($rawlangs as $lang) {
8018 if (strpos($lang, ';') === false) {
8019 $langs[(string)$order] = $lang;
8020 $order = $order-0.01;
8021 } else {
8022 $parts = explode(';', $lang);
8023 $pos = strpos($parts[1], '=');
8024 $langs[substr($parts[1], $pos+1)] = $parts[0];
8027 krsort($langs, SORT_NUMERIC);
8029 $langlist = get_list_of_languages();
8031 /// Look for such langs under standard locations
8032 foreach ($langs as $lang) {
8033 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR)); // clean it properly for include
8034 if (!array_key_exists($lang, $langlist)) {
8035 continue; // language not allowed, try next one
8037 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
8038 $SESSION->lang = $lang; /// Lang exists, set it in session
8039 break; /// We have finished. Go out
8042 return;
8046 ////////////////////////////////////////////////////////////////////////////////
8048 function is_newnav($navigation) {
8049 if (is_array($navigation) && !empty($navigation['newnav'])) {
8050 return true;
8051 } else {
8052 return false;
8057 * Checks whether the given variable name is defined as a variable within the given object.
8058 * @note This will NOT work with stdClass objects, which have no class variables.
8059 * @param string $var The variable name
8060 * @param object $object The object to check
8061 * @return boolean
8063 function in_object_vars($var, $object) {
8064 $class_vars = get_class_vars(get_class($object));
8065 $class_vars = array_keys($class_vars);
8066 return in_array($var, $class_vars);
8070 * Returns an array without repeated objects.
8071 * This function is similar to array_unique, but for arrays that have objects as values
8073 * @param unknown_type $array
8074 * @param unknown_type $keep_key_assoc
8075 * @return unknown
8077 function object_array_unique($array, $keep_key_assoc = true) {
8078 $duplicate_keys = array();
8079 $tmp = array();
8081 foreach ($array as $key=>$val) {
8082 // convert objects to arrays, in_array() does not support objects
8083 if (is_object($val)) {
8084 $val = (array)$val;
8087 if (!in_array($val, $tmp)) {
8088 $tmp[] = $val;
8089 } else {
8090 $duplicate_keys[] = $key;
8094 foreach ($duplicate_keys as $key) {
8095 unset($array[$key]);
8098 return $keep_key_assoc ? $array : array_values($array);
8102 * Returns the language string for the given plugin.
8104 * @param string $plugin the plugin code name
8105 * @param string $type the type of plugin (mod, block, filter)
8106 * @return string The plugin language string
8108 function get_plugin_name($plugin, $type='mod') {
8109 $plugin_name = '';
8111 switch ($type) {
8112 case 'mod':
8113 $plugin_name = get_string('modulename', $plugin);
8114 break;
8115 case 'blocks':
8116 $plugin_name = get_string('blockname', "block_$plugin");
8117 if (empty($plugin_name) || $plugin_name == '[[blockname]]') {
8118 if (($block = block_instance($plugin)) !== false) {
8119 $plugin_name = $block->get_title();
8120 } else {
8121 $plugin_name = "[[$plugin]]";
8124 break;
8125 case 'filter':
8126 $plugin_name = trim(get_string('filtername', $plugin));
8127 if (empty($plugin_name) or ($plugin_name == '[[filtername]]')) {
8128 $textlib = textlib_get_instance();
8129 $plugin_name = $textlib->strtotitle($plugin);
8131 break;
8132 default:
8133 $plugin_name = $plugin;
8134 break;
8137 return $plugin_name;
8141 * Is a userid the primary administrator?
8143 * @param $userid int id of user to check
8144 * @return boolean
8146 function is_primary_admin($userid){
8147 $primaryadmin = get_admin();
8149 if($userid == $primaryadmin->id){
8150 return true;
8151 }else{
8152 return false;
8156 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: