"MDL-12304, fix double text"
[moodle-linuxchix.git] / lib / moodlelib.php
blob057d3e5f30104200b6e6ef92c2fa8ee28d36c8d2
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);
3013 return true;
3015 } else {
3016 rollback_sql();
3017 return false;
3022 * Retrieve the guest user object
3024 * @uses $CFG
3025 * @return user A {@link $USER} object
3027 function guest_user() {
3028 global $CFG;
3030 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
3031 $newuser->confirmed = 1;
3032 $newuser->lang = $CFG->lang;
3033 $newuser->lastip = getremoteaddr();
3036 return $newuser;
3040 * Given a username and password, this function looks them
3041 * up using the currently selected authentication mechanism,
3042 * and if the authentication is successful, it returns a
3043 * valid $user object from the 'user' table.
3045 * Uses auth_ functions from the currently active auth module
3047 * After authenticate_user_login() returns success, you will need to
3048 * log that the user has logged in, and call complete_user_login() to set
3049 * the session up.
3051 * @uses $CFG
3052 * @param string $username User's username (with system magic quotes)
3053 * @param string $password User's password (with system magic quotes)
3054 * @return user|flase A {@link $USER} object or false if error
3056 function authenticate_user_login($username, $password) {
3058 global $CFG;
3060 $authsenabled = get_enabled_auth_plugins();
3062 if ($user = get_complete_user_data('username', $username)) {
3063 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
3064 if ($auth=='nologin' or !is_enabled_auth($auth)) {
3065 add_to_log(0, 'login', 'error', 'index.php', $username);
3066 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3067 return false;
3069 if (!empty($user->deleted)) {
3070 add_to_log(0, 'login', 'error', 'index.php', $username);
3071 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3072 return false;
3074 $auths = array($auth);
3076 } else {
3077 $auths = $authsenabled;
3078 $user = new object();
3079 $user->id = 0; // User does not exist
3082 foreach ($auths as $auth) {
3083 $authplugin = get_auth_plugin($auth);
3085 // on auth fail fall through to the next plugin
3086 if (!$authplugin->user_login($username, $password)) {
3087 continue;
3090 // successful authentication
3091 if ($user->id) { // User already exists in database
3092 if (empty($user->auth)) { // For some reason auth isn't set yet
3093 set_field('user', 'auth', $auth, 'username', $username);
3094 $user->auth = $auth;
3097 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
3099 if (!$authplugin->is_internal()) { // update user record from external DB
3100 $user = update_user_record($username, get_auth_plugin($user->auth));
3102 } else {
3103 // if user not found, create him
3104 $user = create_user_record($username, $password, $auth);
3107 $authplugin->sync_roles($user);
3109 foreach ($authsenabled as $hau) {
3110 $hauth = get_auth_plugin($hau);
3111 $hauth->user_authenticated_hook($user, $username, $password);
3114 /// Log in to a second system if necessary
3115 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
3116 if (!empty($CFG->sso)) {
3117 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
3118 if (function_exists('sso_user_login')) {
3119 if (!sso_user_login($username, $password)) { // Perform the signon process
3120 notify('Second sign-on failed');
3125 if ($user->id===0) {
3126 return false;
3128 return $user;
3131 // failed if all the plugins have failed
3132 add_to_log(0, 'login', 'error', 'index.php', $username);
3133 if (debugging('', DEBUG_ALL)) {
3134 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
3136 return false;
3140 * Call to complete the user login process after authenticate_user_login()
3141 * has succeeded. It will setup the $USER variable and other required bits
3142 * and pieces.
3144 * NOTE:
3145 * - It will NOT log anything -- up to the caller to decide what to log.
3149 * @uses $CFG, $USER
3150 * @param string $user obj
3151 * @return user|flase A {@link $USER} object or false if error
3153 function complete_user_login($user) {
3154 global $CFG, $USER;
3156 $USER = $user; // this is required because we need to access preferences here!
3158 reload_user_preferences();
3160 update_user_login_times();
3161 if (empty($CFG->nolastloggedin)) {
3162 set_moodle_cookie($USER->username);
3163 } else {
3164 // do not store last logged in user in cookie
3165 // auth plugins can temporarily override this from loginpage_hook()
3166 // do not save $CFG->nolastloggedin in database!
3167 set_moodle_cookie('nobody');
3169 set_login_session_preferences();
3171 // Call enrolment plugins
3172 check_enrolment_plugins($user);
3174 /// This is what lets the user do anything on the site :-)
3175 load_all_capabilities();
3177 /// Select password change url
3178 $userauth = get_auth_plugin($USER->auth);
3180 /// check whether the user should be changing password
3181 if (get_user_preferences('auth_forcepasswordchange', false)){
3182 if ($userauth->can_change_password()) {
3183 if ($changeurl = $userauth->change_password_url()) {
3184 redirect($changeurl);
3185 } else {
3186 redirect($CFG->httpswwwroot.'/login/change_password.php');
3188 } else {
3189 print_error('nopasswordchangeforced', 'auth');
3192 return $USER;
3196 * Compare password against hash stored in internal user table.
3197 * If necessary it also updates the stored hash to new format.
3199 * @param object user
3200 * @param string plain text password
3201 * @return bool is password valid?
3203 function validate_internal_user_password(&$user, $password) {
3204 global $CFG;
3206 if (!isset($CFG->passwordsaltmain)) {
3207 $CFG->passwordsaltmain = '';
3210 $validated = false;
3212 // get password original encoding in case it was not updated to unicode yet
3213 $textlib = textlib_get_instance();
3214 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
3216 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
3217 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
3218 $validated = true;
3219 } else {
3220 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
3221 $alt = 'passwordsaltalt'.$i;
3222 if (!empty($CFG->$alt)) {
3223 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
3224 $validated = true;
3225 break;
3231 if ($validated) {
3232 // force update of password hash using latest main password salt and encoding if needed
3233 update_internal_user_password($user, $password);
3236 return $validated;
3240 * Calculate hashed value from password using current hash mechanism.
3242 * @param string password
3243 * @return string password hash
3245 function hash_internal_user_password($password) {
3246 global $CFG;
3248 if (isset($CFG->passwordsaltmain)) {
3249 return md5($password.$CFG->passwordsaltmain);
3250 } else {
3251 return md5($password);
3256 * Update pssword hash in user object.
3258 * @param object user
3259 * @param string plain text password
3260 * @param bool store changes also in db, default true
3261 * @return true if hash changed
3263 function update_internal_user_password(&$user, $password) {
3264 global $CFG;
3266 $authplugin = get_auth_plugin($user->auth);
3267 if (!empty($authplugin->config->preventpassindb)) {
3268 $hashedpassword = 'not cached';
3269 } else {
3270 $hashedpassword = hash_internal_user_password($password);
3273 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
3277 * Get a complete user record, which includes all the info
3278 * in the user record
3279 * Intended for setting as $USER session variable
3281 * @uses $CFG
3282 * @uses SITEID
3283 * @param string $field The user field to be checked for a given value.
3284 * @param string $value The value to match for $field.
3285 * @return user A {@link $USER} object.
3287 function get_complete_user_data($field, $value, $mnethostid=null) {
3289 global $CFG;
3291 if (!$field || !$value) {
3292 return false;
3295 /// Build the WHERE clause for an SQL query
3297 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
3299 if (is_null($mnethostid)) {
3300 // if null, we restrict to local users
3301 // ** testing for local user can be done with
3302 // mnethostid = $CFG->mnet_localhost_id
3303 // or with
3304 // auth != 'mnet'
3305 // but the first one is FAST with our indexes
3306 $mnethostid = $CFG->mnet_localhost_id;
3308 $mnethostid = (int)$mnethostid;
3309 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
3311 /// Get all the basic user data
3313 if (! $user = get_record_select('user', $constraints)) {
3314 return false;
3317 /// Get various settings and preferences
3319 if ($displays = get_records('course_display', 'userid', $user->id)) {
3320 foreach ($displays as $display) {
3321 $user->display[$display->course] = $display->display;
3325 $user->preference = get_user_preferences(null, null, $user->id);
3327 $user->lastcourseaccess = array(); // during last session
3328 $user->currentcourseaccess = array(); // during current session
3329 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
3330 foreach ($lastaccesses as $lastaccess) {
3331 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
3335 $sql = "SELECT g.id, g.courseid
3336 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
3337 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
3339 // this is a special hack to speedup calendar display
3340 $user->groupmember = array();
3341 if ($groups = get_records_sql($sql)) {
3342 foreach ($groups as $group) {
3343 if (!array_key_exists($group->courseid, $user->groupmember)) {
3344 $user->groupmember[$group->courseid] = array();
3346 $user->groupmember[$group->courseid][$group->id] = $group->id;
3350 /// Add the custom profile fields to the user record
3351 include_once($CFG->dirroot.'/user/profile/lib.php');
3352 $customfields = (array)profile_user_record($user->id);
3353 foreach ($customfields as $cname=>$cvalue) {
3354 if (!isset($user->$cname)) { // Don't overwrite any standard fields
3355 $user->$cname = $cvalue;
3359 /// Rewrite some variables if necessary
3360 if (!empty($user->description)) {
3361 $user->description = true; // No need to cart all of it around
3363 if ($user->username == 'guest') {
3364 $user->lang = $CFG->lang; // Guest language always same as site
3365 $user->firstname = get_string('guestuser'); // Name always in current language
3366 $user->lastname = ' ';
3369 $user->sesskey = random_string(10);
3370 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
3372 return $user;
3376 * @uses $CFG
3377 * @param string $password the password to be checked agains the password policy
3378 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
3379 * @return bool true if the password is valid according to the policy. false otherwise.
3381 function check_password_policy($password, &$errmsg) {
3382 global $CFG;
3384 if (empty($CFG->passwordpolicy)) {
3385 return true;
3388 $textlib = textlib_get_instance();
3389 $errmsg = '';
3390 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
3391 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
3393 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
3394 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
3396 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
3397 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
3399 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
3400 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
3402 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
3403 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3405 } else if ($password == 'admin' or $password == 'password') {
3406 $errmsg = get_string('unsafepassword');
3409 if ($errmsg == '') {
3410 return true;
3411 } else {
3412 return false;
3418 * When logging in, this function is run to set certain preferences
3419 * for the current SESSION
3421 function set_login_session_preferences() {
3422 global $SESSION, $CFG;
3424 $SESSION->justloggedin = true;
3426 unset($SESSION->lang);
3428 // Restore the calendar filters, if saved
3429 if (intval(get_user_preferences('calendar_persistflt', 0))) {
3430 include_once($CFG->dirroot.'/calendar/lib.php');
3431 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
3437 * Delete a course, including all related data from the database,
3438 * and any associated files from the moodledata folder.
3440 * @param int $courseid The id of the course to delete.
3441 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3442 * @return bool true if all the removals succeeded. false if there were any failures. If this
3443 * method returns false, some of the removals will probably have succeeded, and others
3444 * failed, but you have no way of knowing which.
3446 function delete_course($courseid, $showfeedback = true) {
3447 global $CFG;
3448 $result = true;
3450 // frontpage course can not be deleted!!
3451 if ($courseid == SITEID) {
3452 return false;
3455 if (!remove_course_contents($courseid, $showfeedback)) {
3456 if ($showfeedback) {
3457 notify("An error occurred while deleting some of the course contents.");
3459 $result = false;
3462 if (!delete_records("course", "id", $courseid)) {
3463 if ($showfeedback) {
3464 notify("An error occurred while deleting the main course record.");
3466 $result = false;
3469 /// Delete all roles and overiddes in the course context
3470 if (!delete_context(CONTEXT_COURSE, $courseid)) {
3471 if ($showfeedback) {
3472 notify("An error occurred while deleting the main course context.");
3474 $result = false;
3477 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
3478 if ($showfeedback) {
3479 notify("An error occurred while deleting the course files.");
3481 $result = false;
3484 return $result;
3488 * Clear a course out completely, deleting all content
3489 * but don't delete the course itself
3491 * @uses $CFG
3492 * @param int $courseid The id of the course that is being deleted
3493 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3494 * @return bool true if all the removals succeeded. false if there were any failures. If this
3495 * method returns false, some of the removals will probably have succeeded, and others
3496 * failed, but you have no way of knowing which.
3498 function remove_course_contents($courseid, $showfeedback=true) {
3500 global $CFG;
3501 require_once($CFG->libdir.'/questionlib.php');
3502 require_once($CFG->libdir.'/gradelib.php');
3504 $result = true;
3506 if (! $course = get_record('course', 'id', $courseid)) {
3507 error('Course ID was incorrect (can\'t find it)');
3510 $strdeleted = get_string('deleted');
3512 /// First delete every instance of every module
3514 if ($allmods = get_records('modules') ) {
3515 foreach ($allmods as $mod) {
3516 $modname = $mod->name;
3517 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3518 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3519 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3520 $count=0;
3521 if (file_exists($modfile)) {
3522 include_once($modfile);
3523 if (function_exists($moddelete)) {
3524 if ($instances = get_records($modname, 'course', $course->id)) {
3525 foreach ($instances as $instance) {
3526 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
3527 /// Delete activity context questions and question categories
3528 question_delete_activity($cm, $showfeedback);
3530 if ($moddelete($instance->id)) {
3531 $count++;
3533 } else {
3534 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
3535 $result = false;
3537 if ($cm) {
3538 // delete cm and its context in correct order
3539 delete_records('course_modules', 'id', $cm->id);
3540 delete_context(CONTEXT_MODULE, $cm->id);
3544 } else {
3545 notify('Function '.$moddelete.'() doesn\'t exist!');
3546 $result = false;
3549 if (function_exists($moddeletecourse)) {
3550 $moddeletecourse($course, $showfeedback);
3553 if ($showfeedback) {
3554 notify($strdeleted .' '. $count .' x '. $modname);
3557 } else {
3558 error('No modules are installed!');
3561 /// Give local code a chance to delete its references to this course.
3562 require_once('locallib.php');
3563 notify_local_delete_course($courseid, $showfeedback);
3565 /// Delete course blocks
3567 if ($blocks = get_records_sql("SELECT *
3568 FROM {$CFG->prefix}block_instance
3569 WHERE pagetype = '".PAGE_COURSE_VIEW."'
3570 AND pageid = $course->id")) {
3571 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
3572 if ($showfeedback) {
3573 notify($strdeleted .' block_instance');
3576 require_once($CFG->libdir.'/blocklib.php');
3577 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3579 delete_context(CONTEXT_BLOCK, $block->id);
3581 // fix for MDL-7164
3582 // Get the block object and call instance_delete()
3583 if (!$record = blocks_get_record($block->blockid)) {
3584 $result = false;
3585 continue;
3587 if (!$obj = block_instance($record->name, $block)) {
3588 $result = false;
3589 continue;
3591 // Return value ignored, in core mods this does not do anything, but just in case
3592 // third party blocks might have stuff to clean up
3593 // we execute this anyway
3594 $obj->instance_delete();
3597 } else {
3598 $result = false;
3602 /// Delete any groups, removing members and grouping/course links first.
3603 require_once($CFG->dirroot.'/group/lib.php');
3604 groups_delete_groupings($courseid, $showfeedback);
3605 groups_delete_groups($courseid, $showfeedback);
3607 /// Delete all related records in other tables that may have a courseid
3608 /// This array stores the tables that need to be cleared, as
3609 /// table_name => column_name that contains the course id.
3611 $tablestoclear = array(
3612 'event' => 'courseid', // Delete events
3613 'log' => 'course', // Delete logs
3614 'course_sections' => 'course', // Delete any course stuff
3615 'course_modules' => 'course',
3616 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3617 'user_lastaccess' => 'courseid',
3618 'backup_log' => 'courseid'
3620 foreach ($tablestoclear as $table => $col) {
3621 if (delete_records($table, $col, $course->id)) {
3622 if ($showfeedback) {
3623 notify($strdeleted . ' ' . $table);
3625 } else {
3626 $result = false;
3631 /// Clean up metacourse stuff
3633 if ($course->metacourse) {
3634 delete_records("course_meta","parent_course",$course->id);
3635 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3636 if ($showfeedback) {
3637 notify("$strdeleted course_meta");
3639 } else {
3640 if ($parents = get_records("course_meta","child_course",$course->id)) {
3641 foreach ($parents as $parent) {
3642 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3644 if ($showfeedback) {
3645 notify("$strdeleted course_meta");
3650 /// Delete questions and question categories
3651 question_delete_course($course, $showfeedback);
3653 /// Remove all data from gradebook
3654 $context = get_context_instance(CONTEXT_COURSE, $courseid);
3655 remove_course_grades($courseid, $showfeedback);
3656 remove_grade_letters($context, $showfeedback);
3658 return $result;
3662 * Change dates in module - used from course reset.
3663 * @param strin $modname forum, assignent, etc
3664 * @param array $fields array of date fields from mod table
3665 * @param int $timeshift time difference
3666 * @return success
3668 function shift_course_mod_dates($modname, $fields, $timeshift, $courseid) {
3669 global $CFG;
3670 include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
3672 $return = true;
3673 foreach ($fields as $field) {
3674 $updatesql = "UPDATE {$CFG->prefix}$modname
3675 SET $field = $field + ($timeshift)
3676 WHERE course=$courseid AND $field<>0 AND $field<>0";
3677 $return = execute_sql($updatesql, false) && $return;
3680 $refreshfunction = $modname.'_refresh_events';
3681 if (function_exists($refreshfunction)) {
3682 $refreshfunction($courseid);
3685 return $return;
3689 * This function will empty a course of user data.
3690 * It will retain the activities and the structure of the course.
3691 * @param object $data an object containing all the settings including courseid (without magic quotes)
3692 * @return array status array of array component, item, error
3694 function reset_course_userdata($data) {
3695 global $CFG, $USER;
3696 require_once($CFG->libdir.'/gradelib.php');
3697 require_once($CFG->dirroot.'/group/lib.php');
3699 $data->courseid = $data->id;
3700 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
3702 // calculate the time shift of dates
3703 if (!empty($data->reset_start_date)) {
3704 // time part of course startdate should be zero
3705 $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
3706 } else {
3707 $data->timeshift = 0;
3710 // result array: component, item, error
3711 $status = array();
3713 // start the resetting
3714 $componentstr = get_string('general');
3716 // move the course start time
3717 if (!empty($data->reset_start_date) and $data->timeshift) {
3718 // change course start data
3719 set_field('course', 'startdate', $data->reset_start_date, 'id', $data->courseid);
3720 // update all course and group events - do not move activity events
3721 $updatesql = "UPDATE {$CFG->prefix}event
3722 SET timestart = timestart + ({$data->timeshift})
3723 WHERE courseid={$data->courseid} AND instance=0";
3724 execute_sql($updatesql, false);
3726 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged'), 'error'=>false);
3729 if (!empty($data->reset_logs)) {
3730 delete_records('log', 'course', $data->courseid);
3731 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelogs'), 'error'=>false);
3734 if (!empty($data->reset_events)) {
3735 delete_records('event', 'courseid', $data->courseid);
3736 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteevents', 'calendar'), 'error'=>false);
3739 if (!empty($data->reset_notes)) {
3740 require_once($CFG->dirroot.'/notes/lib.php');
3741 note_delete_all($data->courseid);
3742 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletenotes', 'notes'), 'error'=>false);
3745 $componentstr = get_string('roles');
3747 if (!empty($data->reset_roles_overrides)) {
3748 $children = get_child_contexts($context);
3749 foreach ($children as $child) {
3750 delete_records('role_capabilities', 'contextid', $child->id);
3752 delete_records('role_capabilities', 'contextid', $context->id);
3753 //force refresh for logged in users
3754 mark_context_dirty($context->path);
3755 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletecourseoverrides', 'role'), 'error'=>false);
3758 if (!empty($data->reset_roles_local)) {
3759 $children = get_child_contexts($context);
3760 foreach ($children as $child) {
3761 role_unassign(0, 0, 0, $child->id);
3763 //force refresh for logged in users
3764 mark_context_dirty($context->path);
3765 $status[] = array('component'=>$componentstr, 'item'=>get_string('deletelocalroles', 'role'), 'error'=>false);
3768 // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
3769 $data->unenrolled = array();
3770 if (!empty($data->reset_roles)) {
3771 foreach($data->reset_roles as $roleid) {
3772 if ($users = get_role_users($roleid, $context, false, 'u.id', 'u.id ASC')) {
3773 foreach ($users as $user) {
3774 role_unassign($roleid, $user->id, 0, $context->id);
3775 if (!has_capability('moodle/course:view', $context, $user->id)) {
3776 $data->unenrolled[$user->id] = $user->id;
3782 if (!empty($data->unenrolled)) {
3783 $status[] = array('component'=>$componentstr, 'item'=>get_string('unenrol').' ('.count($data->unenrolled).')', 'error'=>false);
3787 $componentstr = get_string('groups');
3789 // remove all group members
3790 if (!empty($data->reset_groups_members)) {
3791 groups_delete_group_members($data->courseid, false);
3792 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupsmembers', 'group'), 'error'=>false);
3795 // remove all groups
3796 if (!empty($data->reset_groups_remove)) {
3797 groups_delete_groups($data->courseid, false);
3798 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroups', 'group'), 'error'=>false);
3801 // remove all grouping members
3802 if (!empty($data->reset_groupings_members)) {
3803 groups_delete_groupings_groups($data->courseid, false);
3804 $status[] = array('component'=>$componentstr, 'item'=>get_string('removegroupingsmembers', 'group'), 'error'=>false);
3807 // remove all groupings
3808 if (!empty($data->reset_groupings_remove)) {
3809 groups_delete_groupings($data->courseid, false);
3810 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallgroupings', 'group'), 'error'=>false);
3813 // Look in every instance of every module for data to delete
3814 $unsupported_mods = array();
3815 if ($allmods = get_records('modules') ) {
3816 foreach ($allmods as $mod) {
3817 $modname = $mod->name;
3818 if (!count_records($modname, 'course', $data->courseid)) {
3819 continue; // skip mods with no instances
3821 $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
3822 $moddeleteuserdata = $modname.'_reset_userdata'; // Function to delete user data
3823 if (file_exists($modfile)) {
3824 include_once($modfile);
3825 if (function_exists($moddeleteuserdata)) {
3826 $modstatus = $moddeleteuserdata($data);
3827 if (is_array($modstatus)) {
3828 $status = array_merge($status, $modstatus);
3829 } else {
3830 debugging('Module '.$modname.' returned incorrect staus - must be an array!');
3832 } else {
3833 $unsupported_mods[] = $mod;
3835 } else {
3836 debugging('Missing lib.php in '.$modname.' module!');
3841 // mention unsupported mods
3842 if (!empty($unsupported_mods)) {
3843 foreach($unsupported_mods as $mod) {
3844 $status[] = array('component'=>get_string('modulenameplural', $mod->name), 'item'=>'', 'error'=>get_string('resetnotimplemented'));
3849 $componentstr = get_string('gradebook', 'grades');
3850 // reset gradebook
3851 if (!empty($data->reset_gradebook_items)) {
3852 remove_course_grades($data->courseid, false);
3853 grade_grab_course_grades($data->courseid);
3854 grade_regrade_final_grades($data->courseid);
3855 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcourseitems', 'grades'), 'error'=>false);
3857 } else if (!empty($data->reset_gradebook_grades)) {
3858 grade_course_reset($data->courseid);
3859 $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallcoursegrades', 'grades'), 'error'=>false);
3862 return $status;
3865 function generate_email_processing_address($modid,$modargs) {
3866 global $CFG;
3868 if (empty($CFG->siteidentifier)) { // Unique site identification code
3869 set_config('siteidentifier', random_string(32));
3872 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3873 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
3877 function moodle_process_email($modargs,$body) {
3878 // the first char should be an unencoded letter. We'll take this as an action
3879 switch ($modargs{0}) {
3880 case 'B': { // bounce
3881 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3882 if ($user = get_record_select("user","id=$userid","id,email")) {
3883 // check the half md5 of their email
3884 $md5check = substr(md5($user->email),0,16);
3885 if ($md5check == substr($modargs, -16)) {
3886 set_bounce_count($user);
3888 // else maybe they've already changed it?
3891 break;
3892 // maybe more later?
3896 /// CORRESPONDENCE ////////////////////////////////////////////////
3899 * Get mailer instance, enable buffering, flush buffer or disable buffering.
3900 * @param $action string 'get', 'buffer', 'close' or 'flush'
3901 * @return reference to mailer instance if 'get' used or nothing
3903 function &get_mailer($action='get') {
3904 global $CFG;
3906 static $mailer = null;
3907 static $counter = 0;
3909 if (!isset($CFG->smtpmaxbulk)) {
3910 $CFG->smtpmaxbulk = 1;
3913 if ($action == 'get') {
3914 $prevkeepalive = false;
3916 if (isset($mailer) and $mailer->Mailer == 'smtp') {
3917 if ($counter < $CFG->smtpmaxbulk and empty($mailer->error_count)) {
3918 $counter++;
3919 // reset the mailer
3920 $mailer->Priority = 3;
3921 $mailer->CharSet = 'UTF-8'; // our default
3922 $mailer->ContentType = "text/plain";
3923 $mailer->Encoding = "8bit";
3924 $mailer->From = "root@localhost";
3925 $mailer->FromName = "Root User";
3926 $mailer->Sender = "";
3927 $mailer->Subject = "";
3928 $mailer->Body = "";
3929 $mailer->AltBody = "";
3930 $mailer->ConfirmReadingTo = "";
3932 $mailer->ClearAllRecipients();
3933 $mailer->ClearReplyTos();
3934 $mailer->ClearAttachments();
3935 $mailer->ClearCustomHeaders();
3936 return $mailer;
3939 $prevkeepalive = $mailer->SMTPKeepAlive;
3940 get_mailer('flush');
3943 include_once($CFG->libdir.'/phpmailer/class.phpmailer.php');
3944 $mailer = new phpmailer();
3946 $counter = 1;
3948 $mailer->Version = 'Moodle '.$CFG->version; // mailer version
3949 $mailer->PluginDir = $CFG->libdir.'/phpmailer/'; // plugin directory (eg smtp plugin)
3950 $mailer->CharSet = 'UTF-8';
3952 // some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis
3953 // hmm, this is a bit hacky because LE should be private
3954 if (isset($CFG->mailnewline) and $CFG->mailnewline == 'CRLF') {
3955 $mailer->LE = "\r\n";
3956 } else {
3957 $mailer->LE = "\n";
3960 if ($CFG->smtphosts == 'qmail') {
3961 $mailer->IsQmail(); // use Qmail system
3963 } else if (empty($CFG->smtphosts)) {
3964 $mailer->IsMail(); // use PHP mail() = sendmail
3966 } else {
3967 $mailer->IsSMTP(); // use SMTP directly
3968 if (!empty($CFG->debugsmtp)) {
3969 $mailer->SMTPDebug = true;
3971 $mailer->Host = $CFG->smtphosts; // specify main and backup servers
3972 $mailer->SMTPKeepAlive = $prevkeepalive; // use previous keepalive
3974 if ($CFG->smtpuser) { // Use SMTP authentication
3975 $mailer->SMTPAuth = true;
3976 $mailer->Username = $CFG->smtpuser;
3977 $mailer->Password = $CFG->smtppass;
3981 return $mailer;
3984 $nothing = null;
3986 // keep smtp session open after sending
3987 if ($action == 'buffer') {
3988 if (!empty($CFG->smtpmaxbulk)) {
3989 get_mailer('flush');
3990 $m =& get_mailer();
3991 if ($m->Mailer == 'smtp') {
3992 $m->SMTPKeepAlive = true;
3995 return $nothing;
3998 // close smtp session, but continue buffering
3999 if ($action == 'flush') {
4000 if (isset($mailer) and $mailer->Mailer == 'smtp') {
4001 if (!empty($mailer->SMTPDebug)) {
4002 echo '<pre>'."\n";
4004 $mailer->SmtpClose();
4005 if (!empty($mailer->SMTPDebug)) {
4006 echo '</pre>';
4009 return $nothing;
4012 // close smtp session, do not buffer anymore
4013 if ($action == 'close') {
4014 if (isset($mailer) and $mailer->Mailer == 'smtp') {
4015 get_mailer('flush');
4016 $mailer->SMTPKeepAlive = false;
4018 $mailer = null; // better force new instance
4019 return $nothing;
4024 * Send an email to a specified user
4026 * @uses $CFG
4027 * @uses $FULLME
4028 * @uses SITEID
4029 * @param user $user A {@link $USER} object
4030 * @param user $from A {@link $USER} object
4031 * @param string $subject plain text subject line of the email
4032 * @param string $messagetext plain text version of the message
4033 * @param string $messagehtml complete html version of the message (optional)
4034 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
4035 * @param string $attachname the name of the file (extension indicates MIME)
4036 * @param bool $usetrueaddress determines whether $from email address should
4037 * be sent out. Will be overruled by user profile setting for maildisplay
4038 * @param int $wordwrapwidth custom word wrap width
4039 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4040 * was blocked by user and "false" if there was another sort of error.
4042 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='', $wordwrapwidth=79) {
4044 global $CFG, $FULLME;
4046 if (empty($user)) {
4047 return false;
4050 if (!empty($CFG->noemailever)) {
4051 // hidden setting for development sites, set in config.php if needed
4052 return true;
4055 // skip mail to suspended users
4056 if (isset($user->auth) && $user->auth=='nologin') {
4057 return true;
4060 if (!empty($user->emailstop)) {
4061 return 'emailstop';
4064 if (over_bounce_threshold($user)) {
4065 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
4066 return false;
4069 $mail =& get_mailer();
4071 if (!empty($mail->SMTPDebug)) {
4072 echo '<pre>' . "\n";
4075 /// We are going to use textlib services here
4076 $textlib = textlib_get_instance();
4078 $supportuser = generate_email_supportuser();
4080 // make up an email address for handling bounces
4081 if (!empty($CFG->handlebounces)) {
4082 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
4083 $mail->Sender = generate_email_processing_address(0,$modargs);
4084 } else {
4085 $mail->Sender = $supportuser->email;
4088 if (is_string($from)) { // So we can pass whatever we want if there is need
4089 $mail->From = $CFG->noreplyaddress;
4090 $mail->FromName = $from;
4091 } else if ($usetrueaddress and $from->maildisplay) {
4092 $mail->From = $from->email;
4093 $mail->FromName = fullname($from);
4094 } else {
4095 $mail->From = $CFG->noreplyaddress;
4096 $mail->FromName = fullname($from);
4097 if (empty($replyto)) {
4098 $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
4102 if (!empty($replyto)) {
4103 $mail->AddReplyTo($replyto,$replytoname);
4106 $mail->Subject = substr(stripslashes($subject), 0, 900);
4108 $mail->AddAddress($user->email, fullname($user) );
4110 $mail->WordWrap = $wordwrapwidth; // set word wrap
4112 if (!empty($from->customheaders)) { // Add custom headers
4113 if (is_array($from->customheaders)) {
4114 foreach ($from->customheaders as $customheader) {
4115 $mail->AddCustomHeader($customheader);
4117 } else {
4118 $mail->AddCustomHeader($from->customheaders);
4122 if (!empty($from->priority)) {
4123 $mail->Priority = $from->priority;
4126 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
4127 $mail->IsHTML(true);
4128 $mail->Encoding = 'quoted-printable'; // Encoding to use
4129 $mail->Body = $messagehtml;
4130 $mail->AltBody = "\n$messagetext\n";
4131 } else {
4132 $mail->IsHTML(false);
4133 $mail->Body = "\n$messagetext\n";
4136 if ($attachment && $attachname) {
4137 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
4138 $mail->AddAddress($supportuser->email, fullname($supportuser, true) );
4139 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
4140 } else {
4141 require_once($CFG->libdir.'/filelib.php');
4142 $mimetype = mimeinfo('type', $attachname);
4143 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
4149 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
4150 /// encoding to the specified one
4151 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
4152 /// Set it to site mail charset
4153 $charset = $CFG->sitemailcharset;
4154 /// Overwrite it with the user mail charset
4155 if (!empty($CFG->allowusermailcharset)) {
4156 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
4157 $charset = $useremailcharset;
4160 /// If it has changed, convert all the necessary strings
4161 $charsets = get_list_of_charsets();
4162 unset($charsets['UTF-8']);
4163 if (in_array($charset, $charsets)) {
4164 /// Save the new mail charset
4165 $mail->CharSet = $charset;
4166 /// And convert some strings
4167 $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
4168 foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names
4169 $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet);
4171 $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject
4172 foreach ($mail->to as $key => $to) {
4173 $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet); //To Names
4175 $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body
4176 $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject
4180 if ($mail->Send()) {
4181 set_send_count($user);
4182 $mail->IsSMTP(); // use SMTP directly
4183 if (!empty($mail->SMTPDebug)) {
4184 echo '</pre>';
4186 return true;
4187 } else {
4188 mtrace('ERROR: '. $mail->ErrorInfo);
4189 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
4190 if (!empty($mail->SMTPDebug)) {
4191 echo '</pre>';
4193 return false;
4198 * Generate a signoff for emails based on support settings
4201 function generate_email_signoff() {
4202 global $CFG;
4204 $signoff = "\n";
4205 if (!empty($CFG->supportname)) {
4206 $signoff .= $CFG->supportname."\n";
4208 if (!empty($CFG->supportemail)) {
4209 $signoff .= $CFG->supportemail."\n";
4211 if (!empty($CFG->supportpage)) {
4212 $signoff .= $CFG->supportpage."\n";
4214 return $signoff;
4218 * Generate a fake user for emails based on support settings
4221 function generate_email_supportuser() {
4223 global $CFG;
4225 static $supportuser;
4227 if (!empty($supportuser)) {
4228 return $supportuser;
4231 $supportuser = new object;
4232 $supportuser->email = $CFG->supportemail ? $CFG->supportemail : $CFG->noreplyaddress;
4233 $supportuser->firstname = $CFG->supportname ? $CFG->supportname : get_string('noreplyname');
4234 $supportuser->lastname = '';
4235 $supportuser->maildisplay = true;
4237 return $supportuser;
4242 * Sets specified user's password and send the new password to the user via email.
4244 * @uses $CFG
4245 * @param user $user A {@link $USER} object
4246 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
4247 * was blocked by user and "false" if there was another sort of error.
4249 function setnew_password_and_mail($user) {
4251 global $CFG;
4253 $site = get_site();
4255 $supportuser = generate_email_supportuser();
4257 $newpassword = generate_password();
4259 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
4260 trigger_error('Could not set user password!');
4261 return false;
4264 $a = new object();
4265 $a->firstname = fullname($user, true);
4266 $a->sitename = format_string($site->fullname);
4267 $a->username = $user->username;
4268 $a->newpassword = $newpassword;
4269 $a->link = $CFG->wwwroot .'/login/';
4270 $a->signoff = generate_email_signoff();
4272 $message = get_string('newusernewpasswordtext', '', $a);
4274 $subject = format_string($site->fullname) .': '. get_string('newusernewpasswordsubj');
4276 return email_to_user($user, $supportuser, $subject, $message);
4281 * Resets specified user's password and send the new password to the user via email.
4283 * @uses $CFG
4284 * @param user $user A {@link $USER} object
4285 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4286 * was blocked by user and "false" if there was another sort of error.
4288 function reset_password_and_mail($user) {
4290 global $CFG;
4292 $site = get_site();
4293 $supportuser = generate_email_supportuser();
4295 $userauth = get_auth_plugin($user->auth);
4296 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
4297 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
4298 return false;
4301 $newpassword = generate_password();
4303 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
4304 error("Could not set user password!");
4307 $a = new object();
4308 $a->firstname = $user->firstname;
4309 $a->sitename = format_string($site->fullname);
4310 $a->username = $user->username;
4311 $a->newpassword = $newpassword;
4312 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
4313 $a->signoff = generate_email_signoff();
4315 $message = get_string('newpasswordtext', '', $a);
4317 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
4319 return email_to_user($user, $supportuser, $subject, $message);
4324 * Send email to specified user with confirmation text and activation link.
4326 * @uses $CFG
4327 * @param user $user A {@link $USER} object
4328 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4329 * was blocked by user and "false" if there was another sort of error.
4331 function send_confirmation_email($user) {
4333 global $CFG;
4335 $site = get_site();
4336 $supportuser = generate_email_supportuser();
4338 $data = new object();
4339 $data->firstname = fullname($user);
4340 $data->sitename = format_string($site->fullname);
4341 $data->admin = generate_email_signoff();
4343 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
4345 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. urlencode($user->username);
4346 $message = get_string('emailconfirmation', '', $data);
4347 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
4349 $user->mailformat = 1; // Always send HTML version as well
4351 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
4356 * send_password_change_confirmation_email.
4358 * @uses $CFG
4359 * @param user $user A {@link $USER} object
4360 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4361 * was blocked by user and "false" if there was another sort of error.
4363 function send_password_change_confirmation_email($user) {
4365 global $CFG;
4367 $site = get_site();
4368 $supportuser = generate_email_supportuser();
4370 $data = new object();
4371 $data->firstname = $user->firstname;
4372 $data->sitename = format_string($site->fullname);
4373 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
4374 $data->admin = generate_email_signoff();
4376 $message = get_string('emailpasswordconfirmation', '', $data);
4377 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
4379 return email_to_user($user, $supportuser, $subject, $message);
4384 * send_password_change_info.
4386 * @uses $CFG
4387 * @param user $user A {@link $USER} object
4388 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
4389 * was blocked by user and "false" if there was another sort of error.
4391 function send_password_change_info($user) {
4393 global $CFG;
4395 $site = get_site();
4396 $supportuser = generate_email_supportuser();
4397 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
4399 $data = new object();
4400 $data->firstname = $user->firstname;
4401 $data->sitename = format_string($site->fullname);
4402 $data->admin = generate_email_signoff();
4404 $userauth = get_auth_plugin($user->auth);
4406 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
4407 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
4408 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
4409 return email_to_user($user, $supportuser, $subject, $message);
4412 if ($userauth->can_change_password() and $userauth->change_password_url()) {
4413 // we have some external url for password changing
4414 $data->link .= $userauth->change_password_url();
4416 } else {
4417 //no way to change password, sorry
4418 $data->link = '';
4421 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
4422 $message = get_string('emailpasswordchangeinfo', '', $data);
4423 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
4424 } else {
4425 $message = get_string('emailpasswordchangeinfofail', '', $data);
4426 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
4429 return email_to_user($user, $supportuser, $subject, $message);
4434 * Check that an email is allowed. It returns an error message if there
4435 * was a problem.
4437 * @uses $CFG
4438 * @param string $email Content of email
4439 * @return string|false
4441 function email_is_not_allowed($email) {
4443 global $CFG;
4445 if (!empty($CFG->allowemailaddresses)) {
4446 $allowed = explode(' ', $CFG->allowemailaddresses);
4447 foreach ($allowed as $allowedpattern) {
4448 $allowedpattern = trim($allowedpattern);
4449 if (!$allowedpattern) {
4450 continue;
4452 if (strpos($allowedpattern, '.') === 0) {
4453 if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
4454 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
4455 return false;
4458 } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
4459 return false;
4462 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
4464 } else if (!empty($CFG->denyemailaddresses)) {
4465 $denied = explode(' ', $CFG->denyemailaddresses);
4466 foreach ($denied as $deniedpattern) {
4467 $deniedpattern = trim($deniedpattern);
4468 if (!$deniedpattern) {
4469 continue;
4471 if (strpos($deniedpattern, '.') === 0) {
4472 if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
4473 // subdomains are in a form ".example.com" - matches "xxx@anything.example.com"
4474 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
4477 } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
4478 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
4483 return false;
4486 function email_welcome_message_to_user($course, $user=NULL) {
4487 global $CFG, $USER;
4489 if (empty($user)) {
4490 if (!isloggedin()) {
4491 return false;
4493 $user = $USER;
4496 if (!empty($course->welcomemessage)) {
4497 $message = $course->welcomemessage;
4498 } else {
4499 $a = new Object();
4500 $a->coursename = $course->fullname;
4501 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
4502 $message = get_string("welcometocoursetext", "", $a);
4505 /// If you don't want a welcome message sent, then make the message string blank.
4506 if (!empty($message)) {
4507 $subject = get_string('welcometocourse', '', format_string($course->fullname));
4509 if (! $teacher = get_teacher($course->id)) {
4510 $teacher = get_admin();
4512 email_to_user($user, $teacher, $subject, $message);
4516 /// FILE HANDLING /////////////////////////////////////////////
4520 * Makes an upload directory for a particular module.
4522 * @uses $CFG
4523 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
4524 * @return string|false Returns full path to directory if successful, false if not
4526 function make_mod_upload_directory($courseid) {
4527 global $CFG;
4529 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
4530 return false;
4533 $strreadme = get_string('readme');
4535 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
4536 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4537 } else {
4538 copy($CFG->dirroot .'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4540 return $moddata;
4544 * Makes a directory for a particular user.
4546 * @uses $CFG
4547 * @param int $userid The id of the user in question - maps to id field of 'user' table.
4548 * @param bool $test Whether we are only testing the return value (do not create the directory)
4549 * @return string|false Returns full path to directory if successful, false if not
4551 function make_user_directory($userid, $test=false) {
4552 global $CFG;
4554 if (is_bool($userid) || $userid < 0 || !ereg('^[0-9]{1,10}$', $userid) || $userid > 2147483647) {
4555 if (!$test) {
4556 notify("Given userid was not a valid integer! (" . gettype($userid) . " $userid)");
4558 return false;
4561 // Generate a two-level path for the userid. First level groups them by slices of 1000 users, second level is userid
4562 $level1 = floor($userid / 1000) * 1000;
4564 $userdir = "user/$level1/$userid";
4565 if ($test) {
4566 return $CFG->dataroot . '/' . $userdir;
4567 } else {
4568 return make_upload_directory($userdir);
4573 * Returns an array of full paths to user directories, indexed by their userids.
4575 * @param bool $only_non_empty Only return directories that contain files
4576 * @param bool $legacy Search for user directories in legacy location (dataroot/users/userid) instead of (dataroot/user/section/userid)
4577 * @return array An associative array: userid=>array(basedir => $basedir, userfolder => $userfolder)
4579 function get_user_directories($only_non_empty=true, $legacy=false) {
4580 global $CFG;
4582 $rootdir = $CFG->dataroot."/user";
4584 if ($legacy) {
4585 $rootdir = $CFG->dataroot."/users";
4587 $dirlist = array();
4589 //Check if directory exists
4590 if (check_dir_exists($rootdir, true)) {
4591 if ($legacy) {
4592 if ($userlist = get_directory_list($rootdir, '', true, true, false)) {
4593 foreach ($userlist as $userid) {
4594 $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $userid);
4596 } else {
4597 notify("no directories found under $rootdir");
4599 } else {
4600 if ($grouplist =get_directory_list($rootdir, '', true, true, false)) { // directories will be in the form 0, 1000, 2000 etc...
4601 foreach ($grouplist as $group) {
4602 if ($userlist = get_directory_list("$rootdir/$group", '', true, true, false)) {
4603 foreach ($userlist as $userid) {
4604 $dirlist[$userid] = array('basedir' => $rootdir, 'userfolder' => $group . '/' . $userid);
4610 } else {
4611 notify("$rootdir does not exist!");
4612 return false;
4614 return $dirlist;
4618 * Returns current name of file on disk if it exists.
4620 * @param string $newfile File to be verified
4621 * @return string Current name of file on disk if true
4623 function valid_uploaded_file($newfile) {
4624 if (empty($newfile)) {
4625 return '';
4627 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
4628 return $newfile['tmp_name'];
4629 } else {
4630 return '';
4635 * Returns the maximum size for uploading files.
4637 * There are seven possible upload limits:
4638 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
4639 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
4640 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
4641 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
4642 * 5. by the Moodle admin in $CFG->maxbytes
4643 * 6. by the teacher in the current course $course->maxbytes
4644 * 7. by the teacher for the current module, eg $assignment->maxbytes
4646 * These last two are passed to this function as arguments (in bytes).
4647 * Anything defined as 0 is ignored.
4648 * The smallest of all the non-zero numbers is returned.
4650 * @param int $sizebytes ?
4651 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4652 * @param int $modulebytes Current module ->maxbytes (in bytes)
4653 * @return int The maximum size for uploading files.
4654 * @todo Finish documenting this function
4656 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4658 if (! $filesize = ini_get('upload_max_filesize')) {
4659 $filesize = '5M';
4661 $minimumsize = get_real_size($filesize);
4663 if ($postsize = ini_get('post_max_size')) {
4664 $postsize = get_real_size($postsize);
4665 if ($postsize < $minimumsize) {
4666 $minimumsize = $postsize;
4670 if ($sitebytes and $sitebytes < $minimumsize) {
4671 $minimumsize = $sitebytes;
4674 if ($coursebytes and $coursebytes < $minimumsize) {
4675 $minimumsize = $coursebytes;
4678 if ($modulebytes and $modulebytes < $minimumsize) {
4679 $minimumsize = $modulebytes;
4682 return $minimumsize;
4686 * Related to {@link get_max_upload_file_size()} - this function returns an
4687 * array of possible sizes in an array, translated to the
4688 * local language.
4690 * @uses SORT_NUMERIC
4691 * @param int $sizebytes ?
4692 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4693 * @param int $modulebytes Current module ->maxbytes (in bytes)
4694 * @return int
4695 * @todo Finish documenting this function
4697 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4698 global $CFG;
4700 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
4701 return array();
4704 $filesize[$maxsize] = display_size($maxsize);
4706 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4707 5242880, 10485760, 20971520, 52428800, 104857600);
4709 // Allow maxbytes to be selected if it falls outside the above boundaries
4710 if( isset($CFG->maxbytes) && !in_array($CFG->maxbytes, $sizelist) ){
4711 $sizelist[] = $CFG->maxbytes;
4714 foreach ($sizelist as $sizebytes) {
4715 if ($sizebytes < $maxsize) {
4716 $filesize[$sizebytes] = display_size($sizebytes);
4720 krsort($filesize, SORT_NUMERIC);
4722 return $filesize;
4726 * If there has been an error uploading a file, print the appropriate error message
4727 * Numerical constants used as constant definitions not added until PHP version 4.2.0
4729 * $filearray is a 1-dimensional sub-array of the $_FILES array
4730 * eg $filearray = $_FILES['userfile1']
4731 * If left empty then the first element of the $_FILES array will be used
4733 * @uses $_FILES
4734 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
4735 * @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.
4736 * @return bool|string
4738 function print_file_upload_error($filearray = '', $returnerror = false) {
4740 if ($filearray == '' or !isset($filearray['error'])) {
4742 if (empty($_FILES)) return false;
4744 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
4745 $filearray = array_shift($files); /// use first element of array
4748 switch ($filearray['error']) {
4750 case 0: // UPLOAD_ERR_OK
4751 if ($filearray['size'] > 0) {
4752 $errmessage = get_string('uploadproblem', $filearray['name']);
4753 } else {
4754 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
4756 break;
4758 case 1: // UPLOAD_ERR_INI_SIZE
4759 $errmessage = get_string('uploadserverlimit');
4760 break;
4762 case 2: // UPLOAD_ERR_FORM_SIZE
4763 $errmessage = get_string('uploadformlimit');
4764 break;
4766 case 3: // UPLOAD_ERR_PARTIAL
4767 $errmessage = get_string('uploadpartialfile');
4768 break;
4770 case 4: // UPLOAD_ERR_NO_FILE
4771 $errmessage = get_string('uploadnofilefound');
4772 break;
4774 default:
4775 $errmessage = get_string('uploadproblem', $filearray['name']);
4778 if ($returnerror) {
4779 return $errmessage;
4780 } else {
4781 notify($errmessage);
4782 return true;
4788 * handy function to loop through an array of files and resolve any filename conflicts
4789 * both in the array of filenames and for what is already on disk.
4790 * not really compatible with the similar function in uploadlib.php
4791 * but this could be used for files/index.php for moving files around.
4794 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4795 foreach ($files as $k => $f) {
4796 if (check_potential_filename($destination,$f,$files)) {
4797 $bits = explode('.', $f);
4798 for ($i = 1; true; $i++) {
4799 $try = sprintf($format, $bits[0], $i, $bits[1]);
4800 if (!check_potential_filename($destination,$try,$files)) {
4801 $files[$k] = $try;
4802 break;
4807 return $files;
4811 * @used by resolve_filename_collisions
4813 function check_potential_filename($destination,$filename,$files) {
4814 if (file_exists($destination.'/'.$filename)) {
4815 return true;
4817 if (count(array_keys($files,$filename)) > 1) {
4818 return true;
4820 return false;
4825 * Returns an array with all the filenames in
4826 * all subdirectories, relative to the given rootdir.
4827 * If excludefile is defined, then that file/directory is ignored
4828 * If getdirs is true, then (sub)directories are included in the output
4829 * If getfiles is true, then files are included in the output
4830 * (at least one of these must be true!)
4832 * @param string $rootdir ?
4833 * @param string $excludefile If defined then the specified file/directory is ignored
4834 * @param bool $descend ?
4835 * @param bool $getdirs If true then (sub)directories are included in the output
4836 * @param bool $getfiles If true then files are included in the output
4837 * @return array An array with all the filenames in
4838 * all subdirectories, relative to the given rootdir
4839 * @todo Finish documenting this function. Add examples of $excludefile usage.
4841 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4843 $dirs = array();
4845 if (!$getdirs and !$getfiles) { // Nothing to show
4846 return $dirs;
4849 if (!is_dir($rootdir)) { // Must be a directory
4850 return $dirs;
4853 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4854 return $dirs;
4857 if (!is_array($excludefiles)) {
4858 $excludefiles = array($excludefiles);
4861 while (false !== ($file = readdir($dir))) {
4862 $firstchar = substr($file, 0, 1);
4863 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4864 continue;
4866 $fullfile = $rootdir .'/'. $file;
4867 if (filetype($fullfile) == 'dir') {
4868 if ($getdirs) {
4869 $dirs[] = $file;
4871 if ($descend) {
4872 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4873 foreach ($subdirs as $subdir) {
4874 $dirs[] = $file .'/'. $subdir;
4877 } else if ($getfiles) {
4878 $dirs[] = $file;
4881 closedir($dir);
4883 asort($dirs);
4885 return $dirs;
4890 * Adds up all the files in a directory and works out the size.
4892 * @param string $rootdir ?
4893 * @param string $excludefile ?
4894 * @return array
4895 * @todo Finish documenting this function
4897 function get_directory_size($rootdir, $excludefile='') {
4899 global $CFG;
4901 // do it this way if we can, it's much faster
4902 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
4903 $command = trim($CFG->pathtodu).' -sk --apparent-size '.escapeshellarg($rootdir);
4904 $output = null;
4905 $return = null;
4906 exec($command,$output,$return);
4907 if (is_array($output)) {
4908 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4912 if (!is_dir($rootdir)) { // Must be a directory
4913 return 0;
4916 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
4917 return 0;
4920 $size = 0;
4922 while (false !== ($file = readdir($dir))) {
4923 $firstchar = substr($file, 0, 1);
4924 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4925 continue;
4927 $fullfile = $rootdir .'/'. $file;
4928 if (filetype($fullfile) == 'dir') {
4929 $size += get_directory_size($fullfile, $excludefile);
4930 } else {
4931 $size += filesize($fullfile);
4934 closedir($dir);
4936 return $size;
4940 * Converts bytes into display form
4942 * @param string $size ?
4943 * @return string
4944 * @staticvar string $gb Localized string for size in gigabytes
4945 * @staticvar string $mb Localized string for size in megabytes
4946 * @staticvar string $kb Localized string for size in kilobytes
4947 * @staticvar string $b Localized string for size in bytes
4948 * @todo Finish documenting this function. Verify return type.
4950 function display_size($size) {
4952 static $gb, $mb, $kb, $b;
4954 if (empty($gb)) {
4955 $gb = get_string('sizegb');
4956 $mb = get_string('sizemb');
4957 $kb = get_string('sizekb');
4958 $b = get_string('sizeb');
4961 if ($size >= 1073741824) {
4962 $size = round($size / 1073741824 * 10) / 10 . $gb;
4963 } else if ($size >= 1048576) {
4964 $size = round($size / 1048576 * 10) / 10 . $mb;
4965 } else if ($size >= 1024) {
4966 $size = round($size / 1024 * 10) / 10 . $kb;
4967 } else {
4968 $size = $size .' '. $b;
4970 return $size;
4974 * Cleans a given filename by removing suspicious or troublesome characters
4975 * Only these are allowed: alphanumeric _ - .
4976 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4978 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4979 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4981 * @param string $string file name
4982 * @return string cleaned file name
4984 function clean_filename($string) {
4985 global $CFG;
4986 if (empty($CFG->unicodecleanfilename)) {
4987 $textlib = textlib_get_instance();
4988 $string = $textlib->specialtoascii($string);
4989 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4990 } else {
4991 //clean only ascii range
4992 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4994 $string = preg_replace("/_+/", '_', $string);
4995 $string = preg_replace("/\.\.+/", '.', $string);
4996 return $string;
5000 /// STRING TRANSLATION ////////////////////////////////////////
5003 * Returns the code for the current language
5005 * @uses $CFG
5006 * @param $USER
5007 * @param $SESSION
5008 * @return string
5010 function current_language() {
5011 global $CFG, $USER, $SESSION, $COURSE;
5013 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
5014 $return = $COURSE->lang;
5016 } else if (!empty($SESSION->lang)) { // Session language can override other settings
5017 $return = $SESSION->lang;
5019 } else if (!empty($USER->lang)) {
5020 $return = $USER->lang;
5022 } else {
5023 $return = $CFG->lang;
5026 if ($return == 'en') {
5027 $return = 'en_utf8';
5030 return $return;
5034 * Prints out a translated string.
5036 * Prints out a translated string using the return value from the {@link get_string()} function.
5038 * Example usage of this function when the string is in the moodle.php file:<br/>
5039 * <code>
5040 * echo '<strong>';
5041 * print_string('wordforstudent');
5042 * echo '</strong>';
5043 * </code>
5045 * Example usage of this function when the string is not in the moodle.php file:<br/>
5046 * <code>
5047 * echo '<h1>';
5048 * print_string('typecourse', 'calendar');
5049 * echo '</h1>';
5050 * </code>
5052 * @param string $identifier The key identifier for the localized string
5053 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
5054 * @param mixed $a An object, string or number that can be used
5055 * within translation strings
5057 function print_string($identifier, $module='', $a=NULL) {
5058 echo get_string($identifier, $module, $a);
5062 * fix up the optional data in get_string()/print_string() etc
5063 * ensure possible sprintf() format characters are escaped correctly
5064 * needs to handle arbitrary strings and objects
5065 * @param mixed $a An object, string or number that can be used
5066 * @return mixed the supplied parameter 'cleaned'
5068 function clean_getstring_data( $a ) {
5069 if (is_string($a)) {
5070 return str_replace( '%','%%',$a );
5072 elseif (is_object($a)) {
5073 $a_vars = get_object_vars( $a );
5074 $new_a_vars = array();
5075 foreach ($a_vars as $fname => $a_var) {
5076 $new_a_vars[$fname] = clean_getstring_data( $a_var );
5078 return (object)$new_a_vars;
5080 else {
5081 return $a;
5086 * @return array places to look for lang strings based on the prefix to the
5087 * module name. For example qtype_ in question/type. Used by get_string and
5088 * help.php.
5090 function places_to_search_for_lang_strings() {
5091 global $CFG;
5093 return array(
5094 '__exceptions' => array('moodle', 'langconfig'),
5095 'assignment_' => array('mod/assignment/type'),
5096 'auth_' => array('auth'),
5097 'block_' => array('blocks'),
5098 'datafield_' => array('mod/data/field'),
5099 'datapreset_' => array('mod/data/preset'),
5100 'enrol_' => array('enrol'),
5101 'filter_' => array('filter'),
5102 'format_' => array('course/format'),
5103 'qtype_' => array('question/type'),
5104 'report_' => array($CFG->admin.'/report', 'course/report', 'mod/quiz/report'),
5105 'resource_' => array('mod/resource/type'),
5106 'gradereport_' => array('grade/report'),
5107 'gradeimport_' => array('grade/import'),
5108 'gradeexport_' => array('grade/export'),
5109 'profilefield_' => array('user/profile/field'),
5110 '' => array('mod')
5115 * Returns a localized string.
5117 * Returns the translated string specified by $identifier as
5118 * for $module. Uses the same format files as STphp.
5119 * $a is an object, string or number that can be used
5120 * within translation strings
5122 * eg "hello \$a->firstname \$a->lastname"
5123 * or "hello \$a"
5125 * If you would like to directly echo the localized string use
5126 * the function {@link print_string()}
5128 * Example usage of this function involves finding the string you would
5129 * like a local equivalent of and using its identifier and module information
5130 * to retrive it.<br/>
5131 * If you open moodle/lang/en/moodle.php and look near line 1031
5132 * you will find a string to prompt a user for their word for student
5133 * <code>
5134 * $string['wordforstudent'] = 'Your word for Student';
5135 * </code>
5136 * So if you want to display the string 'Your word for student'
5137 * in any language that supports it on your site
5138 * you just need to use the identifier 'wordforstudent'
5139 * <code>
5140 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
5142 * </code>
5143 * If the string you want is in another file you'd take a slightly
5144 * different approach. Looking in moodle/lang/en/calendar.php you find
5145 * around line 75:
5146 * <code>
5147 * $string['typecourse'] = 'Course event';
5148 * </code>
5149 * If you want to display the string "Course event" in any language
5150 * supported you would use the identifier 'typecourse' and the module 'calendar'
5151 * (because it is in the file calendar.php):
5152 * <code>
5153 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
5154 * </code>
5156 * As a last resort, should the identifier fail to map to a string
5157 * the returned string will be [[ $identifier ]]
5159 * @uses $CFG
5160 * @param string $identifier The key identifier for the localized string
5161 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
5162 * @param mixed $a An object, string or number that can be used
5163 * within translation strings
5164 * @param array $extralocations An array of strings with other locations to look for string files
5165 * @return string The localized string.
5167 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
5169 global $CFG;
5171 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
5172 $langconfigstrs = array('alphabet', 'backupnameformat', 'decsep', 'firstdayofweek', 'listsep', 'locale',
5173 'localewin', 'localewincharset', 'oldcharset',
5174 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
5175 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
5176 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
5177 'thischarset', 'thisdirection', 'thislanguage', 'strftimedatetimeshort');
5179 $filetocheck = 'langconfig.php';
5180 $defaultlang = 'en_utf8';
5181 if (in_array($identifier, $langconfigstrs)) {
5182 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
5185 $lang = current_language();
5187 if ($module == '') {
5188 $module = 'moodle';
5191 // if $a happens to have % in it, double it so sprintf() doesn't break
5192 if ($a) {
5193 $a = clean_getstring_data( $a );
5196 /// Define the two or three major locations of language strings for this module
5197 $locations = array();
5199 if (!empty($extralocations)) { // Calling code has a good idea where to look
5200 if (is_array($extralocations)) {
5201 $locations += $extralocations;
5202 } else if (is_string($extralocations)) {
5203 $locations[] = $extralocations;
5204 } else {
5205 debugging('Bad lang path provided');
5209 if (isset($CFG->running_installer)) {
5210 $module = 'installer';
5211 $filetocheck = 'installer.php';
5212 $locations[] = $CFG->dirroot.'/install/lang/';
5213 $locations[] = $CFG->dataroot.'/lang/';
5214 $locations[] = $CFG->dirroot.'/lang/';
5215 $defaultlang = 'en_utf8';
5216 } else {
5217 $locations[] = $CFG->dataroot.'/lang/';
5218 $locations[] = $CFG->dirroot.'/lang/';
5219 $locations[] = $CFG->dirroot.'/local/lang/';
5222 /// Add extra places to look for strings for particular plugin types.
5223 $rules = places_to_search_for_lang_strings();
5224 $exceptions = $rules['__exceptions'];
5225 unset($rules['__exceptions']);
5227 if (!in_array($module, $exceptions)) {
5228 $dividerpos = strpos($module, '_');
5229 if ($dividerpos === false) {
5230 $type = '';
5231 $plugin = $module;
5232 } else {
5233 $type = substr($module, 0, $dividerpos + 1);
5234 $plugin = substr($module, $dividerpos + 1);
5236 if (!empty($rules[$type])) {
5237 foreach ($rules[$type] as $location) {
5238 $locations[] = $CFG->dirroot . "/$location/$plugin/lang/";
5243 /// First check all the normal locations for the string in the current language
5244 $resultstring = '';
5245 foreach ($locations as $location) {
5246 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
5247 if (file_exists($locallangfile)) {
5248 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5249 if (eval($result) === FALSE) {
5250 trigger_error('Lang error: '.$identifier.':'.$locallangfile, E_USER_NOTICE);
5252 return $resultstring;
5255 //if local directory not found, or particular string does not exist in local direcotry
5256 $langfile = $location.$lang.'/'.$module.'.php';
5257 if (file_exists($langfile)) {
5258 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5259 if (eval($result) === FALSE) {
5260 trigger_error('Lang error: '.$identifier.':'.$langfile, E_USER_NOTICE);
5262 return $resultstring;
5267 /// If the preferred language was English (utf8) we can abort now
5268 /// saving some checks beacuse it's the only "root" lang
5269 if ($lang == 'en_utf8') {
5270 return '[['. $identifier .']]';
5273 /// Is a parent language defined? If so, try to find this string in a parent language file
5275 foreach ($locations as $location) {
5276 $langfile = $location.$lang.'/'.$filetocheck;
5277 if (file_exists($langfile)) {
5278 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
5279 eval($result);
5280 if (!empty($parentlang)) { // found it!
5282 //first, see if there's a local file for parent
5283 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
5284 if (file_exists($locallangfile)) {
5285 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5286 eval($result);
5287 return $resultstring;
5291 //if local directory not found, or particular string does not exist in local direcotry
5292 $langfile = $location.$parentlang.'/'.$module.'.php';
5293 if (file_exists($langfile)) {
5294 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5295 eval($result);
5296 return $resultstring;
5304 /// Our only remaining option is to try English
5306 foreach ($locations as $location) {
5307 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
5308 if (file_exists($locallangfile)) {
5309 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5310 eval($result);
5311 return $resultstring;
5315 //if local_en not found, or string not found in local_en
5316 $langfile = $location.$defaultlang.'/'.$module.'.php';
5318 if (file_exists($langfile)) {
5319 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5320 eval($result);
5321 return $resultstring;
5326 /// And, because under 1.6 en is defined as en_utf8 child, me must try
5327 /// if it hasn't been queried before.
5328 if ($defaultlang == 'en') {
5329 $defaultlang = 'en_utf8';
5330 foreach ($locations as $location) {
5331 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
5332 if (file_exists($locallangfile)) {
5333 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
5334 eval($result);
5335 return $resultstring;
5339 //if local_en not found, or string not found in local_en
5340 $langfile = $location.$defaultlang.'/'.$module.'.php';
5342 if (file_exists($langfile)) {
5343 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
5344 eval($result);
5345 return $resultstring;
5351 return '[['.$identifier.']]'; // Last resort
5355 * This function is only used from {@link get_string()}.
5357 * @internal Only used from get_string, not meant to be public API
5358 * @param string $identifier ?
5359 * @param string $langfile ?
5360 * @param string $destination ?
5361 * @return string|false ?
5362 * @staticvar array $strings Localized strings
5363 * @access private
5364 * @todo Finish documenting this function.
5366 function get_string_from_file($identifier, $langfile, $destination) {
5368 static $strings; // Keep the strings cached in memory.
5370 if (empty($strings[$langfile])) {
5371 $string = array();
5372 include ($langfile);
5373 $strings[$langfile] = $string;
5374 } else {
5375 $string = &$strings[$langfile];
5378 if (!isset ($string[$identifier])) {
5379 return false;
5382 return $destination .'= sprintf("'. $string[$identifier] .'");';
5386 * Converts an array of strings to their localized value.
5388 * @param array $array An array of strings
5389 * @param string $module The language module that these strings can be found in.
5390 * @return string
5392 function get_strings($array, $module='') {
5394 $string = NULL;
5395 foreach ($array as $item) {
5396 $string->$item = get_string($item, $module);
5398 return $string;
5402 * Returns a list of language codes and their full names
5403 * hides the _local files from everyone.
5404 * @param bool refreshcache force refreshing of lang cache
5405 * @param bool returnall ignore langlist, return all languages available
5406 * @return array An associative array with contents in the form of LanguageCode => LanguageName
5408 function get_list_of_languages($refreshcache=false, $returnall=false) {
5410 global $CFG;
5412 $languages = array();
5414 $filetocheck = 'langconfig.php';
5416 if (!$refreshcache && !$returnall && !empty($CFG->langcache) && file_exists($CFG->dataroot .'/cache/languages')) {
5417 /// read available langs from cache
5419 $lines = file($CFG->dataroot .'/cache/languages');
5420 foreach ($lines as $line) {
5421 $line = trim($line);
5422 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
5423 $languages[$matches[1]] = $matches[2];
5426 unset($lines); unset($line); unset($matches);
5427 return $languages;
5430 if (!$returnall && !empty($CFG->langlist)) {
5431 /// return only languages allowed in langlist admin setting
5433 $langlist = explode(',', $CFG->langlist);
5434 // fix short lang names first - non existing langs are skipped anyway...
5435 foreach ($langlist as $lang) {
5436 if (strpos($lang, '_utf8') === false) {
5437 $langlist[] = $lang.'_utf8';
5440 // find existing langs from langlist
5441 foreach ($langlist as $lang) {
5442 $lang = trim($lang); //Just trim spaces to be a bit more permissive
5443 if (strstr($lang, '_local')!==false) {
5444 continue;
5446 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
5447 $shortlang = substr($lang, 0, -5);
5448 } else {
5449 $shortlang = $lang;
5451 /// Search under dirroot/lang
5452 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
5453 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
5454 if (!empty($string['thislanguage'])) {
5455 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
5457 unset($string);
5459 /// And moodledata/lang
5460 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
5461 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
5462 if (!empty($string['thislanguage'])) {
5463 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
5465 unset($string);
5469 } else {
5470 /// return all languages available in system
5471 /// Fetch langs from moodle/lang directory
5472 $langdirs = get_list_of_plugins('lang');
5473 /// Fetch langs from moodledata/lang directory
5474 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot);
5475 /// Merge both lists of langs
5476 $langdirs = array_merge($langdirs, $langdirs2);
5477 /// Sort all
5478 asort($langdirs);
5479 /// Get some info from each lang (first from moodledata, then from moodle)
5480 foreach ($langdirs as $lang) {
5481 if (strstr($lang, '_local')!==false) {
5482 continue;
5484 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
5485 $shortlang = substr($lang, 0, -5);
5486 } else {
5487 $shortlang = $lang;
5489 /// Search under moodledata/lang
5490 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
5491 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
5492 if (!empty($string['thislanguage'])) {
5493 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
5495 unset($string);
5497 /// And dirroot/lang
5498 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
5499 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
5500 if (!empty($string['thislanguage'])) {
5501 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
5503 unset($string);
5508 if ($refreshcache && !empty($CFG->langcache)) {
5509 if ($returnall) {
5510 // we have a list of all langs only, just delete old cache
5511 @unlink($CFG->dataroot.'/cache/languages');
5513 } else {
5514 // store the list of allowed languages
5515 if ($file = fopen($CFG->dataroot .'/cache/languages', 'w')) {
5516 foreach ($languages as $key => $value) {
5517 fwrite($file, "$key $value\n");
5519 fclose($file);
5524 return $languages;
5528 * Returns a list of charset codes. It's hardcoded, so they should be added manually
5529 * (cheking that such charset is supported by the texlib library!)
5531 * @return array And associative array with contents in the form of charset => charset
5533 function get_list_of_charsets() {
5535 $charsets = array(
5536 'EUC-JP' => 'EUC-JP',
5537 'ISO-2022-JP'=> 'ISO-2022-JP',
5538 'ISO-8859-1' => 'ISO-8859-1',
5539 'SHIFT-JIS' => 'SHIFT-JIS',
5540 'GB2312' => 'GB2312',
5541 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
5542 'UTF-8' => 'UTF-8');
5544 asort($charsets);
5546 return $charsets;
5550 * Returns a list of country names in the current language
5552 * @uses $CFG
5553 * @uses $USER
5554 * @return array
5556 function get_list_of_countries() {
5557 global $CFG, $USER;
5559 $lang = current_language();
5561 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php') &&
5562 !file_exists($CFG->dataroot.'/lang/'. $lang .'/countries.php')) {
5563 if ($parentlang = get_string('parentlanguage')) {
5564 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/countries.php') ||
5565 file_exists($CFG->dataroot.'/lang/'. $parentlang .'/countries.php')) {
5566 $lang = $parentlang;
5567 } else {
5568 $lang = 'en_utf8'; // countries.php must exist in this pack
5570 } else {
5571 $lang = 'en_utf8'; // countries.php must exist in this pack
5575 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/countries.php')) {
5576 include($CFG->dataroot .'/lang/'. $lang .'/countries.php');
5577 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
5578 include($CFG->dirroot .'/lang/'. $lang .'/countries.php');
5581 if (!empty($string)) {
5582 uasort($string, 'strcoll');
5585 return $string;
5589 * Returns a list of valid and compatible themes
5591 * @uses $CFG
5592 * @return array
5594 function get_list_of_themes() {
5596 global $CFG;
5598 $themes = array();
5600 if (!empty($CFG->themelist)) { // use admin's list of themes
5601 $themelist = explode(',', $CFG->themelist);
5602 } else {
5603 $themelist = get_list_of_plugins("theme");
5606 foreach ($themelist as $key => $theme) {
5607 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
5608 continue;
5610 $THEME = new object(); // Note this is not the global one!! :-)
5611 include("$CFG->themedir/$theme/config.php");
5612 if (!isset($THEME->sheets)) { // Not a valid 1.5 theme
5613 continue;
5615 $themes[$theme] = $theme;
5617 asort($themes);
5619 return $themes;
5624 * Returns a list of picture names in the current or specified language
5626 * @uses $CFG
5627 * @return array
5629 function get_list_of_pixnames($lang = '') {
5630 global $CFG;
5632 if (empty($lang)) {
5633 $lang = current_language();
5636 $string = array();
5638 $path = $CFG->dirroot .'/lang/en_utf8/pix.php'; // always exists
5640 if (file_exists($CFG->dataroot .'/lang/'. $lang .'_local/pix.php')) {
5641 $path = $CFG->dataroot .'/lang/'. $lang .'_local/pix.php';
5643 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
5644 $path = $CFG->dirroot .'/lang/'. $lang .'/pix.php';
5646 } else if (file_exists($CFG->dataroot .'/lang/'. $lang .'/pix.php')) {
5647 $path = $CFG->dataroot .'/lang/'. $lang .'/pix.php';
5649 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
5650 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
5653 include($path);
5655 return $string;
5659 * Returns a list of timezones in the current language
5661 * @uses $CFG
5662 * @return array
5664 function get_list_of_timezones() {
5665 global $CFG;
5667 static $timezones;
5669 if (!empty($timezones)) { // This function has been called recently
5670 return $timezones;
5673 $timezones = array();
5675 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix.'timezone GROUP BY name')) {
5676 foreach($rawtimezones as $timezone) {
5677 if (!empty($timezone->name)) {
5678 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
5679 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
5680 $timezones[$timezone->name] = $timezone->name;
5686 asort($timezones);
5688 for ($i = -13; $i <= 13; $i += .5) {
5689 $tzstring = 'UTC';
5690 if ($i < 0) {
5691 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
5692 } else if ($i > 0) {
5693 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
5694 } else {
5695 $timezones[sprintf("%.1f", $i)] = $tzstring;
5699 return $timezones;
5703 * Returns a list of currencies in the current language
5705 * @uses $CFG
5706 * @uses $USER
5707 * @return array
5709 function get_list_of_currencies() {
5710 global $CFG, $USER;
5712 $lang = current_language();
5714 if (!file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
5715 if ($parentlang = get_string('parentlanguage')) {
5716 if (file_exists($CFG->dataroot .'/lang/'. $parentlang .'/currencies.php')) {
5717 $lang = $parentlang;
5718 } else {
5719 $lang = 'en_utf8'; // currencies.php must exist in this pack
5721 } else {
5722 $lang = 'en_utf8'; // currencies.php must exist in this pack
5726 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
5727 include_once($CFG->dataroot .'/lang/'. $lang .'/currencies.php');
5728 } else { //if en_utf8 is not installed in dataroot
5729 include_once($CFG->dirroot .'/lang/'. $lang .'/currencies.php');
5732 if (!empty($string)) {
5733 asort($string);
5736 return $string;
5740 /// ENCRYPTION ////////////////////////////////////////////////
5743 * rc4encrypt
5745 * @param string $data ?
5746 * @return string
5747 * @todo Finish documenting this function
5749 function rc4encrypt($data) {
5750 $password = 'nfgjeingjk';
5751 return endecrypt($password, $data, '');
5755 * rc4decrypt
5757 * @param string $data ?
5758 * @return string
5759 * @todo Finish documenting this function
5761 function rc4decrypt($data) {
5762 $password = 'nfgjeingjk';
5763 return endecrypt($password, $data, 'de');
5767 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5769 * @param string $pwd ?
5770 * @param string $data ?
5771 * @param string $case ?
5772 * @return string
5773 * @todo Finish documenting this function
5775 function endecrypt ($pwd, $data, $case) {
5777 if ($case == 'de') {
5778 $data = urldecode($data);
5781 $key[] = '';
5782 $box[] = '';
5783 $temp_swap = '';
5784 $pwd_length = 0;
5786 $pwd_length = strlen($pwd);
5788 for ($i = 0; $i <= 255; $i++) {
5789 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
5790 $box[$i] = $i;
5793 $x = 0;
5795 for ($i = 0; $i <= 255; $i++) {
5796 $x = ($x + $box[$i] + $key[$i]) % 256;
5797 $temp_swap = $box[$i];
5798 $box[$i] = $box[$x];
5799 $box[$x] = $temp_swap;
5802 $temp = '';
5803 $k = '';
5805 $cipherby = '';
5806 $cipher = '';
5808 $a = 0;
5809 $j = 0;
5811 for ($i = 0; $i < strlen($data); $i++) {
5812 $a = ($a + 1) % 256;
5813 $j = ($j + $box[$a]) % 256;
5814 $temp = $box[$a];
5815 $box[$a] = $box[$j];
5816 $box[$j] = $temp;
5817 $k = $box[(($box[$a] + $box[$j]) % 256)];
5818 $cipherby = ord(substr($data, $i, 1)) ^ $k;
5819 $cipher .= chr($cipherby);
5822 if ($case == 'de') {
5823 $cipher = urldecode(urlencode($cipher));
5824 } else {
5825 $cipher = urlencode($cipher);
5828 return $cipher;
5832 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5836 * Call this function to add an event to the calendar table
5837 * and to call any calendar plugins
5839 * @uses $CFG
5840 * @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:
5841 * <ul>
5842 * <li><b>$event->name</b> - Name for the event
5843 * <li><b>$event->description</b> - Description of the event (defaults to '')
5844 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5845 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5846 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5847 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5848 * <li><b>$event->modulename</b> - Name of the module that creates this event
5849 * <li><b>$event->instance</b> - Instance of the module that owns this event
5850 * <li><b>$event->eventtype</b> - The type info together with the module info could
5851 * be used by calendar plugins to decide how to display event
5852 * <li><b>$event->timestart</b>- Timestamp for start of event
5853 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5854 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5855 * </ul>
5856 * @return int The id number of the resulting record
5858 function add_event($event) {
5860 global $CFG;
5862 $event->timemodified = time();
5864 if (!$event->id = insert_record('event', $event)) {
5865 return false;
5868 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
5869 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5870 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5871 $calendar_add_event = $CFG->calendar.'_add_event';
5872 if (function_exists($calendar_add_event)) {
5873 $calendar_add_event($event);
5878 return $event->id;
5882 * Call this function to update an event in the calendar table
5883 * the event will be identified by the id field of the $event object.
5885 * @uses $CFG
5886 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5887 * @return bool
5889 function update_event($event) {
5891 global $CFG;
5893 $event->timemodified = time();
5895 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5896 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5897 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5898 $calendar_update_event = $CFG->calendar.'_update_event';
5899 if (function_exists($calendar_update_event)) {
5900 $calendar_update_event($event);
5904 return update_record('event', $event);
5908 * Call this function to delete the event with id $id from calendar table.
5910 * @uses $CFG
5911 * @param int $id The id of an event from the 'calendar' table.
5912 * @return array An associative array with the results from the SQL call.
5913 * @todo Verify return type
5915 function delete_event($id) {
5917 global $CFG;
5919 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
5920 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5921 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5922 $calendar_delete_event = $CFG->calendar.'_delete_event';
5923 if (function_exists($calendar_delete_event)) {
5924 $calendar_delete_event($id);
5928 return delete_records('event', 'id', $id);
5932 * Call this function to hide an event in the calendar table
5933 * the event will be identified by the id field of the $event object.
5935 * @uses $CFG
5936 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5937 * @return array An associative array with the results from the SQL call.
5938 * @todo Verify return type
5940 function hide_event($event) {
5941 global $CFG;
5943 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5944 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5945 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5946 $calendar_hide_event = $CFG->calendar.'_hide_event';
5947 if (function_exists($calendar_hide_event)) {
5948 $calendar_hide_event($event);
5952 return set_field('event', 'visible', 0, 'id', $event->id);
5956 * Call this function to unhide an event in the calendar table
5957 * the event will be identified by the id field of the $event object.
5959 * @uses $CFG
5960 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5961 * @return array An associative array with the results from the SQL call.
5962 * @todo Verify return type
5964 function show_event($event) {
5965 global $CFG;
5967 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5968 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5969 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5970 $calendar_show_event = $CFG->calendar.'_show_event';
5971 if (function_exists($calendar_show_event)) {
5972 $calendar_show_event($event);
5976 return set_field('event', 'visible', 1, 'id', $event->id);
5980 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5983 * Lists plugin directories within some directory
5985 * @uses $CFG
5986 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5987 * @param string $exclude dir name to exclude from the list (defaults to none)
5988 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5989 * @return array of plugins found under the requested parameters
5991 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5993 global $CFG;
5995 $plugins = array();
5997 if (empty($basedir)) {
5999 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
6000 switch ($plugin) {
6001 case "theme":
6002 $basedir = $CFG->themedir;
6003 break;
6005 default:
6006 $basedir = $CFG->dirroot .'/'. $plugin;
6009 } else {
6010 $basedir = $basedir .'/'. $plugin;
6013 if (file_exists($basedir) && filetype($basedir) == 'dir') {
6014 $dirhandle = opendir($basedir);
6015 while (false !== ($dir = readdir($dirhandle))) {
6016 $firstchar = substr($dir, 0, 1);
6017 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
6018 continue;
6020 if (filetype($basedir .'/'. $dir) != 'dir') {
6021 continue;
6023 $plugins[] = $dir;
6025 closedir($dirhandle);
6027 if ($plugins) {
6028 asort($plugins);
6030 return $plugins;
6034 * Returns true if the current version of PHP is greater that the specified one.
6036 * @param string $version The version of php being tested.
6037 * @return bool
6039 function check_php_version($version='4.1.0') {
6040 return (version_compare(phpversion(), $version) >= 0);
6045 * Checks to see if is a browser matches the specified
6046 * brand and is equal or better version.
6048 * @uses $_SERVER
6049 * @param string $brand The browser identifier being tested
6050 * @param int $version The version of the browser
6051 * @return bool true if the given version is below that of the detected browser
6053 function check_browser_version($brand='MSIE', $version=5.5) {
6054 if (empty($_SERVER['HTTP_USER_AGENT'])) {
6055 return false;
6058 $agent = $_SERVER['HTTP_USER_AGENT'];
6060 switch ($brand) {
6062 case 'Camino': /// Mozilla Firefox browsers
6064 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
6065 if (version_compare($match[1], $version) >= 0) {
6066 return true;
6069 break;
6072 case 'Firefox': /// Mozilla Firefox browsers
6074 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
6075 if (version_compare($match[1], $version) >= 0) {
6076 return true;
6079 break;
6082 case 'Gecko': /// Gecko based browsers
6084 if (substr_count($agent, 'Camino')) {
6085 // MacOS X Camino support
6086 $version = 20041110;
6089 // the proper string - Gecko/CCYYMMDD Vendor/Version
6090 // Faster version and work-a-round No IDN problem.
6091 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
6092 if ($match[1] > $version) {
6093 return true;
6096 break;
6099 case 'MSIE': /// Internet Explorer
6101 if (strpos($agent, 'Opera')) { // Reject Opera
6102 return false;
6104 $string = explode(';', $agent);
6105 if (!isset($string[1])) {
6106 return false;
6108 $string = explode(' ', trim($string[1]));
6109 if (!isset($string[0]) and !isset($string[1])) {
6110 return false;
6112 if ($string[0] == $brand and (float)$string[1] >= $version ) {
6113 return true;
6115 break;
6117 case 'Opera': /// Opera
6119 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
6120 if (version_compare($match[1], $version) >= 0) {
6121 return true;
6124 break;
6126 case 'Safari': /// Safari
6127 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
6128 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
6129 return false;
6130 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
6131 return false;
6132 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
6133 return false;
6136 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
6137 if (version_compare($match[1], $version) >= 0) {
6138 return true;
6142 break;
6146 return false;
6150 * This function makes the return value of ini_get consistent if you are
6151 * setting server directives through the .htaccess file in apache.
6152 * Current behavior for value set from php.ini On = 1, Off = [blank]
6153 * Current behavior for value set from .htaccess On = On, Off = Off
6154 * Contributed by jdell @ unr.edu
6156 * @param string $ini_get_arg ?
6157 * @return bool
6158 * @todo Finish documenting this function
6160 function ini_get_bool($ini_get_arg) {
6161 $temp = ini_get($ini_get_arg);
6163 if ($temp == '1' or strtolower($temp) == 'on') {
6164 return true;
6166 return false;
6170 * Compatibility stub to provide backward compatibility
6172 * Determines if the HTML editor is enabled.
6173 * @deprecated Use {@link can_use_html_editor()} instead.
6175 function can_use_richtext_editor() {
6176 return can_use_html_editor();
6180 * Determines if the HTML editor is enabled.
6182 * This depends on site and user
6183 * settings, as well as the current browser being used.
6185 * @return string|false Returns false if editor is not being used, otherwise
6186 * returns 'MSIE' or 'Gecko'.
6188 function can_use_html_editor() {
6189 global $USER, $CFG;
6191 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
6192 if (check_browser_version('MSIE', 5.5)) {
6193 return 'MSIE';
6194 } else if (check_browser_version('Gecko', 20030516)) {
6195 return 'Gecko';
6198 return false;
6202 * Hack to find out the GD version by parsing phpinfo output
6204 * @return int GD version (1, 2, or 0)
6206 function check_gd_version() {
6207 $gdversion = 0;
6209 if (function_exists('gd_info')){
6210 $gd_info = gd_info();
6211 if (substr_count($gd_info['GD Version'], '2.')) {
6212 $gdversion = 2;
6213 } else if (substr_count($gd_info['GD Version'], '1.')) {
6214 $gdversion = 1;
6217 } else {
6218 ob_start();
6219 phpinfo(INFO_MODULES);
6220 $phpinfo = ob_get_contents();
6221 ob_end_clean();
6223 $phpinfo = explode("\n", $phpinfo);
6226 foreach ($phpinfo as $text) {
6227 $parts = explode('</td>', $text);
6228 foreach ($parts as $key => $val) {
6229 $parts[$key] = trim(strip_tags($val));
6231 if ($parts[0] == 'GD Version') {
6232 if (substr_count($parts[1], '2.0')) {
6233 $parts[1] = '2.0';
6235 $gdversion = intval($parts[1]);
6240 return $gdversion; // 1, 2 or 0
6244 * Determine if moodle installation requires update
6246 * Checks version numbers of main code and all modules to see
6247 * if there are any mismatches
6249 * @uses $CFG
6250 * @return bool
6252 function moodle_needs_upgrading() {
6253 global $CFG;
6255 $version = null;
6256 include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
6257 if ($CFG->version) {
6258 if ($version > $CFG->version) {
6259 return true;
6261 if ($mods = get_list_of_plugins('mod')) {
6262 foreach ($mods as $mod) {
6263 $fullmod = $CFG->dirroot .'/mod/'. $mod;
6264 $module = new object();
6265 if (!is_readable($fullmod .'/version.php')) {
6266 notify('Module "'. $mod .'" is not readable - check permissions');
6267 continue;
6269 include_once($fullmod .'/version.php'); # defines $module with version etc
6270 if ($currmodule = get_record('modules', 'name', $mod)) {
6271 if ($module->version > $currmodule->version) {
6272 return true;
6277 } else {
6278 return true;
6280 return false;
6284 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
6287 * Notify admin users or admin user of any failed logins (since last notification).
6289 * Note that this function must be only executed from the cron script
6290 * It uses the cache_flags system to store temporary records, deleting them
6291 * by name before finishing
6293 * @uses $CFG
6294 * @uses $db
6295 * @uses HOURSECS
6297 function notify_login_failures() {
6298 global $CFG, $db;
6300 switch ($CFG->notifyloginfailures) {
6301 case 'mainadmin' :
6302 $recip = array(get_admin());
6303 break;
6304 case 'alladmins':
6305 $recip = get_admins();
6306 break;
6309 if (empty($CFG->lastnotifyfailure)) {
6310 $CFG->lastnotifyfailure=0;
6313 // we need to deal with the threshold stuff first.
6314 if (empty($CFG->notifyloginthreshold)) {
6315 $CFG->notifyloginthreshold = 10; // default to something sensible.
6318 /// Get all the IPs with more than notifyloginthreshold failures since lastnotifyfailure
6319 /// and insert them into the cache_flags temp table
6320 $iprs = get_recordset_sql("SELECT ip, count(*)
6321 FROM {$CFG->prefix}log
6322 WHERE module = 'login'
6323 AND action = 'error'
6324 AND time > $CFG->lastnotifyfailure
6325 GROUP BY ip
6326 HAVING count(*) >= $CFG->notifyloginthreshold");
6327 while ($iprec = rs_fetch_next_record($iprs)) {
6328 if (!empty($iprec->ip)) {
6329 set_cache_flag('login_failure_by_ip', $iprec->ip, '1', 0);
6332 rs_close($iprs);
6334 /// Get all the INFOs with more than notifyloginthreshold failures since lastnotifyfailure
6335 /// and insert them into the cache_flags temp table
6336 $infors = get_recordset_sql("SELECT info, count(*)
6337 FROM {$CFG->prefix}log
6338 WHERE module = 'login'
6339 AND action = 'error'
6340 AND time > $CFG->lastnotifyfailure
6341 GROUP BY info
6342 HAVING count(*) >= $CFG->notifyloginthreshold");
6343 while ($inforec = rs_fetch_next_record($infors)) {
6344 if (!empty($inforec->info)) {
6345 set_cache_flag('login_failure_by_info', $inforec->info, '1', 0);
6348 rs_close($infors);
6350 /// Now, select all the login error logged records belonging to the ips and infos
6351 /// since lastnotifyfailure, that we have stored in the cache_flags table
6352 $logsrs = get_recordset_sql("SELECT l.*, u.firstname, u.lastname
6353 FROM {$CFG->prefix}log l
6354 JOIN {$CFG->prefix}cache_flags cf ON (l.ip = cf.name)
6355 LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
6356 WHERE l.module = 'login'
6357 AND l.action = 'error'
6358 AND l.time > $CFG->lastnotifyfailure
6359 AND cf.flagtype = 'login_failure_by_ip'
6360 UNION ALL
6361 SELECT l.*, u.firstname, u.lastname
6362 FROM {$CFG->prefix}log l
6363 JOIN {$CFG->prefix}cache_flags cf ON (l.info = cf.name)
6364 LEFT JOIN {$CFG->prefix}user u ON (l.userid = u.id)
6365 WHERE l.module = 'login'
6366 AND l.action = 'error'
6367 AND l.time > $CFG->lastnotifyfailure
6368 AND cf.flagtype = 'login_failure_by_info'
6369 ORDER BY time DESC");
6371 /// Init some variables
6372 $count = 0;
6373 $messages = '';
6374 /// Iterate over the logs recordset
6375 while ($log = rs_fetch_next_record($logsrs)) {
6376 $log->time = userdate($log->time);
6377 $messages .= get_string('notifyloginfailuresmessage','',$log)."\n";
6378 $count++;
6380 rs_close($logsrs);
6382 /// If we haven't run in the last hour and
6383 /// we have something useful to report and we
6384 /// are actually supposed to be reporting to somebody
6385 if ((time() - HOURSECS) > $CFG->lastnotifyfailure && $count > 0 && is_array($recip) && count($recip) > 0) {
6386 $site = get_site();
6387 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
6388 /// Calculate the complete body of notification (start + messages + end)
6389 $body = get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot) .
6390 (($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n" .
6391 $messages .
6392 "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
6394 /// For each destination, send mail
6395 foreach ($recip as $admin) {
6396 mtrace('Emailing '. $admin->username .' about '. $count .' failed login attempts');
6397 email_to_user($admin,get_admin(), $subject, $body);
6400 /// Update lastnotifyfailure with current time
6401 set_config('lastnotifyfailure', time());
6404 /// Finally, delete all the temp records we have created in cache_flags
6405 delete_records_select('cache_flags', "flagtype IN ('login_failure_by_ip', 'login_failure_by_info')");
6409 * moodle_setlocale
6411 * @uses $CFG
6412 * @param string $locale ?
6413 * @todo Finish documenting this function
6415 function moodle_setlocale($locale='') {
6417 global $CFG;
6419 static $currentlocale = ''; // last locale caching
6421 $oldlocale = $currentlocale;
6423 /// Fetch the correct locale based on ostype
6424 if($CFG->ostype == 'WINDOWS') {
6425 $stringtofetch = 'localewin';
6426 } else {
6427 $stringtofetch = 'locale';
6430 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
6431 if (!empty($locale)) {
6432 $currentlocale = $locale;
6433 } else if (!empty($CFG->locale)) { // override locale for all language packs
6434 $currentlocale = $CFG->locale;
6435 } else {
6436 $currentlocale = get_string($stringtofetch);
6439 /// do nothing if locale already set up
6440 if ($oldlocale == $currentlocale) {
6441 return;
6444 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
6445 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
6446 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
6448 /// Get current values
6449 $monetary= setlocale (LC_MONETARY, 0);
6450 $numeric = setlocale (LC_NUMERIC, 0);
6451 $ctype = setlocale (LC_CTYPE, 0);
6452 if ($CFG->ostype != 'WINDOWS') {
6453 $messages= setlocale (LC_MESSAGES, 0);
6455 /// Set locale to all
6456 setlocale (LC_ALL, $currentlocale);
6457 /// Set old values
6458 setlocale (LC_MONETARY, $monetary);
6459 setlocale (LC_NUMERIC, $numeric);
6460 if ($CFG->ostype != 'WINDOWS') {
6461 setlocale (LC_MESSAGES, $messages);
6463 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
6464 setlocale (LC_CTYPE, $ctype);
6469 * Converts string to lowercase using most compatible function available.
6471 * @param string $string The string to convert to all lowercase characters.
6472 * @param string $encoding The encoding on the string.
6473 * @return string
6474 * @todo Add examples of calling this function with/without encoding types
6475 * @deprecated Use textlib->strtolower($text) instead.
6477 function moodle_strtolower ($string, $encoding='') {
6479 //If not specified use utf8
6480 if (empty($encoding)) {
6481 $encoding = 'UTF-8';
6483 //Use text services
6484 $textlib = textlib_get_instance();
6486 return $textlib->strtolower($string, $encoding);
6490 * Count words in a string.
6492 * Words are defined as things between whitespace.
6494 * @param string $string The text to be searched for words.
6495 * @return int The count of words in the specified string
6497 function count_words($string) {
6498 $string = strip_tags($string);
6499 return count(preg_split("/\w\b/", $string)) - 1;
6502 /** Count letters in a string.
6504 * Letters are defined as chars not in tags and different from whitespace.
6506 * @param string $string The text to be searched for letters.
6507 * @return int The count of letters in the specified text.
6509 function count_letters($string) {
6510 /// Loading the textlib singleton instance. We are going to need it.
6511 $textlib = textlib_get_instance();
6513 $string = strip_tags($string); // Tags are out now
6514 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
6516 return $textlib->strlen($string);
6520 * Generate and return a random string of the specified length.
6522 * @param int $length The length of the string to be created.
6523 * @return string
6525 function random_string ($length=15) {
6526 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
6527 $pool .= 'abcdefghijklmnopqrstuvwxyz';
6528 $pool .= '0123456789';
6529 $poollen = strlen($pool);
6530 mt_srand ((double) microtime() * 1000000);
6531 $string = '';
6532 for ($i = 0; $i < $length; $i++) {
6533 $string .= substr($pool, (mt_rand()%($poollen)), 1);
6535 return $string;
6539 * Given some text (which may contain HTML) and an ideal length,
6540 * this function truncates the text neatly on a word boundary if possible
6541 * @param string $text - text to be shortened
6542 * @param int $ideal - ideal string length
6543 * @param boolean $exact if false, $text will not be cut mid-word
6544 * @return string $truncate - shortened string
6547 function shorten_text($text, $ideal=30, $exact = false) {
6549 global $CFG;
6550 $ending = '...';
6552 // if the plain text is shorter than the maximum length, return the whole text
6553 if (strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
6554 return $text;
6557 // splits all html-tags to scanable lines
6558 preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
6560 $total_length = strlen($ending);
6561 $open_tags = array();
6562 $truncate = '';
6564 foreach ($lines as $line_matchings) {
6565 // if there is any html-tag in this line, handle it and add it (uncounted) to the output
6566 if (!empty($line_matchings[1])) {
6567 // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
6568 if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
6569 // do nothing
6570 // if tag is a closing tag (f.e. </b>)
6571 } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
6572 // delete tag from $open_tags list
6573 $pos = array_search($tag_matchings[1], array_reverse($open_tags, true)); // can have multiple exact same open tags, close the last one
6574 if ($pos !== false) {
6575 unset($open_tags[$pos]);
6577 // if tag is an opening tag (f.e. <b>)
6578 } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
6579 // add tag to the beginning of $open_tags list
6580 array_unshift($open_tags, strtolower($tag_matchings[1]));
6582 // add html-tag to $truncate'd text
6583 $truncate .= $line_matchings[1];
6586 // calculate the length of the plain text part of the line; handle entities as one character
6587 $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
6588 if ($total_length+$content_length > $ideal) {
6589 // the number of characters which are left
6590 $left = $ideal - $total_length;
6591 $entities_length = 0;
6592 // search for html entities
6593 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)) {
6594 // calculate the real length of all entities in the legal range
6595 foreach ($entities[0] as $entity) {
6596 if ($entity[1]+1-$entities_length <= $left) {
6597 $left--;
6598 $entities_length += strlen($entity[0]);
6599 } else {
6600 // no more characters left
6601 break;
6605 $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
6606 // maximum lenght is reached, so get off the loop
6607 break;
6608 } else {
6609 $truncate .= $line_matchings[2];
6610 $total_length += $content_length;
6613 // if the maximum length is reached, get off the loop
6614 if($total_length >= $ideal) {
6615 break;
6619 // if the words shouldn't be cut in the middle...
6620 if (!$exact) {
6621 // ...search the last occurance of a space...
6622 for ($k=strlen($truncate);$k>0;$k--) {
6623 if (!empty($truncate[$k]) && ($char = $truncate[$k])) {
6624 if ($char == '.' or $char == ' ') {
6625 $breakpos = $k+1;
6626 break;
6627 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
6628 $breakpos = $k; // can be truncated at any UTF-8
6629 break; // character boundary.
6634 if (isset($breakpos)) {
6635 // ...and cut the text in this position
6636 $truncate = substr($truncate, 0, $breakpos);
6640 // add the defined ending to the text
6641 $truncate .= $ending;
6643 // close all unclosed html-tags
6644 foreach ($open_tags as $tag) {
6645 $truncate .= '</' . $tag . '>';
6648 return $truncate;
6653 * Given dates in seconds, how many weeks is the date from startdate
6654 * The first week is 1, the second 2 etc ...
6656 * @uses WEEKSECS
6657 * @param ? $startdate ?
6658 * @param ? $thedate ?
6659 * @return string
6660 * @todo Finish documenting this function
6662 function getweek ($startdate, $thedate) {
6663 if ($thedate < $startdate) { // error
6664 return 0;
6667 return floor(($thedate - $startdate) / WEEKSECS) + 1;
6671 * returns a randomly generated password of length $maxlen. inspired by
6672 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
6673 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
6675 * @param int $maxlen The maximum size of the password being generated.
6676 * @return string
6678 function generate_password($maxlen=10) {
6679 global $CFG;
6681 if (empty($CFG->passwordpolicy)) {
6682 $fillers = PASSWORD_DIGITS;
6683 $wordlist = file($CFG->wordlist);
6684 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6685 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6686 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
6687 $password = $word1 . $filler1 . $word2;
6688 } else {
6689 $maxlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
6690 $digits = $CFG->minpassworddigits;
6691 $lower = $CFG->minpasswordlower;
6692 $upper = $CFG->minpasswordupper;
6693 $nonalphanum = $CFG->minpasswordnonalphanum;
6694 $additional = $maxlen - ($lower + $upper + $digits + $nonalphanum);
6696 // Make sure we have enough characters to fulfill
6697 // complexity requirements
6698 $passworddigits = PASSWORD_DIGITS;
6699 while ($digits > strlen($passworddigits)) {
6700 $passworddigits .= PASSWORD_DIGITS;
6702 $passwordlower = PASSWORD_LOWER;
6703 while ($lower > strlen($passwordlower)) {
6704 $passwordlower .= PASSWORD_LOWER;
6706 $passwordupper = PASSWORD_UPPER;
6707 while ($upper > strlen($passwordupper)) {
6708 $passwordupper .= PASSWORD_UPPER;
6710 $passwordnonalphanum = PASSWORD_NONALPHANUM;
6711 while ($nonalphanum > strlen($passwordnonalphanum)) {
6712 $passwordnonalphanum .= PASSWORD_NONALPHANUM;
6715 // Now mix and shuffle it all
6716 $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
6717 substr(str_shuffle ($passwordupper), 0, $upper) .
6718 substr(str_shuffle ($passworddigits), 0, $digits) .
6719 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
6720 substr(str_shuffle ($passwordlower .
6721 $passwordupper .
6722 $passworddigits .
6723 $passwordnonalphanum), 0 , $additional));
6726 return substr ($password, 0, $maxlen);
6730 * Given a float, prints it nicely.
6731 * Localized floats must not be used in calculations!
6733 * @param float $flaot The float to print
6734 * @param int $places The number of decimal places to print.
6735 * @param bool $localized use localized decimal separator
6736 * @return string locale float
6738 function format_float($float, $decimalpoints=1, $localized=true) {
6739 if (is_null($float)) {
6740 return '';
6742 if ($localized) {
6743 return number_format($float, $decimalpoints, get_string('decsep'), '');
6744 } else {
6745 return number_format($float, $decimalpoints, '.', '');
6750 * Converts locale specific floating point/comma number back to standard PHP float value
6751 * Do NOT try to do any math operations before this conversion on any user submitted floats!
6753 * @param string $locale_float locale aware float representation
6755 function unformat_float($locale_float) {
6756 $locale_float = trim($locale_float);
6758 if ($locale_float == '') {
6759 return null;
6762 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
6764 return (float)str_replace(get_string('decsep'), '.', $locale_float);
6768 * Given a simple array, this shuffles it up just like shuffle()
6769 * Unlike PHP's shuffle() this function works on any machine.
6771 * @param array $array The array to be rearranged
6772 * @return array
6774 function swapshuffle($array) {
6776 srand ((double) microtime() * 10000000);
6777 $last = count($array) - 1;
6778 for ($i=0;$i<=$last;$i++) {
6779 $from = rand(0,$last);
6780 $curr = $array[$i];
6781 $array[$i] = $array[$from];
6782 $array[$from] = $curr;
6784 return $array;
6788 * Like {@link swapshuffle()}, but works on associative arrays
6790 * @param array $array The associative array to be rearranged
6791 * @return array
6793 function swapshuffle_assoc($array) {
6795 $newarray = array();
6796 $newkeys = swapshuffle(array_keys($array));
6798 foreach ($newkeys as $newkey) {
6799 $newarray[$newkey] = $array[$newkey];
6801 return $newarray;
6805 * Given an arbitrary array, and a number of draws,
6806 * this function returns an array with that amount
6807 * of items. The indexes are retained.
6809 * @param array $array ?
6810 * @param ? $draws ?
6811 * @return ?
6812 * @todo Finish documenting this function
6814 function draw_rand_array($array, $draws) {
6815 srand ((double) microtime() * 10000000);
6817 $return = array();
6819 $last = count($array);
6821 if ($draws > $last) {
6822 $draws = $last;
6825 while ($draws > 0) {
6826 $last--;
6828 $keys = array_keys($array);
6829 $rand = rand(0, $last);
6831 $return[$keys[$rand]] = $array[$keys[$rand]];
6832 unset($array[$keys[$rand]]);
6834 $draws--;
6837 return $return;
6841 * microtime_diff
6843 * @param string $a ?
6844 * @param string $b ?
6845 * @return string
6846 * @todo Finish documenting this function
6848 function microtime_diff($a, $b) {
6849 list($a_dec, $a_sec) = explode(' ', $a);
6850 list($b_dec, $b_sec) = explode(' ', $b);
6851 return $b_sec - $a_sec + $b_dec - $a_dec;
6855 * Given a list (eg a,b,c,d,e) this function returns
6856 * an array of 1->a, 2->b, 3->c etc
6858 * @param array $list ?
6859 * @param string $separator ?
6860 * @todo Finish documenting this function
6862 function make_menu_from_list($list, $separator=',') {
6864 $array = array_reverse(explode($separator, $list), true);
6865 foreach ($array as $key => $item) {
6866 $outarray[$key+1] = trim($item);
6868 return $outarray;
6872 * Creates an array that represents all the current grades that
6873 * can be chosen using the given grading type. Negative numbers
6874 * are scales, zero is no grade, and positive numbers are maximum
6875 * grades.
6877 * @param int $gradingtype ?
6878 * return int
6879 * @todo Finish documenting this function
6881 function make_grades_menu($gradingtype) {
6882 $grades = array();
6883 if ($gradingtype < 0) {
6884 if ($scale = get_record('scale', 'id', - $gradingtype)) {
6885 return make_menu_from_list($scale->scale);
6887 } else if ($gradingtype > 0) {
6888 for ($i=$gradingtype; $i>=0; $i--) {
6889 $grades[$i] = $i .' / '. $gradingtype;
6891 return $grades;
6893 return $grades;
6897 * This function returns the nummber of activities
6898 * using scaleid in a courseid
6900 * @param int $courseid ?
6901 * @param int $scaleid ?
6902 * @return int
6903 * @todo Finish documenting this function
6905 function course_scale_used($courseid, $scaleid) {
6907 global $CFG;
6909 $return = 0;
6911 if (!empty($scaleid)) {
6912 if ($cms = get_course_mods($courseid)) {
6913 foreach ($cms as $cm) {
6914 //Check cm->name/lib.php exists
6915 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
6916 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
6917 $function_name = $cm->modname.'_scale_used';
6918 if (function_exists($function_name)) {
6919 if ($function_name($cm->instance,$scaleid)) {
6920 $return++;
6927 // check if any course grade item makes use of the scale
6928 $return += count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
6930 // check if any outcome in the course makes use of the scale
6931 $return += count_records_sql("SELECT COUNT(*)
6932 FROM {$CFG->prefix}grade_outcomes_courses goc,
6933 {$CFG->prefix}grade_outcomes go
6934 WHERE go.id = goc.outcomeid
6935 AND go.scaleid = $scaleid
6936 AND goc.courseid = $courseid");
6938 return $return;
6942 * This function returns the nummber of activities
6943 * using scaleid in the entire site
6945 * @param int $scaleid ?
6946 * @return int
6947 * @todo Finish documenting this function. Is return type correct?
6949 function site_scale_used($scaleid,&$courses) {
6951 global $CFG;
6953 $return = 0;
6955 if (!is_array($courses) || count($courses) == 0) {
6956 $courses = get_courses("all",false,"c.id,c.shortname");
6959 if (!empty($scaleid)) {
6960 if (is_array($courses) && count($courses) > 0) {
6961 foreach ($courses as $course) {
6962 $return += course_scale_used($course->id,$scaleid);
6966 return $return;
6970 * make_unique_id_code
6972 * @param string $extra ?
6973 * @return string
6974 * @todo Finish documenting this function
6976 function make_unique_id_code($extra='') {
6978 $hostname = 'unknownhost';
6979 if (!empty($_SERVER['HTTP_HOST'])) {
6980 $hostname = $_SERVER['HTTP_HOST'];
6981 } else if (!empty($_ENV['HTTP_HOST'])) {
6982 $hostname = $_ENV['HTTP_HOST'];
6983 } else if (!empty($_SERVER['SERVER_NAME'])) {
6984 $hostname = $_SERVER['SERVER_NAME'];
6985 } else if (!empty($_ENV['SERVER_NAME'])) {
6986 $hostname = $_ENV['SERVER_NAME'];
6989 $date = gmdate("ymdHis");
6991 $random = random_string(6);
6993 if ($extra) {
6994 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6995 } else {
6996 return $hostname .'+'. $date .'+'. $random;
7002 * Function to check the passed address is within the passed subnet
7004 * The parameter is a comma separated string of subnet definitions.
7005 * Subnet strings can be in one of three formats:
7006 * 1: xxx.xxx.xxx.xxx/xx
7007 * 2: xxx.xxx
7008 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
7009 * Code for type 1 modified from user posted comments by mediator at
7010 * {@link http://au.php.net/manual/en/function.ip2long.php}
7012 * @param string $addr The address you are checking
7013 * @param string $subnetstr The string of subnet addresses
7014 * @return bool
7016 function address_in_subnet($addr, $subnetstr) {
7018 $subnets = explode(',', $subnetstr);
7019 $found = false;
7020 $addr = trim($addr);
7022 foreach ($subnets as $subnet) {
7023 $subnet = trim($subnet);
7024 if (strpos($subnet, '/') !== false) { /// type 1
7025 list($ip, $mask) = explode('/', $subnet);
7026 $mask = 0xffffffff << (32 - $mask);
7027 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
7028 } else if (strpos($subnet, '-') !== false) {/// type 3
7029 $subnetparts = explode('.', $subnet);
7030 $addrparts = explode('.', $addr);
7031 $subnetrange = explode('-', array_pop($subnetparts));
7032 if (count($subnetrange) == 2) {
7033 $lastaddrpart = array_pop($addrparts);
7034 $found = ($subnetparts == $addrparts &&
7035 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
7037 } else { /// type 2
7038 $found = (strpos($addr, $subnet) === 0);
7041 if ($found) {
7042 break;
7045 return $found;
7049 * This function sets the $HTTPSPAGEREQUIRED global
7050 * (used in some parts of moodle to change some links)
7051 * and calculate the proper wwwroot to be used
7053 * By using this function properly, we can ensure 100% https-ized pages
7054 * at our entire discretion (login, forgot_password, change_password)
7056 function httpsrequired() {
7058 global $CFG, $HTTPSPAGEREQUIRED;
7060 if (!empty($CFG->loginhttps)) {
7061 $HTTPSPAGEREQUIRED = true;
7062 $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
7063 $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
7065 // change theme URLs to https
7066 theme_setup();
7068 } else {
7069 $CFG->httpswwwroot = $CFG->wwwroot;
7070 $CFG->httpsthemewww = $CFG->themewww;
7075 * For outputting debugging info
7077 * @uses STDOUT
7078 * @param string $string ?
7079 * @param string $eol ?
7080 * @todo Finish documenting this function
7082 function mtrace($string, $eol="\n", $sleep=0) {
7084 if (defined('STDOUT')) {
7085 fwrite(STDOUT, $string.$eol);
7086 } else {
7087 echo $string . $eol;
7090 flush();
7092 //delay to keep message on user's screen in case of subsequent redirect
7093 if ($sleep) {
7094 sleep($sleep);
7098 //Replace 1 or more slashes or backslashes to 1 slash
7099 function cleardoubleslashes ($path) {
7100 return preg_replace('/(\/|\\\){1,}/','/',$path);
7103 function zip_files ($originalfiles, $destination) {
7104 //Zip an array of files/dirs to a destination zip file
7105 //Both parameters must be FULL paths to the files/dirs
7107 global $CFG;
7109 //Extract everything from destination
7110 $path_parts = pathinfo(cleardoubleslashes($destination));
7111 $destpath = $path_parts["dirname"]; //The path of the zip file
7112 $destfilename = $path_parts["basename"]; //The name of the zip file
7113 $extension = $path_parts["extension"]; //The extension of the file
7115 //If no file, error
7116 if (empty($destfilename)) {
7117 return false;
7120 //If no extension, add it
7121 if (empty($extension)) {
7122 $extension = 'zip';
7123 $destfilename = $destfilename.'.'.$extension;
7126 //Check destination path exists
7127 if (!is_dir($destpath)) {
7128 return false;
7131 //Check destination path is writable. TODO!!
7133 //Clean destination filename
7134 $destfilename = clean_filename($destfilename);
7136 //Now check and prepare every file
7137 $files = array();
7138 $origpath = NULL;
7140 foreach ($originalfiles as $file) { //Iterate over each file
7141 //Check for every file
7142 $tempfile = cleardoubleslashes($file); // no doubleslashes!
7143 //Calculate the base path for all files if it isn't set
7144 if ($origpath === NULL) {
7145 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
7147 //See if the file is readable
7148 if (!is_readable($tempfile)) { //Is readable
7149 continue;
7151 //See if the file/dir is in the same directory than the rest
7152 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
7153 continue;
7155 //Add the file to the array
7156 $files[] = $tempfile;
7159 //Everything is ready:
7160 // -$origpath is the path where ALL the files to be compressed reside (dir).
7161 // -$destpath is the destination path where the zip file will go (dir).
7162 // -$files is an array of files/dirs to compress (fullpath)
7163 // -$destfilename is the name of the zip file (without path)
7165 //print_object($files); //Debug
7167 if (empty($CFG->zip)) { // Use built-in php-based zip function
7169 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
7170 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
7171 $zipfiles = array();
7172 $start = strlen($origpath)+1;
7173 foreach($files as $file) {
7174 $tf = array();
7175 $tf[PCLZIP_ATT_FILE_NAME] = $file;
7176 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME] = substr($file, $start);
7177 $zipfiles[] = $tf;
7179 //create the archive
7180 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
7181 if (($list = $archive->create($zipfiles) == 0)) {
7182 notice($archive->errorInfo(true));
7183 return false;
7186 } else { // Use external zip program
7188 $filestozip = "";
7189 foreach ($files as $filetozip) {
7190 $filestozip .= escapeshellarg(basename($filetozip));
7191 $filestozip .= " ";
7193 //Construct the command
7194 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
7195 $command = 'cd '.escapeshellarg($origpath).$separator.
7196 escapeshellarg($CFG->zip).' -r '.
7197 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
7198 //All converted to backslashes in WIN
7199 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
7200 $command = str_replace('/','\\',$command);
7202 Exec($command);
7204 return true;
7207 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
7208 //Unzip one zip file to a destination dir
7209 //Both parameters must be FULL paths
7210 //If destination isn't specified, it will be the
7211 //SAME directory where the zip file resides.
7213 global $CFG;
7215 //Extract everything from zipfile
7216 $path_parts = pathinfo(cleardoubleslashes($zipfile));
7217 $zippath = $path_parts["dirname"]; //The path of the zip file
7218 $zipfilename = $path_parts["basename"]; //The name of the zip file
7219 $extension = $path_parts["extension"]; //The extension of the file
7221 //If no file, error
7222 if (empty($zipfilename)) {
7223 return false;
7226 //If no extension, error
7227 if (empty($extension)) {
7228 return false;
7231 //Clear $zipfile
7232 $zipfile = cleardoubleslashes($zipfile);
7234 //Check zipfile exists
7235 if (!file_exists($zipfile)) {
7236 return false;
7239 //If no destination, passed let's go with the same directory
7240 if (empty($destination)) {
7241 $destination = $zippath;
7244 //Clear $destination
7245 $destpath = rtrim(cleardoubleslashes($destination), "/");
7247 //Check destination path exists
7248 if (!is_dir($destpath)) {
7249 return false;
7252 //Check destination path is writable. TODO!!
7254 //Everything is ready:
7255 // -$zippath is the path where the zip file resides (dir)
7256 // -$zipfilename is the name of the zip file (without path)
7257 // -$destpath is the destination path where the zip file will uncompressed (dir)
7259 $list = null;
7261 if (empty($CFG->unzip)) { // Use built-in php-based unzip function
7263 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
7264 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
7265 if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
7266 PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename',
7267 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $destpath)) {
7268 if (!empty($showstatus)) {
7269 notice($archive->errorInfo(true));
7271 return false;
7274 } else { // Use external unzip program
7276 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
7277 $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
7279 $command = 'cd '.escapeshellarg($zippath).$separator.
7280 escapeshellarg($CFG->unzip).' -o '.
7281 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
7282 escapeshellarg($destpath).$redirection;
7283 //All converted to backslashes in WIN
7284 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
7285 $command = str_replace('/','\\',$command);
7287 Exec($command,$list);
7290 //Display some info about the unzip execution
7291 if ($showstatus) {
7292 unzip_show_status($list,$destpath);
7295 return true;
7298 function unzip_cleanfilename ($p_event, &$p_header) {
7299 //This function is used as callback in unzip_file() function
7300 //to clean illegal characters for given platform and to prevent directory traversal.
7301 //Produces the same result as info-zip unzip.
7302 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
7303 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
7304 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
7305 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
7306 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
7307 } else {
7308 //Add filtering for other systems here
7309 // BSD: none (tested)
7310 // Linux: ??
7311 // MacosX: ??
7313 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
7314 return 1;
7317 function unzip_show_status ($list,$removepath) {
7318 //This function shows the results of the unzip execution
7319 //depending of the value of the $CFG->zip, results will be
7320 //text or an array of files.
7322 global $CFG;
7324 if (empty($CFG->unzip)) { // Use built-in php-based zip function
7325 $strname = get_string("name");
7326 $strsize = get_string("size");
7327 $strmodified = get_string("modified");
7328 $strstatus = get_string("status");
7329 echo "<table width=\"640\">";
7330 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
7331 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
7332 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
7333 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
7334 foreach ($list as $item) {
7335 echo "<tr>";
7336 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
7337 print_cell("left", s($item['filename']));
7338 if (! $item['folder']) {
7339 print_cell("right", display_size($item['size']));
7340 } else {
7341 echo "<td>&nbsp;</td>";
7343 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
7344 print_cell("right", $filedate);
7345 print_cell("right", $item['status']);
7346 echo "</tr>";
7348 echo "</table>";
7350 } else { // Use external zip program
7351 print_simple_box_start("center");
7352 echo "<pre>";
7353 foreach ($list as $item) {
7354 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
7356 echo "</pre>";
7357 print_simple_box_end();
7362 * Returns most reliable client address
7364 * @return string The remote IP address
7366 function getremoteaddr() {
7367 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
7368 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
7370 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
7371 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
7373 if (!empty($_SERVER['REMOTE_ADDR'])) {
7374 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
7376 return '';
7380 * Cleans a remote address ready to put into the log table
7382 function cleanremoteaddr($addr) {
7383 $originaladdr = $addr;
7384 $matches = array();
7385 // first get all things that look like IP addresses.
7386 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER)) {
7387 return '';
7389 $goodmatches = array();
7390 $lanmatches = array();
7391 foreach ($matches as $match) {
7392 // print_r($match);
7393 // check to make sure it's not an internal address.
7394 // the following are reserved for private lans...
7395 // 10.0.0.0 - 10.255.255.255
7396 // 172.16.0.0 - 172.31.255.255
7397 // 192.168.0.0 - 192.168.255.255
7398 // 169.254.0.0 -169.254.255.255
7399 $bits = explode('.',$match[0]);
7400 if (count($bits) != 4) {
7401 // weird, preg match shouldn't give us it.
7402 continue;
7404 if (($bits[0] == 10)
7405 || ($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
7406 || ($bits[0] == 192 && $bits[1] == 168)
7407 || ($bits[0] == 169 && $bits[1] == 254)) {
7408 $lanmatches[] = $match[0];
7409 continue;
7411 // finally, it's ok
7412 $goodmatches[] = $match[0];
7414 if (!count($goodmatches)) {
7415 // perhaps we have a lan match, it's probably better to return that.
7416 if (!count($lanmatches)) {
7417 return '';
7418 } else {
7419 return array_pop($lanmatches);
7422 if (count($goodmatches) == 1) {
7423 return $goodmatches[0];
7425 //Commented out following because there are so many, and it clogs the logs MDL-13544
7426 //error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
7428 // We need to return something, so return the first
7429 return array_pop($goodmatches);
7433 * file_put_contents is only supported by php 5.0 and higher
7434 * so if it is not predefined, define it here
7436 * @param $file full path of the file to write
7437 * @param $contents contents to be sent
7438 * @return number of bytes written (false on error)
7440 if(!function_exists('file_put_contents')) {
7441 function file_put_contents($file, $contents) {
7442 $result = false;
7443 if ($f = fopen($file, 'w')) {
7444 $result = fwrite($f, $contents);
7445 fclose($f);
7447 return $result;
7452 * The clone keyword is only supported from PHP 5 onwards.
7453 * The behaviour of $obj2 = $obj1 differs fundamentally
7454 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
7455 * created, in PHP 5 $obj1 is referenced. To create a copy
7456 * in PHP 5 the clone keyword was introduced. This function
7457 * simulates this behaviour for PHP < 5.0.0.
7458 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
7460 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
7461 * Found a better implementation (more checks and possibilities) from PEAR:
7462 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
7464 * @param object $obj
7465 * @return object
7467 if(!check_php_version('5.0.0')) {
7468 // the eval is needed to prevent PHP 5 from getting a parse error!
7469 eval('
7470 function clone($obj) {
7471 /// Sanity check
7472 if (!is_object($obj)) {
7473 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
7474 return;
7477 /// Use serialize/unserialize trick to deep copy the object
7478 $obj = unserialize(serialize($obj));
7480 /// If there is a __clone method call it on the "new" class
7481 if (method_exists($obj, \'__clone\')) {
7482 $obj->__clone();
7485 return $obj;
7488 // Supply the PHP5 function scandir() to older versions.
7489 function scandir($directory) {
7490 $files = array();
7491 if ($dh = opendir($directory)) {
7492 while (($file = readdir($dh)) !== false) {
7493 $files[] = $file;
7495 closedir($dh);
7497 return $files;
7500 // Supply the PHP5 function array_combine() to older versions.
7501 function array_combine($keys, $values) {
7502 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
7503 return false;
7505 reset($values);
7506 $result = array();
7507 foreach ($keys as $key) {
7508 $result[$key] = current($values);
7509 next($values);
7511 return $result;
7517 * This function will make a complete copy of anything it's given,
7518 * regardless of whether it's an object or not.
7519 * @param mixed $thing
7520 * @return mixed
7522 function fullclone($thing) {
7523 return unserialize(serialize($thing));
7528 * This function expects to called during shutdown
7529 * should be set via register_shutdown_function()
7530 * in lib/setup.php .
7532 * Right now we do it only if we are under apache, to
7533 * make sure apache children that hog too much mem are
7534 * killed.
7537 function moodle_request_shutdown() {
7539 global $CFG;
7541 // initially, we are only ever called under apache
7542 // but check just in case
7543 if (function_exists('apache_child_terminate')
7544 && function_exists('memory_get_usage')
7545 && ini_get_bool('child_terminate')) {
7546 if (empty($CFG->apachemaxmem)) {
7547 $CFG->apachemaxmem = 25000000; // default 25MiB
7549 if (memory_get_usage() > (int)$CFG->apachemaxmem) {
7550 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
7551 @apache_child_terminate();
7554 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
7555 if (defined('MDL_PERFTOLOG')) {
7556 $perf = get_performance_info();
7557 error_log("PERF: " . $perf['txt']);
7559 if (defined('MDL_PERFINC')) {
7560 $inc = get_included_files();
7561 $ts = 0;
7562 foreach($inc as $f) {
7563 if (preg_match(':^/:', $f)) {
7564 $fs = filesize($f);
7565 $ts += $fs;
7566 $hfs = display_size($fs);
7567 error_log(substr($f,strlen($CFG->dirroot)) . " size: $fs ($hfs)"
7568 , NULL, NULL, 0);
7569 } else {
7570 error_log($f , NULL, NULL, 0);
7573 if ($ts > 0 ) {
7574 $hts = display_size($ts);
7575 error_log("Total size of files included: $ts ($hts)");
7582 * If new messages are waiting for the current user, then return
7583 * Javascript code to create a popup window
7585 * @return string Javascript code
7587 function message_popup_window() {
7588 global $USER;
7590 $popuplimit = 30; // Minimum seconds between popups
7592 if (!defined('MESSAGE_WINDOW')) {
7593 if (isset($USER->id) and !isguestuser()) {
7594 if (!isset($USER->message_lastpopup)) {
7595 $USER->message_lastpopup = 0;
7597 if ((time() - $USER->message_lastpopup) > $popuplimit) { /// It's been long enough
7598 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
7599 if (count_records_select('message', 'useridto = \''.$USER->id.'\' AND timecreated > \''.$USER->message_lastpopup.'\'')) {
7600 $USER->message_lastpopup = time();
7601 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
7602 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
7609 return '';
7612 // Used to make sure that $min <= $value <= $max
7613 function bounded_number($min, $value, $max) {
7614 if($value < $min) {
7615 return $min;
7617 if($value > $max) {
7618 return $max;
7620 return $value;
7623 function array_is_nested($array) {
7624 foreach ($array as $value) {
7625 if (is_array($value)) {
7626 return true;
7629 return false;
7633 *** get_performance_info() pairs up with init_performance_info()
7634 *** loaded in setup.php. Returns an array with 'html' and 'txt'
7635 *** values ready for use, and each of the individual stats provided
7636 *** separately as well.
7639 function get_performance_info() {
7640 global $CFG, $PERF, $rcache;
7642 $info = array();
7643 $info['html'] = ''; // holds userfriendly HTML representation
7644 $info['txt'] = me() . ' '; // holds log-friendly representation
7646 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
7648 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
7649 $info['txt'] .= 'time: '.$info['realtime'].'s ';
7651 if (function_exists('memory_get_usage')) {
7652 $info['memory_total'] = memory_get_usage();
7653 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
7654 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
7655 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
7658 if (function_exists('memory_get_peak_usage')) {
7659 $info['memory_peak'] = memory_get_peak_usage();
7660 $info['html'] .= '<span class="memoryused">RAM peak: '.display_size($info['memory_peak']).'</span> ';
7661 $info['txt'] .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
7664 $inc = get_included_files();
7665 //error_log(print_r($inc,1));
7666 $info['includecount'] = count($inc);
7667 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
7668 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
7670 if (!empty($PERF->dbqueries)) {
7671 $info['dbqueries'] = $PERF->dbqueries;
7672 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
7673 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
7676 if (!empty($PERF->logwrites)) {
7677 $info['logwrites'] = $PERF->logwrites;
7678 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
7679 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
7682 if (!empty($PERF->profiling) && $PERF->profiling) {
7683 require_once($CFG->dirroot .'/lib/profilerlib.php');
7684 $info['html'] .= '<span class="profilinginfo">'.Profiler::get_profiling(array('-R')).'</span>';
7687 if (function_exists('posix_times')) {
7688 $ptimes = posix_times();
7689 if (is_array($ptimes)) {
7690 foreach ($ptimes as $key => $val) {
7691 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
7693 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
7694 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
7698 // Grab the load average for the last minute
7699 // /proc will only work under some linux configurations
7700 // while uptime is there under MacOSX/Darwin and other unices
7701 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
7702 list($server_load) = explode(' ', $loadavg[0]);
7703 unset($loadavg);
7704 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
7705 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
7706 $server_load = $matches[1];
7707 } else {
7708 trigger_error('Could not parse uptime output!');
7711 if (!empty($server_load)) {
7712 $info['serverload'] = $server_load;
7713 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
7714 $info['txt'] .= "serverload: {$info['serverload']} ";
7717 if (isset($rcache->hits) && isset($rcache->misses)) {
7718 $info['rcachehits'] = $rcache->hits;
7719 $info['rcachemisses'] = $rcache->misses;
7720 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
7721 "{$rcache->hits}/{$rcache->misses}</span> ";
7722 $info['txt'] .= 'rcache: '.
7723 "{$rcache->hits}/{$rcache->misses} ";
7725 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
7726 return $info;
7729 function apd_get_profiling() {
7730 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
7734 * Delete directory or only it's content
7735 * @param string $dir directory path
7736 * @param bool $content_only
7737 * @return bool success, true also if dir does not exist
7739 function remove_dir($dir, $content_only=false) {
7740 if (!file_exists($dir)) {
7741 // nothing to do
7742 return true;
7744 $handle = opendir($dir);
7745 $result = true;
7746 while (false!==($item = readdir($handle))) {
7747 if($item != '.' && $item != '..') {
7748 if(is_dir($dir.'/'.$item)) {
7749 $result = remove_dir($dir.'/'.$item) && $result;
7750 }else{
7751 $result = unlink($dir.'/'.$item) && $result;
7755 closedir($handle);
7756 if ($content_only) {
7757 return $result;
7759 return rmdir($dir); // if anything left the result will be false, noo need for && $result
7763 * Function to check if a directory exists and optionally create it.
7765 * @param string absolute directory path (must be under $CFG->dataroot)
7766 * @param boolean create directory if does not exist
7767 * @param boolean create directory recursively
7769 * @return boolean true if directory exists or created
7771 function check_dir_exists($dir, $create=false, $recursive=false) {
7773 global $CFG;
7775 if (strstr($dir, $CFG->dataroot.'/') === false) {
7776 debugging('Warning. Wrong call to check_dir_exists(). $dir must be an absolute path under $CFG->dataroot ("' . $dir . '" is incorrect)', DEBUG_DEVELOPER);
7779 $status = true;
7781 if(!is_dir($dir)) {
7782 if (!$create) {
7783 $status = false;
7784 } else {
7785 umask(0000);
7786 if ($recursive) {
7787 /// PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
7788 $dir = str_replace('\\', '/', $dir); //windows compatibility
7789 /// We are going to make it recursive under $CFG->dataroot only
7790 /// (will help sites running open_basedir security and others)
7791 $dir = str_replace($CFG->dataroot . '/', '', $dir);
7792 $dirs = explode('/', $dir); /// Extract path parts
7793 /// Iterate over each part with start point $CFG->dataroot
7794 $dir = $CFG->dataroot . '/';
7795 foreach ($dirs as $part) {
7796 if ($part == '') {
7797 continue;
7799 $dir .= $part.'/';
7800 if (!is_dir($dir)) {
7801 if (!mkdir($dir, $CFG->directorypermissions)) {
7802 $status = false;
7803 break;
7807 } else {
7808 $status = mkdir($dir, $CFG->directorypermissions);
7812 return $status;
7815 function report_session_error() {
7816 global $CFG, $FULLME;
7818 if (empty($CFG->lang)) {
7819 $CFG->lang = "en";
7821 // Set up default theme and locale
7822 theme_setup();
7823 moodle_setlocale();
7825 //clear session cookies
7826 if (check_php_version('5.2.0')) {
7827 //PHP 5.2.0
7828 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
7829 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure, $CFG->cookiehttponly);
7830 } else {
7831 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
7832 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath, '', $CFG->cookiesecure);
7834 //increment database error counters
7835 if (isset($CFG->session_error_counter)) {
7836 set_config('session_error_counter', 1 + $CFG->session_error_counter);
7837 } else {
7838 set_config('session_error_counter', 1);
7840 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
7845 * Detect if an object or a class contains a given property
7846 * will take an actual object or the name of a class
7847 * @param mix $obj Name of class or real object to test
7848 * @param string $property name of property to find
7849 * @return bool true if property exists
7851 function object_property_exists( $obj, $property ) {
7852 if (is_string( $obj )) {
7853 $properties = get_class_vars( $obj );
7855 else {
7856 $properties = get_object_vars( $obj );
7858 return array_key_exists( $property, $properties );
7863 * Detect a custom script replacement in the data directory that will
7864 * replace an existing moodle script
7865 * @param string $urlpath path to the original script
7866 * @return string full path name if a custom script exists
7867 * @return bool false if no custom script exists
7869 function custom_script_path($urlpath='') {
7870 global $CFG;
7872 // set default $urlpath, if necessary
7873 if (empty($urlpath)) {
7874 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
7877 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
7878 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot) === false )) {
7879 return false;
7882 // replace wwwroot with the path to the customscripts folder and clean path
7883 $scriptpath = $CFG->customscripts . clean_param(substr($urlpath, strlen($CFG->wwwroot)), PARAM_PATH);
7885 // remove the query string, if any
7886 if (($strpos = strpos($scriptpath, '?')) !== false) {
7887 $scriptpath = substr($scriptpath, 0, $strpos);
7890 // remove trailing slashes, if any
7891 $scriptpath = rtrim($scriptpath, '/\\');
7893 // append index.php, if necessary
7894 if (is_dir($scriptpath)) {
7895 $scriptpath .= '/index.php';
7898 // check the custom script exists
7899 if (file_exists($scriptpath)) {
7900 return $scriptpath;
7901 } else {
7902 return false;
7907 * Wrapper function to load necessary editor scripts
7908 * to $CFG->editorsrc array. Params can be coursei id
7909 * or associative array('courseid' => value, 'name' => 'editorname').
7910 * @uses $CFG
7911 * @param mixed $args Courseid or associative array.
7913 function loadeditor($args) {
7914 global $CFG;
7915 include($CFG->libdir .'/editorlib.php');
7916 return editorObject::loadeditor($args);
7920 * Returns whether or not the user object is a remote MNET user. This function
7921 * is in moodlelib because it does not rely on loading any of the MNET code.
7923 * @param object $user A valid user object
7924 * @return bool True if the user is from a remote Moodle.
7926 function is_mnet_remote_user($user) {
7927 global $CFG;
7929 if (!isset($CFG->mnet_localhost_id)) {
7930 include_once $CFG->dirroot . '/mnet/lib.php';
7931 $env = new mnet_environment();
7932 $env->init();
7933 unset($env);
7936 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
7940 * Checks if a given plugin is in the list of enabled enrolment plugins.
7942 * @param string $auth Enrolment plugin.
7943 * @return boolean Whether the plugin is enabled.
7945 function is_enabled_enrol($enrol='') {
7946 global $CFG;
7948 // use the global default if not specified
7949 if ($enrol == '') {
7950 $enrol = $CFG->enrol;
7952 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
7956 * This function will search for browser prefereed languages, setting Moodle
7957 * to use the best one available if $SESSION->lang is undefined
7959 function setup_lang_from_browser() {
7961 global $CFG, $SESSION, $USER;
7963 if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
7964 // Lang is defined in session or user profile, nothing to do
7965 return;
7968 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
7969 return;
7972 /// Extract and clean langs from headers
7973 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
7974 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
7975 $rawlangs = explode(',', $rawlangs); // Convert to array
7976 $langs = array();
7978 $order = 1.0;
7979 foreach ($rawlangs as $lang) {
7980 if (strpos($lang, ';') === false) {
7981 $langs[(string)$order] = $lang;
7982 $order = $order-0.01;
7983 } else {
7984 $parts = explode(';', $lang);
7985 $pos = strpos($parts[1], '=');
7986 $langs[substr($parts[1], $pos+1)] = $parts[0];
7989 krsort($langs, SORT_NUMERIC);
7991 $langlist = get_list_of_languages();
7993 /// Look for such langs under standard locations
7994 foreach ($langs as $lang) {
7995 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR)); // clean it properly for include
7996 if (!array_key_exists($lang, $langlist)) {
7997 continue; // language not allowed, try next one
7999 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
8000 $SESSION->lang = $lang; /// Lang exists, set it in session
8001 break; /// We have finished. Go out
8004 return;
8008 ////////////////////////////////////////////////////////////////////////////////
8010 function is_newnav($navigation) {
8011 if (is_array($navigation) && !empty($navigation['newnav'])) {
8012 return true;
8013 } else {
8014 return false;
8019 * Checks whether the given variable name is defined as a variable within the given object.
8020 * @note This will NOT work with stdClass objects, which have no class variables.
8021 * @param string $var The variable name
8022 * @param object $object The object to check
8023 * @return boolean
8025 function in_object_vars($var, $object) {
8026 $class_vars = get_class_vars(get_class($object));
8027 $class_vars = array_keys($class_vars);
8028 return in_array($var, $class_vars);
8032 * Returns an array without repeated objects.
8033 * This function is similar to array_unique, but for arrays that have objects as values
8035 * @param unknown_type $array
8036 * @param unknown_type $keep_key_assoc
8037 * @return unknown
8039 function object_array_unique($array, $keep_key_assoc = true) {
8040 $duplicate_keys = array();
8041 $tmp = array();
8043 foreach ($array as $key=>$val) {
8044 // convert objects to arrays, in_array() does not support objects
8045 if (is_object($val)) {
8046 $val = (array)$val;
8049 if (!in_array($val, $tmp)) {
8050 $tmp[] = $val;
8051 } else {
8052 $duplicate_keys[] = $key;
8056 foreach ($duplicate_keys as $key) {
8057 unset($array[$key]);
8060 return $keep_key_assoc ? $array : array_values($array);
8064 * Returns the language string for the given plugin.
8066 * @param string $plugin the plugin code name
8067 * @param string $type the type of plugin (mod, block, filter)
8068 * @return string The plugin language string
8070 function get_plugin_name($plugin, $type='mod') {
8071 $plugin_name = '';
8073 switch ($type) {
8074 case 'mod':
8075 $plugin_name = get_string('modulename', $plugin);
8076 break;
8077 case 'blocks':
8078 $plugin_name = get_string('blockname', "block_$plugin");
8079 if (empty($plugin_name) || $plugin_name == '[[blockname]]') {
8080 if (($block = block_instance($plugin)) !== false) {
8081 $plugin_name = $block->get_title();
8082 } else {
8083 $plugin_name = "[[$plugin]]";
8086 break;
8087 case 'filter':
8088 $plugin_name = trim(get_string('filtername', $plugin));
8089 if (empty($plugin_name) or ($plugin_name == '[[filtername]]')) {
8090 $textlib = textlib_get_instance();
8091 $plugin_name = $textlib->strtotitle($plugin);
8093 break;
8094 default:
8095 $plugin_name = $plugin;
8096 break;
8099 return $plugin_name;
8103 * Is a userid the primary administrator?
8105 * @param $userid int id of user to check
8106 * @return boolean
8108 function is_primary_admin($userid){
8109 $primaryadmin = get_admin();
8111 if($userid == $primaryadmin->id){
8112 return true;
8113 }else{
8114 return false;
8118 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: