MDL-11462 fixed PARAM_URL inline focs, uncommented old regex in URL validation librar...
[moodle-pu.git] / lib / moodlelib.php
blob5a65aa27b6ae35c0a05a7319a872870ed574e7f2
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-2004 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 and E_RECOVERABLE_ERROR for now */
246 define ('DEBUG_ALL', 2047);
247 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
248 define ('DEBUG_DEVELOPER', 34815);
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 define('TAG_MAX_LENGTH', 50);
266 /// PARAMETER HANDLING ////////////////////////////////////////////////////
269 * Returns a particular value for the named variable, taken from
270 * POST or GET. If the parameter doesn't exist then an error is
271 * thrown because we require this variable.
273 * This function should be used to initialise all required values
274 * in a script that are based on parameters. Usually it will be
275 * used like this:
276 * $id = required_param('id');
278 * @param string $parname the name of the page parameter we want
279 * @param int $type expected type of parameter
280 * @return mixed
282 function required_param($parname, $type=PARAM_CLEAN) {
284 // detect_unchecked_vars addition
285 global $CFG;
286 if (!empty($CFG->detect_unchecked_vars)) {
287 global $UNCHECKED_VARS;
288 unset ($UNCHECKED_VARS->vars[$parname]);
291 if (isset($_POST[$parname])) { // POST has precedence
292 $param = $_POST[$parname];
293 } else if (isset($_GET[$parname])) {
294 $param = $_GET[$parname];
295 } else {
296 error('A required parameter ('.$parname.') was missing');
299 return clean_param($param, $type);
303 * Returns a particular value for the named variable, taken from
304 * POST or GET, otherwise returning a given default.
306 * This function should be used to initialise all optional values
307 * in a script that are based on parameters. Usually it will be
308 * used like this:
309 * $name = optional_param('name', 'Fred');
311 * @param string $parname the name of the page parameter we want
312 * @param mixed $default the default value to return if nothing is found
313 * @param int $type expected type of parameter
314 * @return mixed
316 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
318 // detect_unchecked_vars addition
319 global $CFG;
320 if (!empty($CFG->detect_unchecked_vars)) {
321 global $UNCHECKED_VARS;
322 unset ($UNCHECKED_VARS->vars[$parname]);
325 if (isset($_POST[$parname])) { // POST has precedence
326 $param = $_POST[$parname];
327 } else if (isset($_GET[$parname])) {
328 $param = $_GET[$parname];
329 } else {
330 return $default;
333 return clean_param($param, $type);
337 * Used by {@link optional_param()} and {@link required_param()} to
338 * clean the variables and/or cast to specific types, based on
339 * an options field.
340 * <code>
341 * $course->format = clean_param($course->format, PARAM_ALPHA);
342 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
343 * </code>
345 * @uses $CFG
346 * @uses PARAM_CLEAN
347 * @uses PARAM_INT
348 * @uses PARAM_INTEGER
349 * @uses PARAM_ALPHA
350 * @uses PARAM_ALPHANUM
351 * @uses PARAM_NOTAGS
352 * @uses PARAM_ALPHAEXT
353 * @uses PARAM_BOOL
354 * @uses PARAM_SAFEDIR
355 * @uses PARAM_CLEANFILE
356 * @uses PARAM_FILE
357 * @uses PARAM_PATH
358 * @uses PARAM_HOST
359 * @uses PARAM_URL
360 * @uses PARAM_LOCALURL
361 * @uses PARAM_CLEANHTML
362 * @uses PARAM_SEQUENCE
363 * @param mixed $param the variable we are cleaning
364 * @param int $type expected format of param after cleaning.
365 * @return mixed
367 function clean_param($param, $type) {
369 global $CFG;
371 if (is_array($param)) { // Let's loop
372 $newparam = array();
373 foreach ($param as $key => $value) {
374 $newparam[$key] = clean_param($value, $type);
376 return $newparam;
379 switch ($type) {
380 case PARAM_RAW: // no cleaning at all
381 return $param;
383 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
384 if (is_numeric($param)) {
385 return $param;
387 $param = stripslashes($param); // Needed for kses to work fine
388 $param = clean_text($param); // Sweep for scripts, etc
389 return addslashes($param); // Restore original request parameter slashes
391 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
392 $param = stripslashes($param); // Remove any slashes
393 $param = clean_text($param); // Sweep for scripts, etc
394 return trim($param);
396 case PARAM_INT:
397 return (int)$param; // Convert to integer
399 case PARAM_NUMBER:
400 return (float)$param; // Convert to integer
402 case PARAM_ALPHA: // Remove everything not a-z
403 return eregi_replace('[^a-zA-Z]', '', $param);
405 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
406 return eregi_replace('[^A-Za-z0-9]', '', $param);
408 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z/_-
409 return eregi_replace('[^a-zA-Z/_-]', '', $param);
411 case PARAM_SEQUENCE: // Remove everything not 0-9,
412 return eregi_replace('[^0-9,]', '', $param);
414 case PARAM_BOOL: // Convert to 1 or 0
415 $tempstr = strtolower($param);
416 if ($tempstr == 'on' or $tempstr == 'yes' ) {
417 $param = 1;
418 } else if ($tempstr == 'off' or $tempstr == 'no') {
419 $param = 0;
420 } else {
421 $param = empty($param) ? 0 : 1;
423 return $param;
425 case PARAM_NOTAGS: // Strip all tags
426 return strip_tags($param);
428 case PARAM_TEXT: // leave only tags needed for multilang
429 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
431 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
432 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
434 case PARAM_CLEANFILE: // allow only safe characters
435 return clean_filename($param);
437 case PARAM_FILE: // Strip all suspicious characters from filename
438 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
439 $param = ereg_replace('\.\.+', '', $param);
440 if($param == '.') {
441 $param = '';
443 return $param;
445 case PARAM_PATH: // Strip all suspicious characters from file path
446 $param = str_replace('\\\'', '\'', $param);
447 $param = str_replace('\\"', '"', $param);
448 $param = str_replace('\\', '/', $param);
449 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
450 $param = ereg_replace('\.\.+', '', $param);
451 $param = ereg_replace('//+', '/', $param);
452 return ereg_replace('/(\./)+', '/', $param);
454 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
455 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
456 // match ipv4 dotted quad
457 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
458 // confirm values are ok
459 if ( $match[0] > 255
460 || $match[1] > 255
461 || $match[3] > 255
462 || $match[4] > 255 ) {
463 // hmmm, what kind of dotted quad is this?
464 $param = '';
466 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
467 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
468 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
470 // all is ok - $param is respected
471 } else {
472 // all is not ok...
473 $param='';
475 return $param;
477 case PARAM_URL: // allow safe ftp, http, mailto urls
478 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
479 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
480 // all is ok, param is respected
481 } else {
482 $param =''; // not really ok
484 return $param;
486 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
487 $param = clean_param($param, PARAM_URL);
488 if (!empty($param)) {
489 if (preg_match(':^/:', $param)) {
490 // root-relative, ok!
491 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
492 // absolute, and matches our wwwroot
493 } else {
494 // relative - let's make sure there are no tricks
495 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
496 // looks ok.
497 } else {
498 $param = '';
502 return $param;
504 case PARAM_PEM:
505 $param = trim($param);
506 // PEM formatted strings may contain letters/numbers and the symbols
507 // forward slash: /
508 // plus sign: +
509 // equal sign: =
510 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
511 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
512 list($wholething, $body) = $matches;
513 unset($wholething, $matches);
514 $b64 = clean_param($body, PARAM_BASE64);
515 if (!empty($b64)) {
516 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
517 } else {
518 return '';
521 return '';
523 case PARAM_BASE64:
524 if (!empty($param)) {
525 // PEM formatted strings may contain letters/numbers and the symbols
526 // forward slash: /
527 // plus sign: +
528 // equal sign: =
529 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
530 return '';
532 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
533 // Each line of base64 encoded data must be 64 characters in
534 // length, except for the last line which may be less than (or
535 // equal to) 64 characters long.
536 for ($i=0, $j=count($lines); $i < $j; $i++) {
537 if ($i + 1 == $j) {
538 if (64 < strlen($lines[$i])) {
539 return '';
541 continue;
544 if (64 != strlen($lines[$i])) {
545 return '';
548 return implode("\n",$lines);
549 } else {
550 return '';
553 case PARAM_TAG:
554 //first fix whitespace
555 $param = preg_replace('/\s+/', ' ', $param);
556 //remove blacklisted ASCII ranges of chars - security FIRST - keep only ascii letters, numnbers and spaces
557 //the result should be safe to be used directly in html and SQL
558 $param = preg_replace("/[\\000-\\x1f\\x21-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]/", '', $param);
559 //now remove some unicode ranges we do not want
560 $param = preg_replace("/[\\x{80}-\\x{bf}\\x{d7}\\x{f7}]/u", '', $param);
561 //cleanup the spaces
562 $param = preg_replace('/ +/', ' ', $param);
563 $param = trim($param);
564 $textlib = textlib_get_instance();
565 $param = $textlib->substr($param, 0, TAG_MAX_LENGTH);
566 //numeric tags not allowed
567 return is_numeric($param) ? '' : $param;
569 case PARAM_TAGLIST:
570 $tags = explode(',', $param);
571 $result = array();
572 foreach ($tags as $tag) {
573 $res = clean_param($tag, PARAM_TAG);
574 if ($res != '') {
575 $result[] = $res;
578 if ($result) {
579 return implode(',', $result);
580 } else {
581 return '';
584 default: // throw error, switched parameters in optional_param or another serious problem
585 error("Unknown parameter type: $type");
592 * Set a key in global configuration
594 * Set a key/value pair in both this session's {@link $CFG} global variable
595 * and in the 'config' database table for future sessions.
597 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
598 * In that case it doesn't affect $CFG.
600 * @param string $name the key to set
601 * @param string $value the value to set (without magic quotes)
602 * @param string $plugin (optional) the plugin scope
603 * @uses $CFG
604 * @return bool
606 function set_config($name, $value, $plugin=NULL) {
607 /// No need for get_config because they are usually always available in $CFG
609 global $CFG;
611 if (empty($plugin)) {
612 $CFG->$name = $value; // So it's defined for this invocation at least
614 if (get_field('config', 'name', 'name', $name)) {
615 return set_field('config', 'value', addslashes($value), 'name', $name);
616 } else {
617 $config = new object();
618 $config->name = $name;
619 $config->value = addslashes($value);
620 return insert_record('config', $config);
622 } else { // plugin scope
623 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
624 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
625 } else {
626 $config = new object();
627 $config->plugin = addslashes($plugin);
628 $config->name = $name;
629 $config->value = addslashes($value);
630 return insert_record('config_plugins', $config);
636 * Get configuration values from the global config table
637 * or the config_plugins table.
639 * If called with no parameters it will do the right thing
640 * generating $CFG safely from the database without overwriting
641 * existing values.
643 * If called with 2 parameters it will return a $string single
644 * value or false of the value is not found.
646 * @param string $plugin
647 * @param string $name
648 * @uses $CFG
649 * @return hash-like object or single value
652 function get_config($plugin=NULL, $name=NULL) {
654 global $CFG;
656 if (!empty($name)) { // the user is asking for a specific value
657 if (!empty($plugin)) {
658 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
659 } else {
660 return get_field('config', 'value', 'name', $name);
664 // the user is after a recordset
665 if (!empty($plugin)) {
666 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
667 $configs = (array)$configs;
668 $localcfg = array();
669 foreach ($configs as $config) {
670 $localcfg[$config->name] = $config->value;
672 return (object)$localcfg;
673 } else {
674 return false;
676 } else {
677 // this was originally in setup.php
678 if ($configs = get_records('config')) {
679 $localcfg = (array)$CFG;
680 foreach ($configs as $config) {
681 if (!isset($localcfg[$config->name])) {
682 $localcfg[$config->name] = $config->value;
683 } else {
684 if ($localcfg[$config->name] != $config->value ) {
685 // complain if the DB has a different
686 // value than config.php does
687 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
692 $localcfg = (object)$localcfg;
693 return $localcfg;
694 } else {
695 // preserve $CFG if DB returns nothing or error
696 return $CFG;
703 * Removes a key from global configuration
705 * @param string $name the key to set
706 * @param string $plugin (optional) the plugin scope
707 * @uses $CFG
708 * @return bool
710 function unset_config($name, $plugin=NULL) {
712 global $CFG;
714 unset($CFG->$name);
716 if (empty($plugin)) {
717 return delete_records('config', 'name', $name);
718 } else {
719 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
725 * Refresh current $USER session global variable with all their current preferences.
726 * @uses $USER
728 function reload_user_preferences() {
730 global $USER;
732 //reset preference
733 $USER->preference = array();
735 if (!isloggedin() or isguestuser()) {
736 // no pernament storage for not-logged-in user and guest
738 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
739 foreach ($preferences as $preference) {
740 $USER->preference[$preference->name] = $preference->value;
744 return true;
748 * Sets a preference for the current user
749 * Optionally, can set a preference for a different user object
750 * @uses $USER
751 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
753 * @param string $name The key to set as preference for the specified user
754 * @param string $value The value to set forthe $name key in the specified user's record
755 * @param int $otheruserid A moodle user ID
756 * @return bool
758 function set_user_preference($name, $value, $otheruserid=NULL) {
760 global $USER;
762 if (!isset($USER->preference)) {
763 reload_user_preferences();
766 if (empty($name)) {
767 return false;
770 $nostore = false;
772 if (empty($otheruserid)){
773 if (!isloggedin() or isguestuser()) {
774 $nostore = true;
776 $userid = $USER->id;
777 } else {
778 if (isguestuser($otheruserid)) {
779 $nostore = true;
781 $userid = $otheruserid;
784 $return = true;
785 if ($nostore) {
786 // no pernament storage for not-logged-in user and guest
788 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
789 if ($preference->value === $value) {
790 return true;
792 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
793 $return = false;
796 } else {
797 $preference = new object();
798 $preference->userid = $userid;
799 $preference->name = addslashes($name);
800 $preference->value = addslashes((string)$value);
801 if (!insert_record('user_preferences', $preference)) {
802 $return = false;
806 // update value in USER session if needed
807 if ($userid == $USER->id) {
808 $USER->preference[$name] = (string)$value;
811 return $return;
815 * Unsets a preference completely by deleting it from the database
816 * Optionally, can set a preference for a different user id
817 * @uses $USER
818 * @param string $name The key to unset as preference for the specified user
819 * @param int $otheruserid A moodle user ID
821 function unset_user_preference($name, $otheruserid=NULL) {
823 global $USER;
825 if (!isset($USER->preference)) {
826 reload_user_preferences();
829 if (empty($otheruserid)){
830 $userid = $USER->id;
831 } else {
832 $userid = $otheruserid;
835 //Delete the preference from $USER if needed
836 if ($userid == $USER->id) {
837 unset($USER->preference[$name]);
840 //Then from DB
841 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
846 * Sets a whole array of preferences for the current user
847 * @param array $prefarray An array of key/value pairs to be set
848 * @param int $otheruserid A moodle user ID
849 * @return bool
851 function set_user_preferences($prefarray, $otheruserid=NULL) {
853 if (!is_array($prefarray) or empty($prefarray)) {
854 return false;
857 $return = true;
858 foreach ($prefarray as $name => $value) {
859 // The order is important; test for return is done first
860 $return = (set_user_preference($name, $value, $otheruserid) && $return);
862 return $return;
866 * If no arguments are supplied this function will return
867 * all of the current user preferences as an array.
868 * If a name is specified then this function
869 * attempts to return that particular preference value. If
870 * none is found, then the optional value $default is returned,
871 * otherwise NULL.
872 * @param string $name Name of the key to use in finding a preference value
873 * @param string $default Value to be returned if the $name key is not set in the user preferences
874 * @param int $otheruserid A moodle user ID
875 * @uses $USER
876 * @return string
878 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
879 global $USER;
881 if (!isset($USER->preference)) {
882 reload_user_preferences();
885 if (empty($otheruserid)){
886 $userid = $USER->id;
887 } else {
888 $userid = $otheruserid;
891 if ($userid == $USER->id) {
892 $preference = $USER->preference;
894 } else {
895 $preference = array();
896 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
897 foreach ($prefdata as $pref) {
898 $preference[$pref->name] = $pref->value;
903 if (empty($name)) {
904 return $preference; // All values
906 } else if (array_key_exists($name, $preference)) {
907 return $preference[$name]; // The single value
909 } else {
910 return $default; // Default value (or NULL)
915 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
918 * Given date parts in user time produce a GMT timestamp.
920 * @param int $year The year part to create timestamp of
921 * @param int $month The month part to create timestamp of
922 * @param int $day The day part to create timestamp of
923 * @param int $hour The hour part to create timestamp of
924 * @param int $minute The minute part to create timestamp of
925 * @param int $second The second part to create timestamp of
926 * @param float $timezone ?
927 * @param bool $applydst ?
928 * @return int timestamp
929 * @todo Finish documenting this function
931 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
933 $timezone = get_user_timezone_offset($timezone);
935 if (abs($timezone) > 13) {
936 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
937 } else {
938 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
939 $time = usertime($time, $timezone);
940 if($applydst) {
941 $time -= dst_offset_on($time);
945 return $time;
950 * Given an amount of time in seconds, returns string
951 * formatted nicely as weeks, days, hours etc as needed
953 * @uses MINSECS
954 * @uses HOURSECS
955 * @uses DAYSECS
956 * @uses YEARSECS
957 * @param int $totalsecs ?
958 * @param array $str ?
959 * @return string
961 function format_time($totalsecs, $str=NULL) {
963 $totalsecs = abs($totalsecs);
965 if (!$str) { // Create the str structure the slow way
966 $str->day = get_string('day');
967 $str->days = get_string('days');
968 $str->hour = get_string('hour');
969 $str->hours = get_string('hours');
970 $str->min = get_string('min');
971 $str->mins = get_string('mins');
972 $str->sec = get_string('sec');
973 $str->secs = get_string('secs');
974 $str->year = get_string('year');
975 $str->years = get_string('years');
979 $years = floor($totalsecs/YEARSECS);
980 $remainder = $totalsecs - ($years*YEARSECS);
981 $days = floor($remainder/DAYSECS);
982 $remainder = $totalsecs - ($days*DAYSECS);
983 $hours = floor($remainder/HOURSECS);
984 $remainder = $remainder - ($hours*HOURSECS);
985 $mins = floor($remainder/MINSECS);
986 $secs = $remainder - ($mins*MINSECS);
988 $ss = ($secs == 1) ? $str->sec : $str->secs;
989 $sm = ($mins == 1) ? $str->min : $str->mins;
990 $sh = ($hours == 1) ? $str->hour : $str->hours;
991 $sd = ($days == 1) ? $str->day : $str->days;
992 $sy = ($years == 1) ? $str->year : $str->years;
994 $oyears = '';
995 $odays = '';
996 $ohours = '';
997 $omins = '';
998 $osecs = '';
1000 if ($years) $oyears = $years .' '. $sy;
1001 if ($days) $odays = $days .' '. $sd;
1002 if ($hours) $ohours = $hours .' '. $sh;
1003 if ($mins) $omins = $mins .' '. $sm;
1004 if ($secs) $osecs = $secs .' '. $ss;
1006 if ($years) return trim($oyears .' '. $odays);
1007 if ($days) return trim($odays .' '. $ohours);
1008 if ($hours) return trim($ohours .' '. $omins);
1009 if ($mins) return trim($omins .' '. $osecs);
1010 if ($secs) return $osecs;
1011 return get_string('now');
1015 * Returns a formatted string that represents a date in user time
1016 * <b>WARNING: note that the format is for strftime(), not date().</b>
1017 * Because of a bug in most Windows time libraries, we can't use
1018 * the nicer %e, so we have to use %d which has leading zeroes.
1019 * A lot of the fuss in the function is just getting rid of these leading
1020 * zeroes as efficiently as possible.
1022 * If parameter fixday = true (default), then take off leading
1023 * zero from %d, else mantain it.
1025 * @uses HOURSECS
1026 * @param int $date timestamp in GMT
1027 * @param string $format strftime format
1028 * @param float $timezone
1029 * @param bool $fixday If true (default) then the leading
1030 * zero from %d is removed. If false then the leading zero is mantained.
1031 * @return string
1033 function userdate($date, $format='', $timezone=99, $fixday = true) {
1035 global $CFG;
1037 if (empty($format)) {
1038 $format = get_string('strftimedaydatetime');
1041 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1042 $fixday = false;
1043 } else if ($fixday) {
1044 $formatnoday = str_replace('%d', 'DD', $format);
1045 $fixday = ($formatnoday != $format);
1048 $date += dst_offset_on($date);
1050 $timezone = get_user_timezone_offset($timezone);
1052 if (abs($timezone) > 13) { /// Server time
1053 if ($fixday) {
1054 $datestring = strftime($formatnoday, $date);
1055 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1056 $datestring = str_replace('DD', $daystring, $datestring);
1057 } else {
1058 $datestring = strftime($format, $date);
1060 } else {
1061 $date += (int)($timezone * 3600);
1062 if ($fixday) {
1063 $datestring = gmstrftime($formatnoday, $date);
1064 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1065 $datestring = str_replace('DD', $daystring, $datestring);
1066 } else {
1067 $datestring = gmstrftime($format, $date);
1071 /// If we are running under Windows convert from windows encoding to UTF-8
1072 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1074 if ($CFG->ostype == 'WINDOWS') {
1075 if ($localewincharset = get_string('localewincharset')) {
1076 $textlib = textlib_get_instance();
1077 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1081 return $datestring;
1085 * Given a $time timestamp in GMT (seconds since epoch),
1086 * returns an array that represents the date in user time
1088 * @uses HOURSECS
1089 * @param int $time Timestamp in GMT
1090 * @param float $timezone ?
1091 * @return array An array that represents the date in user time
1092 * @todo Finish documenting this function
1094 function usergetdate($time, $timezone=99) {
1096 $timezone = get_user_timezone_offset($timezone);
1098 if (abs($timezone) > 13) { // Server time
1099 return getdate($time);
1102 // There is no gmgetdate so we use gmdate instead
1103 $time += dst_offset_on($time);
1104 $time += intval((float)$timezone * HOURSECS);
1106 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1108 list(
1109 $getdate['seconds'],
1110 $getdate['minutes'],
1111 $getdate['hours'],
1112 $getdate['mday'],
1113 $getdate['mon'],
1114 $getdate['year'],
1115 $getdate['wday'],
1116 $getdate['yday'],
1117 $getdate['weekday'],
1118 $getdate['month']
1119 ) = explode('_', $datestring);
1121 return $getdate;
1125 * Given a GMT timestamp (seconds since epoch), offsets it by
1126 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1128 * @uses HOURSECS
1129 * @param int $date Timestamp in GMT
1130 * @param float $timezone
1131 * @return int
1133 function usertime($date, $timezone=99) {
1135 $timezone = get_user_timezone_offset($timezone);
1137 if (abs($timezone) > 13) {
1138 return $date;
1140 return $date - (int)($timezone * HOURSECS);
1144 * Given a time, return the GMT timestamp of the most recent midnight
1145 * for the current user.
1147 * @param int $date Timestamp in GMT
1148 * @param float $timezone ?
1149 * @return ?
1151 function usergetmidnight($date, $timezone=99) {
1153 $timezone = get_user_timezone_offset($timezone);
1154 $userdate = usergetdate($date, $timezone);
1156 // Time of midnight of this user's day, in GMT
1157 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1162 * Returns a string that prints the user's timezone
1164 * @param float $timezone The user's timezone
1165 * @return string
1167 function usertimezone($timezone=99) {
1169 $tz = get_user_timezone($timezone);
1171 if (!is_float($tz)) {
1172 return $tz;
1175 if(abs($tz) > 13) { // Server time
1176 return get_string('serverlocaltime');
1179 if($tz == intval($tz)) {
1180 // Don't show .0 for whole hours
1181 $tz = intval($tz);
1184 if($tz == 0) {
1185 return 'GMT';
1187 else if($tz > 0) {
1188 return 'GMT+'.$tz;
1190 else {
1191 return 'GMT'.$tz;
1197 * Returns a float which represents the user's timezone difference from GMT in hours
1198 * Checks various settings and picks the most dominant of those which have a value
1200 * @uses $CFG
1201 * @uses $USER
1202 * @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
1203 * @return int
1205 function get_user_timezone_offset($tz = 99) {
1207 global $USER, $CFG;
1209 $tz = get_user_timezone($tz);
1211 if (is_float($tz)) {
1212 return $tz;
1213 } else {
1214 $tzrecord = get_timezone_record($tz);
1215 if (empty($tzrecord)) {
1216 return 99.0;
1218 return (float)$tzrecord->gmtoff / HOURMINS;
1223 * Returns a float or a string which denotes the user's timezone
1224 * 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)
1225 * means that for this timezone there are also DST rules to be taken into account
1226 * Checks various settings and picks the most dominant of those which have a value
1228 * @uses $USER
1229 * @uses $CFG
1230 * @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
1231 * @return mixed
1233 function get_user_timezone($tz = 99) {
1234 global $USER, $CFG;
1236 $timezones = array(
1237 $tz,
1238 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1239 isset($USER->timezone) ? $USER->timezone : 99,
1240 isset($CFG->timezone) ? $CFG->timezone : 99,
1243 $tz = 99;
1245 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1246 $tz = $next['value'];
1249 return is_numeric($tz) ? (float) $tz : $tz;
1255 * @uses $CFG
1256 * @uses $db
1257 * @param string $timezonename ?
1258 * @return object
1260 function get_timezone_record($timezonename) {
1261 global $CFG, $db;
1262 static $cache = NULL;
1264 if ($cache === NULL) {
1265 $cache = array();
1268 if (isset($cache[$timezonename])) {
1269 return $cache[$timezonename];
1272 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1273 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1279 * @uses $CFG
1280 * @uses $USER
1281 * @param ? $fromyear ?
1282 * @param ? $to_year ?
1283 * @return bool
1285 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1286 global $CFG, $SESSION;
1288 $usertz = get_user_timezone();
1290 if (is_float($usertz)) {
1291 // Trivial timezone, no DST
1292 return false;
1295 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1296 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1297 unset($SESSION->dst_offsets);
1298 unset($SESSION->dst_range);
1301 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1302 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1303 // This will be the return path most of the time, pretty light computationally
1304 return true;
1307 // Reaching here means we either need to extend our table or create it from scratch
1309 // Remember which TZ we calculated these changes for
1310 $SESSION->dst_offsettz = $usertz;
1312 if(empty($SESSION->dst_offsets)) {
1313 // If we 're creating from scratch, put the two guard elements in there
1314 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1316 if(empty($SESSION->dst_range)) {
1317 // If creating from scratch
1318 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1319 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1321 // Fill in the array with the extra years we need to process
1322 $yearstoprocess = array();
1323 for($i = $from; $i <= $to; ++$i) {
1324 $yearstoprocess[] = $i;
1327 // Take note of which years we have processed for future calls
1328 $SESSION->dst_range = array($from, $to);
1330 else {
1331 // If needing to extend the table, do the same
1332 $yearstoprocess = array();
1334 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1335 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1337 if($from < $SESSION->dst_range[0]) {
1338 // Take note of which years we need to process and then note that we have processed them for future calls
1339 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1340 $yearstoprocess[] = $i;
1342 $SESSION->dst_range[0] = $from;
1344 if($to > $SESSION->dst_range[1]) {
1345 // Take note of which years we need to process and then note that we have processed them for future calls
1346 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1347 $yearstoprocess[] = $i;
1349 $SESSION->dst_range[1] = $to;
1353 if(empty($yearstoprocess)) {
1354 // This means that there was a call requesting a SMALLER range than we have already calculated
1355 return true;
1358 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1359 // Also, the array is sorted in descending timestamp order!
1361 // Get DB data
1362 $presetrecords = 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');
1363 if(empty($presetrecords)) {
1364 return false;
1367 // Remove ending guard (first element of the array)
1368 reset($SESSION->dst_offsets);
1369 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1371 // Add all required change timestamps
1372 foreach($yearstoprocess as $y) {
1373 // Find the record which is in effect for the year $y
1374 foreach($presetrecords as $year => $preset) {
1375 if($year <= $y) {
1376 break;
1380 $changes = dst_changes_for_year($y, $preset);
1382 if($changes === NULL) {
1383 continue;
1385 if($changes['dst'] != 0) {
1386 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1388 if($changes['std'] != 0) {
1389 $SESSION->dst_offsets[$changes['std']] = 0;
1393 // Put in a guard element at the top
1394 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1395 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1397 // Sort again
1398 krsort($SESSION->dst_offsets);
1400 return true;
1403 function dst_changes_for_year($year, $timezone) {
1405 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1406 return NULL;
1409 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1410 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1412 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1413 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1415 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1416 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1418 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1419 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1420 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1422 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1423 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1425 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1428 // $time must NOT be compensated at all, it has to be a pure timestamp
1429 function dst_offset_on($time) {
1430 global $SESSION;
1432 if(!calculate_user_dst_table() || empty($SESSION->dst_offsets)) {
1433 return 0;
1436 reset($SESSION->dst_offsets);
1437 while(list($from, $offset) = each($SESSION->dst_offsets)) {
1438 if($from <= $time) {
1439 break;
1443 // This is the normal return path
1444 if($offset !== NULL) {
1445 return $offset;
1448 // Reaching this point means we haven't calculated far enough, do it now:
1449 // Calculate extra DST changes if needed and recurse. The recursion always
1450 // moves toward the stopping condition, so will always end.
1452 if($from == 0) {
1453 // We need a year smaller than $SESSION->dst_range[0]
1454 if($SESSION->dst_range[0] == 1971) {
1455 return 0;
1457 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL);
1458 return dst_offset_on($time);
1460 else {
1461 // We need a year larger than $SESSION->dst_range[1]
1462 if($SESSION->dst_range[1] == 2035) {
1463 return 0;
1465 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5);
1466 return dst_offset_on($time);
1470 function find_day_in_month($startday, $weekday, $month, $year) {
1472 $daysinmonth = days_in_month($month, $year);
1474 if($weekday == -1) {
1475 // Don't care about weekday, so return:
1476 // abs($startday) if $startday != -1
1477 // $daysinmonth otherwise
1478 return ($startday == -1) ? $daysinmonth : abs($startday);
1481 // From now on we 're looking for a specific weekday
1483 // Give "end of month" its actual value, since we know it
1484 if($startday == -1) {
1485 $startday = -1 * $daysinmonth;
1488 // Starting from day $startday, the sign is the direction
1490 if($startday < 1) {
1492 $startday = abs($startday);
1493 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1495 // This is the last such weekday of the month
1496 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1497 if($lastinmonth > $daysinmonth) {
1498 $lastinmonth -= 7;
1501 // Find the first such weekday <= $startday
1502 while($lastinmonth > $startday) {
1503 $lastinmonth -= 7;
1506 return $lastinmonth;
1509 else {
1511 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1513 $diff = $weekday - $indexweekday;
1514 if($diff < 0) {
1515 $diff += 7;
1518 // This is the first such weekday of the month equal to or after $startday
1519 $firstfromindex = $startday + $diff;
1521 return $firstfromindex;
1527 * Calculate the number of days in a given month
1529 * @param int $month The month whose day count is sought
1530 * @param int $year The year of the month whose day count is sought
1531 * @return int
1533 function days_in_month($month, $year) {
1534 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1538 * Calculate the position in the week of a specific calendar day
1540 * @param int $day The day of the date whose position in the week is sought
1541 * @param int $month The month of the date whose position in the week is sought
1542 * @param int $year The year of the date whose position in the week is sought
1543 * @return int
1545 function dayofweek($day, $month, $year) {
1546 // I wonder if this is any different from
1547 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1548 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1551 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1554 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1555 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1556 * sesskey string if $USER exists, or boolean false if not.
1558 * @uses $USER
1559 * @return string
1561 function sesskey() {
1562 global $USER;
1564 if(!isset($USER)) {
1565 return false;
1568 if (empty($USER->sesskey)) {
1569 $USER->sesskey = random_string(10);
1572 return $USER->sesskey;
1577 * For security purposes, this function will check that the currently
1578 * given sesskey (passed as a parameter to the script or this function)
1579 * matches that of the current user.
1581 * @param string $sesskey optionally provided sesskey
1582 * @return bool
1584 function confirm_sesskey($sesskey=NULL) {
1585 global $USER;
1587 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1588 return true;
1591 if (empty($sesskey)) {
1592 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
1595 if (!isset($USER->sesskey)) {
1596 return false;
1599 return ($USER->sesskey === $sesskey);
1603 * Setup all global $CFG course variables, set locale and also themes
1604 * This function can be used on pages that do not require login instead of require_login()
1606 * @param mixed $courseorid id of the course or course object
1608 function course_setup($courseorid=0) {
1609 global $COURSE, $CFG, $SITE;
1611 /// Redefine global $COURSE if needed
1612 if (empty($courseorid)) {
1613 // no change in global $COURSE - for backwards compatibiltiy
1614 // if require_rogin() used after require_login($courseid);
1615 } else if (is_object($courseorid)) {
1616 $COURSE = clone($courseorid);
1617 } else {
1618 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1619 if (!empty($course->id) and $course->id == SITEID) {
1620 $COURSE = clone($SITE);
1621 } else if (!empty($course->id) and $course->id == $courseorid) {
1622 $COURSE = clone($course);
1623 } else {
1624 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1625 error('Invalid course ID');
1630 /// set locale and themes
1631 moodle_setlocale();
1632 theme_setup();
1637 * This function checks that the current user is logged in and has the
1638 * required privileges
1640 * This function checks that the current user is logged in, and optionally
1641 * whether they are allowed to be in a particular course and view a particular
1642 * course module.
1643 * If they are not logged in, then it redirects them to the site login unless
1644 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1645 * case they are automatically logged in as guests.
1646 * If $courseid is given and the user is not enrolled in that course then the
1647 * user is redirected to the course enrolment page.
1648 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1649 * in the course then the user is redirected to the course home page.
1651 * @uses $CFG
1652 * @uses $SESSION
1653 * @uses $USER
1654 * @uses $FULLME
1655 * @uses SITEID
1656 * @uses $COURSE
1657 * @param mixed $courseorid id of the course or course object
1658 * @param bool $autologinguest
1659 * @param object $cm course module object
1661 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1663 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1665 /// setup global $COURSE, themes, language and locale
1666 course_setup($courseorid);
1668 /// If the user is not even logged in yet then make sure they are
1669 if (!isloggedin()) {
1670 //NOTE: $USER->site check was obsoleted by session test cookie,
1671 // $USER->confirmed test is in login/index.php
1672 $SESSION->wantsurl = $FULLME;
1673 if (!empty($_SERVER['HTTP_REFERER'])) {
1674 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
1676 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
1677 $loginguest = '?loginguest=true';
1678 } else {
1679 $loginguest = '';
1681 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
1682 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
1683 } else {
1684 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1685 redirect($wwwroot .'/login/index.php');
1687 exit;
1690 /// loginas as redirection if needed
1691 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1692 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1693 if ($USER->loginascontext->instanceid != $COURSE->id) {
1694 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
1700 /// check whether the user should be changing password (but only if it is REALLY them)
1701 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
1702 $userauth = get_auth_plugin($USER->auth);
1703 if ($userauth->can_change_password()) {
1704 $SESSION->wantsurl = $FULLME;
1705 if ($changeurl = $userauth->change_password_url()) {
1706 //use plugin custom url
1707 redirect($changeurl);
1708 } else {
1709 //use moodle internal method
1710 if (empty($CFG->loginhttps)) {
1711 redirect($CFG->wwwroot .'/login/change_password.php');
1712 } else {
1713 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1714 redirect($wwwroot .'/login/change_password.php');
1717 } else {
1718 error(get_string('nopasswordchangeforced', 'auth'));
1722 /// Check that the user account is properly set up
1723 if (user_not_fully_set_up($USER)) {
1724 $SESSION->wantsurl = $FULLME;
1725 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
1728 /// Make sure current IP matches the one for this session (if required)
1729 if (!empty($CFG->tracksessionip)) {
1730 if ($USER->sessionIP != md5(getremoteaddr())) {
1731 error(get_string('sessionipnomatch', 'error'));
1735 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1736 sesskey();
1738 // Check that the user has agreed to a site policy if there is one
1739 if (!empty($CFG->sitepolicy)) {
1740 if (!$USER->policyagreed) {
1741 $SESSION->wantsurl = $FULLME;
1742 redirect($CFG->wwwroot .'/user/policy.php');
1746 // Fetch the system context, we are going to use it a lot.
1747 $sysctx = get_context_instance(CONTEXT_SYSTEM);
1749 /// If the site is currently under maintenance, then print a message
1750 if (!has_capability('moodle/site:config', $sysctx)) {
1751 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1752 print_maintenance_message();
1753 exit;
1757 /// groupmembersonly access control
1758 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1759 if (isguestuser() or !groups_has_membership($cm)) {
1760 error(get_string('groupmembersonlyerror', 'group'), $CFG->wwwroot.'/course/view.php?id='.$cm->course);
1764 // Fetch the course context, and prefetch its child contexts
1765 if (!isset($COURSE->context)) {
1766 if ( ! $COURSE->context = get_context_instance(CONTEXT_COURSE, $COURSE->id) ) {
1767 print_error('nocontext');
1770 if ($COURSE->id == SITEID) {
1771 /// Eliminate hidden site activities straight away
1772 if (!empty($cm) && !$cm->visible
1773 && !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
1774 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
1776 return;
1778 } else {
1780 /// Check if the user can be in a particular course
1781 if (empty($USER->access['rsw'][$COURSE->context->path])) {
1783 // Spaghetti logic construct
1785 // - able to view course?
1786 // - able to view category?
1787 // => if either is missing, course is hidden from this user
1789 // It's carefully ordered so we run the cheap checks first, and the
1790 // more costly checks last...
1792 if (! (($COURSE->visible || has_capability('moodle/course:viewhiddencourses', $COURSE->context))
1793 && (course_parent_visible($COURSE)) || has_capability('moodle/course:viewhiddencourses',
1794 get_context_instance(CONTEXT_COURSECAT,
1795 $COURSE->category)))) {
1796 print_header_simple();
1797 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1801 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1803 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $COURSE->context)) {
1804 if ($COURSE->guest == 1) {
1805 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1806 $USER->access = load_temp_role($COURSE->context, $CFG->guestroleid, $USER->access);
1810 /// If the user is a guest then treat them according to the course policy about guests
1812 if (has_capability('moodle/legacy:guest', $COURSE->context, NULL, false)) {
1813 switch ($COURSE->guest) { /// Check course policy about guest access
1815 case 1: /// Guests always allowed
1816 if (!has_capability('moodle/course:view', $COURSE->context)) { // Prohibited by capability
1817 print_header_simple();
1818 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1820 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1821 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1822 get_string('activityiscurrentlyhidden'));
1825 return; // User is allowed to see this course
1827 break;
1829 case 2: /// Guests allowed with key
1830 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
1831 return true;
1833 // otherwise drop through to logic below (--> enrol.php)
1834 break;
1836 default: /// Guests not allowed
1837 $strloggedinasguest = get_string('loggedinasguest');
1838 print_header_simple('', '',
1839 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
1840 if (empty($USER->access['rsw'][$COURSE->context->path])) { // Normal guest
1841 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1842 } else {
1843 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
1844 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
1845 print_footer($COURSE);
1846 exit;
1848 break;
1851 /// For non-guests, check if they have course view access
1853 } else if (has_capability('moodle/course:view', $COURSE->context)) {
1854 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
1855 if (!has_capability('moodle/course:view', $COURSE->context, $USER->realuser)) {
1856 print_header_simple();
1857 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
1861 /// Make sure they can read this activity too, if specified
1863 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $COURSE->context)) {
1864 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1866 return; // User is allowed to see this course
1871 /// Currently not enrolled in the course, so see if they want to enrol
1872 $SESSION->wantsurl = $FULLME;
1873 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
1874 die;
1881 * This function just makes sure a user is logged out.
1883 * @uses $CFG
1884 * @uses $USER
1886 function require_logout() {
1888 global $USER, $CFG, $SESSION;
1890 if (isloggedin()) {
1891 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1893 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1894 foreach($authsequence as $authname) {
1895 $authplugin = get_auth_plugin($authname);
1896 $authplugin->prelogout_hook();
1900 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1901 // This method is just to try to avoid silly warnings from PHP 4.3.0
1902 session_unregister("USER");
1903 session_unregister("SESSION");
1906 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
1907 $file = $line = null;
1908 if (headers_sent($file, $line)) {
1909 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
1910 error_log('Headers were already sent in file: '.$file.' on line '.$line);
1911 } else {
1912 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
1915 unset($_SESSION['USER']);
1916 unset($_SESSION['SESSION']);
1918 unset($SESSION);
1919 unset($USER);
1924 * This is a weaker version of {@link require_login()} which only requires login
1925 * when called from within a course rather than the site page, unless
1926 * the forcelogin option is turned on.
1928 * @uses $CFG
1929 * @param mixed $courseorid The course object or id in question
1930 * @param bool $autologinguest Allow autologin guests if that is wanted
1931 * @param object $cm Course activity module if known
1933 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1934 global $CFG;
1935 if (!empty($CFG->forcelogin)) {
1936 // login required for both SITE and courses
1937 require_login($courseorid, $autologinguest, $cm);
1939 } else if (!empty($cm) and !$cm->visible) {
1940 // always login for hidden activities
1941 require_login($courseorid, $autologinguest, $cm);
1943 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
1944 or (!is_object($courseorid) and $courseorid == SITEID)) {
1945 //login for SITE not required
1946 return;
1948 } else {
1949 // course login always required
1950 require_login($courseorid, $autologinguest, $cm);
1955 * Require key login. Function terminates with error if key not found or incorrect.
1956 * @param string $script unique script identifier
1957 * @param int $instance optional instance id
1959 function require_user_key_login($script, $instance=null) {
1960 global $nomoodlecookie, $USER, $SESSION, $CFG;
1962 if (empty($nomoodlecookie)) {
1963 error('Incorrect use of require_key_login() - session cookies must be disabled!');
1966 /// extra safety
1967 @session_write_close();
1969 $keyvalue = required_param('key', PARAM_ALPHANUM);
1971 if (!$key = get_record('user_private_key', 'script', $script, 'value', $keyvalue, 'instance', $instance)) {
1972 error('Incorrect key');
1975 if (!empty($key->validuntil) and $key->validuntil < time()) {
1976 error('Expired key');
1979 if ($key->iprestriction) {
1980 $remoteaddr = getremoteaddr();
1981 if ($remoteaddr == '' or !address_in_subnet($remoteaddr, $key->iprestriction)) {
1982 error('Client IP address mismatch');
1986 if (!$user = get_record('user', 'id', $key->userid)) {
1987 error('Incorrect user record');
1990 /// emulate normal session
1991 $SESSION = new object();
1992 $USER = $user;
1994 /// note we are not using normal login
1995 if (!defined('USER_KEY_LOGIN')) {
1996 define('USER_KEY_LOGIN', true);
1999 load_all_capabilities();
2001 /// return isntance id - it might be empty
2002 return $key->instance;
2006 * Creates a new private user access key.
2007 * @param string $script unique target identifier
2008 * @param int $userid
2009 * @param instance $int optional instance id
2010 * @param string $iprestriction optional ip restricted access
2011 * @param timestamp $validuntil key valid only until given data
2012 * @return string access key value
2014 function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2015 $key = new object();
2016 $key->script = $script;
2017 $key->userid = $userid;
2018 $key->instance = $instance;
2019 $key->iprestriction = $iprestriction;
2020 $key->validuntil = $validuntil;
2021 $key->timecreated = time();
2023 $key->value = md5($userid.'_'.time().random_string(40)); // something long and unique
2024 while (record_exists('user_private_key', 'value', $key->value)) {
2025 // must be unique
2026 $key->value = md5($userid.'_'.time().random_string(40));
2029 if (!insert_record('user_private_key', $key)) {
2030 error('Can not insert new key');
2033 return $key->value;
2037 * Modify the user table by setting the currently logged in user's
2038 * last login to now.
2040 * @uses $USER
2041 * @return bool
2043 function update_user_login_times() {
2044 global $USER;
2046 $user = new object();
2047 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2048 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
2050 $user->id = $USER->id;
2052 return update_record('user', $user);
2056 * Determines if a user has completed setting up their account.
2058 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
2059 * @return bool
2061 function user_not_fully_set_up($user) {
2062 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
2065 function over_bounce_threshold($user) {
2067 global $CFG;
2069 if (empty($CFG->handlebounces)) {
2070 return false;
2072 // set sensible defaults
2073 if (empty($CFG->minbounces)) {
2074 $CFG->minbounces = 10;
2076 if (empty($CFG->bounceratio)) {
2077 $CFG->bounceratio = .20;
2079 $bouncecount = 0;
2080 $sendcount = 0;
2081 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2082 $bouncecount = $bounce->value;
2084 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2085 $sendcount = $send->value;
2087 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
2091 * @param $user - object containing an id
2092 * @param $reset - will reset the count to 0
2094 function set_send_count($user,$reset=false) {
2095 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
2096 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2097 update_record('user_preferences',$pref);
2099 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2100 // make a new one
2101 $pref->name = 'email_send_count';
2102 $pref->value = 1;
2103 $pref->userid = $user->id;
2104 insert_record('user_preferences',$pref, false);
2109 * @param $user - object containing an id
2110 * @param $reset - will reset the count to 0
2112 function set_bounce_count($user,$reset=false) {
2113 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
2114 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
2115 update_record('user_preferences',$pref);
2117 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
2118 // make a new one
2119 $pref->name = 'email_bounce_count';
2120 $pref->value = 1;
2121 $pref->userid = $user->id;
2122 insert_record('user_preferences',$pref, false);
2127 * Keeps track of login attempts
2129 * @uses $SESSION
2131 function update_login_count() {
2133 global $SESSION;
2135 $max_logins = 10;
2137 if (empty($SESSION->logincount)) {
2138 $SESSION->logincount = 1;
2139 } else {
2140 $SESSION->logincount++;
2143 if ($SESSION->logincount > $max_logins) {
2144 unset($SESSION->wantsurl);
2145 error(get_string('errortoomanylogins'));
2150 * Resets login attempts
2152 * @uses $SESSION
2154 function reset_login_count() {
2155 global $SESSION;
2157 $SESSION->logincount = 0;
2160 function sync_metacourses() {
2162 global $CFG;
2164 if (!$courses = get_records('course', 'metacourse', 1)) {
2165 return;
2168 foreach ($courses as $course) {
2169 sync_metacourse($course);
2174 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2176 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2178 function sync_metacourse($course) {
2179 global $CFG;
2181 // Check the course is valid.
2182 if (!is_object($course)) {
2183 if (!$course = get_record('course', 'id', $course)) {
2184 return false; // invalid course id
2188 // Check that we actually have a metacourse.
2189 if (empty($course->metacourse)) {
2190 return false;
2193 // Get a list of roles that should not be synced.
2194 if (!empty($CFG->nonmetacoursesyncroleids)) {
2195 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2196 } else {
2197 $roleexclusions = '';
2200 // Get the context of the metacourse.
2201 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2203 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2204 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2205 $managers = array_keys($users);
2206 } else {
2207 $managers = array();
2210 // Get assignments of a user to a role that exist in a child course, but
2211 // not in the meta coure. That is, get a list of the assignments that need to be made.
2212 if (!$assignments = get_records_sql("
2213 SELECT
2214 ra.id, ra.roleid, ra.userid
2215 FROM
2216 {$CFG->prefix}role_assignments ra,
2217 {$CFG->prefix}context con,
2218 {$CFG->prefix}course_meta cm
2219 WHERE
2220 ra.contextid = con.id AND
2221 con.contextlevel = " . CONTEXT_COURSE . " AND
2222 con.instanceid = cm.child_course AND
2223 cm.parent_course = {$course->id} AND
2224 $roleexclusions
2225 NOT EXISTS (
2226 SELECT 1 FROM
2227 {$CFG->prefix}role_assignments ra2
2228 WHERE
2229 ra2.userid = ra.userid AND
2230 ra2.roleid = ra.roleid AND
2231 ra2.contextid = {$context->id}
2233 ")) {
2234 $assignments = array();
2237 // Get assignments of a user to a role that exist in the meta course, but
2238 // not in any child courses. That is, get a list of the unassignments that need to be made.
2239 if (!$unassignments = get_records_sql("
2240 SELECT
2241 ra.id, ra.roleid, ra.userid
2242 FROM
2243 {$CFG->prefix}role_assignments ra
2244 WHERE
2245 ra.contextid = {$context->id} AND
2246 $roleexclusions
2247 NOT EXISTS (
2248 SELECT 1 FROM
2249 {$CFG->prefix}role_assignments ra2,
2250 {$CFG->prefix}context con2,
2251 {$CFG->prefix}course_meta cm
2252 WHERE
2253 ra2.userid = ra.userid AND
2254 ra2.roleid = ra.roleid AND
2255 ra2.contextid = con2.id AND
2256 con2.contextlevel = " . CONTEXT_COURSE . " AND
2257 con2.instanceid = cm.child_course AND
2258 cm.parent_course = {$course->id}
2260 ")) {
2261 $unassignments = array();
2264 $success = true;
2266 // Make the unassignments, if they are not managers.
2267 $unchanged = true;
2268 foreach ($unassignments as $unassignment) {
2269 if (!in_array($unassignment->userid, $managers)) {
2270 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
2271 $unchanged = false;
2275 // Make the assignments.
2276 foreach ($assignments as $assignment) {
2277 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
2278 $unchanged = false;
2280 if (!$unchanged) {
2281 // force accessinfo refresh for users visiting this context...
2282 mark_context_dirty($context->path);
2285 return $success;
2287 // TODO: finish timeend and timestart
2288 // maybe we could rely on cron job to do the cleaning from time to time
2292 * Adds a record to the metacourse table and calls sync_metacoures
2294 function add_to_metacourse ($metacourseid, $courseid) {
2296 if (!$metacourse = get_record("course","id",$metacourseid)) {
2297 return false;
2300 if (!$course = get_record("course","id",$courseid)) {
2301 return false;
2304 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2305 $rec = new object();
2306 $rec->parent_course = $metacourseid;
2307 $rec->child_course = $courseid;
2308 if (!insert_record('course_meta',$rec)) {
2309 return false;
2311 return sync_metacourse($metacourseid);
2313 return true;
2318 * Removes the record from the metacourse table and calls sync_metacourse
2320 function remove_from_metacourse($metacourseid, $courseid) {
2322 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2323 return sync_metacourse($metacourseid);
2325 return false;
2330 * Determines if a user is currently logged in
2332 * @uses $USER
2333 * @return bool
2335 function isloggedin() {
2336 global $USER;
2338 return (!empty($USER->id));
2342 * Determines if a user is logged in as real guest user with username 'guest'.
2343 * This function is similar to original isguest() in 1.6 and earlier.
2344 * Current isguest() is deprecated - do not use it anymore.
2346 * @param $user mixed user object or id, $USER if not specified
2347 * @return bool true if user is the real guest user, false if not logged in or other user
2349 function isguestuser($user=NULL) {
2350 global $USER;
2351 if ($user === NULL) {
2352 $user = $USER;
2353 } else if (is_numeric($user)) {
2354 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2357 if (empty($user->id)) {
2358 return false; // not logged in, can not be guest
2361 return ($user->username == 'guest');
2365 * Determines if the currently logged in user is in editing mode.
2366 * Note: originally this function had $userid parameter - it was not usable anyway
2368 * @uses $USER, $PAGE
2369 * @return bool
2371 function isediting() {
2372 global $USER, $PAGE;
2374 if (empty($USER->editing)) {
2375 return false;
2376 } elseif (is_object($PAGE) && method_exists($PAGE,'user_allowed_editing')) {
2377 return $PAGE->user_allowed_editing();
2379 return true;//false;
2383 * Determines if the logged in user is currently moving an activity
2385 * @uses $USER
2386 * @param int $courseid The id of the course being tested
2387 * @return bool
2389 function ismoving($courseid) {
2390 global $USER;
2392 if (!empty($USER->activitycopy)) {
2393 return ($USER->activitycopycourse == $courseid);
2395 return false;
2399 * Given an object containing firstname and lastname
2400 * values, this function returns a string with the
2401 * full name of the person.
2402 * The result may depend on system settings
2403 * or language. 'override' will force both names
2404 * to be used even if system settings specify one.
2406 * @uses $CFG
2407 * @uses $SESSION
2408 * @param object $user A {@link $USER} object to get full name of
2409 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2411 function fullname($user, $override=false) {
2413 global $CFG, $SESSION;
2415 if (!isset($user->firstname) and !isset($user->lastname)) {
2416 return '';
2419 if (!$override) {
2420 if (!empty($CFG->forcefirstname)) {
2421 $user->firstname = $CFG->forcefirstname;
2423 if (!empty($CFG->forcelastname)) {
2424 $user->lastname = $CFG->forcelastname;
2428 if (!empty($SESSION->fullnamedisplay)) {
2429 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2432 if ($CFG->fullnamedisplay == 'firstname lastname') {
2433 return $user->firstname .' '. $user->lastname;
2435 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
2436 return $user->lastname .' '. $user->firstname;
2438 } else if ($CFG->fullnamedisplay == 'firstname') {
2439 if ($override) {
2440 return get_string('fullnamedisplay', '', $user);
2441 } else {
2442 return $user->firstname;
2446 return get_string('fullnamedisplay', '', $user);
2450 * Sets a moodle cookie with an encrypted string
2452 * @uses $CFG
2453 * @uses DAYSECS
2454 * @uses HOURSECS
2455 * @param string $thing The string to encrypt and place in a cookie
2457 function set_moodle_cookie($thing) {
2458 global $CFG;
2460 if ($thing == 'guest') { // Ignore guest account
2461 return;
2464 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2466 $days = 60;
2467 $seconds = DAYSECS*$days;
2469 setCookie($cookiename, '', time() - HOURSECS, '/');
2470 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
2474 * Gets a moodle cookie with an encrypted string
2476 * @uses $CFG
2477 * @return string
2479 function get_moodle_cookie() {
2480 global $CFG;
2482 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2484 if (empty($_COOKIE[$cookiename])) {
2485 return '';
2486 } else {
2487 $thing = rc4decrypt($_COOKIE[$cookiename]);
2488 return ($thing == 'guest') ? '': $thing; // Ignore guest account
2493 * Returns whether a given authentication plugin exists.
2495 * @uses $CFG
2496 * @param string $auth Form of authentication to check for. Defaults to the
2497 * global setting in {@link $CFG}.
2498 * @return boolean Whether the plugin is available.
2500 function exists_auth_plugin($auth) {
2501 global $CFG;
2503 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2504 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2506 return false;
2510 * Checks if a given plugin is in the list of enabled authentication plugins.
2512 * @param string $auth Authentication plugin.
2513 * @return boolean Whether the plugin is enabled.
2515 function is_enabled_auth($auth) {
2516 if (empty($auth)) {
2517 return false;
2520 $enabled = get_enabled_auth_plugins();
2522 return in_array($auth, $enabled);
2526 * Returns an authentication plugin instance.
2528 * @uses $CFG
2529 * @param string $auth name of authentication plugin
2530 * @return object An instance of the required authentication plugin.
2532 function get_auth_plugin($auth) {
2533 global $CFG;
2535 // check the plugin exists first
2536 if (! exists_auth_plugin($auth)) {
2537 error("Authentication plugin '$auth' not found.");
2540 // return auth plugin instance
2541 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2542 $class = "auth_plugin_$auth";
2543 return new $class;
2547 * Returns array of active auth plugins.
2549 * @param bool $fix fix $CFG->auth if needed
2550 * @return array
2552 function get_enabled_auth_plugins($fix=false) {
2553 global $CFG;
2555 $default = array('manual', 'nologin');
2557 if (empty($CFG->auth)) {
2558 $auths = array();
2559 } else {
2560 $auths = explode(',', $CFG->auth);
2563 if ($fix) {
2564 $auths = array_unique($auths);
2565 foreach($auths as $k=>$authname) {
2566 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2567 unset($auths[$k]);
2570 $newconfig = implode(',', $auths);
2571 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2572 set_config('auth', $newconfig);
2576 return (array_merge($default, $auths));
2580 * Returns true if an internal authentication method is being used.
2581 * if method not specified then, global default is assumed
2583 * @uses $CFG
2584 * @param string $auth Form of authentication required
2585 * @return bool
2587 function is_internal_auth($auth) {
2588 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2589 return $authplugin->is_internal();
2593 * Returns an array of user fields
2595 * @uses $CFG
2596 * @uses $db
2597 * @return array User field/column names
2599 function get_user_fieldnames() {
2601 global $CFG, $db;
2603 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2604 unset($fieldarray['ID']);
2606 return $fieldarray;
2610 * Creates the default "guest" user. Used both from
2611 * admin/index.php and login/index.php
2612 * @return mixed user object created or boolean false if the creation has failed
2614 function create_guest_record() {
2616 global $CFG;
2618 $guest = new stdClass();
2619 $guest->auth = 'manual';
2620 $guest->username = 'guest';
2621 $guest->password = hash_internal_user_password('guest');
2622 $guest->firstname = addslashes(get_string('guestuser'));
2623 $guest->lastname = ' ';
2624 $guest->email = 'root@localhost';
2625 $guest->description = addslashes(get_string('guestuserinfo'));
2626 $guest->mnethostid = $CFG->mnet_localhost_id;
2627 $guest->confirmed = 1;
2628 $guest->lang = $CFG->lang;
2629 $guest->timemodified= time();
2631 if (! $guest->id = insert_record("user", $guest)) {
2632 return false;
2635 return $guest;
2639 * Creates a bare-bones user record
2641 * @uses $CFG
2642 * @param string $username New user's username to add to record
2643 * @param string $password New user's password to add to record
2644 * @param string $auth Form of authentication required
2645 * @return object A {@link $USER} object
2646 * @todo Outline auth types and provide code example
2648 function create_user_record($username, $password, $auth='manual') {
2649 global $CFG;
2651 //just in case check text case
2652 $username = trim(moodle_strtolower($username));
2654 $authplugin = get_auth_plugin($auth);
2656 if ($newinfo = $authplugin->get_userinfo($username)) {
2657 $newinfo = truncate_userinfo($newinfo);
2658 foreach ($newinfo as $key => $value){
2659 $newuser->$key = addslashes($value);
2663 if (!empty($newuser->email)) {
2664 if (email_is_not_allowed($newuser->email)) {
2665 unset($newuser->email);
2669 $newuser->auth = $auth;
2670 $newuser->username = $username;
2672 // fix for MDL-8480
2673 // user CFG lang for user if $newuser->lang is empty
2674 // or $user->lang is not an installed language
2675 $sitelangs = array_keys(get_list_of_languages());
2676 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2677 $newuser -> lang = $CFG->lang;
2679 $newuser->confirmed = 1;
2680 $newuser->lastip = getremoteaddr();
2681 $newuser->timemodified = time();
2682 $newuser->mnethostid = $CFG->mnet_localhost_id;
2684 if (insert_record('user', $newuser)) {
2685 $user = get_complete_user_data('username', $newuser->username);
2686 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
2687 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2689 update_internal_user_password($user, $password);
2690 return $user;
2692 return false;
2696 * Will update a local user record from an external source
2698 * @uses $CFG
2699 * @param string $username New user's username to add to record
2700 * @return user A {@link $USER} object
2702 function update_user_record($username, $authplugin) {
2703 $username = trim(moodle_strtolower($username)); /// just in case check text case
2705 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2706 $userauth = get_auth_plugin($oldinfo->auth);
2708 if ($newinfo = $userauth->get_userinfo($username)) {
2709 $newinfo = truncate_userinfo($newinfo);
2710 foreach ($newinfo as $key => $value){
2711 $confkey = 'field_updatelocal_' . $key;
2712 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2713 $value = addslashes(stripslashes($value)); // Just in case
2714 set_field('user', $key, $value, 'username', $username)
2715 or error_log("Error updating $key for $username");
2720 return get_complete_user_data('username', $username);
2723 function truncate_userinfo($info) {
2724 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2725 /// which may have large fields
2727 // define the limits
2728 $limit = array(
2729 'username' => 100,
2730 'idnumber' => 64,
2731 'firstname' => 100,
2732 'lastname' => 100,
2733 'email' => 100,
2734 'icq' => 15,
2735 'phone1' => 20,
2736 'phone2' => 20,
2737 'institution' => 40,
2738 'department' => 30,
2739 'address' => 70,
2740 'city' => 20,
2741 'country' => 2,
2742 'url' => 255,
2745 // apply where needed
2746 foreach (array_keys($info) as $key) {
2747 if (!empty($limit[$key])) {
2748 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2752 return $info;
2756 * Marks user deleted in internal user database and notifies the auth plugin.
2757 * Also unenrols user from all roles and does other cleanup.
2758 * @param object $user Userobject before delete (without system magic quotes)
2759 * @return boolean success
2761 function delete_user($user) {
2762 global $CFG;
2763 require_once($CFG->libdir.'/grouplib.php');
2765 begin_sql();
2767 // delete all grades - backup is kept in grade_grades_history table
2768 if ($grades = grade_grade::fetch_all(array('userid'=>$user->id))) {
2769 foreach ($grades as $grade) {
2770 $grade->delete('userdelete');
2774 // remove from all groups
2775 delete_records('groups_members', 'userid', $user->id);
2777 // unenrol from all roles in all contexts
2778 role_unassign(0, $user->id); // this might be slow but it is really needed - modules might do some extra cleanup!
2780 // now do a final accesslib cleanup - removes all role assingments in user context and context itself
2781 delete_context(CONTEXT_USER, $user->id);
2783 // mark internal user record as "deleted"
2784 $updateuser = new object();
2785 $updateuser->id = $user->id;
2786 $updateuser->deleted = 1;
2787 $updateuser->username = addslashes("$user->email.".time()); // Remember it just in case
2788 $updateuser->email = ''; // Clear this field to free it up
2789 $updateuser->idnumber = ''; // Clear this field to free it up
2790 $updateuser->timemodified = time();
2792 if (update_record('user', $updateuser)) {
2793 commit_sql();
2794 // notify auth plugin - do not block the delete even when plugin fails
2795 $authplugin = get_auth_plugin($user->auth);
2796 $authplugin->user_delete($user);
2797 return true;
2799 } else {
2800 rollback_sql();
2801 return false;
2806 * Retrieve the guest user object
2808 * @uses $CFG
2809 * @return user A {@link $USER} object
2811 function guest_user() {
2812 global $CFG;
2814 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
2815 $newuser->confirmed = 1;
2816 $newuser->lang = $CFG->lang;
2817 $newuser->lastip = getremoteaddr();
2820 return $newuser;
2824 * Given a username and password, this function looks them
2825 * up using the currently selected authentication mechanism,
2826 * and if the authentication is successful, it returns a
2827 * valid $user object from the 'user' table.
2829 * Uses auth_ functions from the currently active auth module
2831 * @uses $CFG
2832 * @param string $username User's username (with system magic quotes)
2833 * @param string $password User's password (with system magic quotes)
2834 * @return user|flase A {@link $USER} object or false if error
2836 function authenticate_user_login($username, $password) {
2838 global $CFG;
2840 $authsenabled = get_enabled_auth_plugins();
2842 if ($user = get_complete_user_data('username', $username)) {
2843 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
2844 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2845 add_to_log(0, 'login', 'error', 'index.php', $username);
2846 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2847 return false;
2849 if (!empty($user->deleted)) {
2850 add_to_log(0, 'login', 'error', 'index.php', $username);
2851 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2852 return false;
2854 $auths = array($auth);
2856 } else {
2857 $auths = $authsenabled;
2858 $user = new object();
2859 $user->id = 0; // User does not exist
2862 foreach ($auths as $auth) {
2863 $authplugin = get_auth_plugin($auth);
2865 // on auth fail fall through to the next plugin
2866 if (!$authplugin->user_login($username, $password)) {
2867 continue;
2870 // successful authentication
2871 if ($user->id) { // User already exists in database
2872 if (empty($user->auth)) { // For some reason auth isn't set yet
2873 set_field('user', 'auth', $auth, 'username', $username);
2874 $user->auth = $auth;
2877 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2879 if (!$authplugin->is_internal()) { // update user record from external DB
2880 $user = update_user_record($username, get_auth_plugin($user->auth));
2882 } else {
2883 // if user not found, create him
2884 $user = create_user_record($username, $password, $auth);
2887 $authplugin->sync_roles($user);
2889 foreach ($authsenabled as $hau) {
2890 $hauth = get_auth_plugin($hau);
2891 $hauth->user_authenticated_hook($user, $username, $password);
2894 /// Log in to a second system if necessary
2895 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2896 if (!empty($CFG->sso)) {
2897 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2898 if (function_exists('sso_user_login')) {
2899 if (!sso_user_login($username, $password)) { // Perform the signon process
2900 notify('Second sign-on failed');
2905 return $user;
2909 // failed if all the plugins have failed
2910 add_to_log(0, 'login', 'error', 'index.php', $username);
2911 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2912 return false;
2916 * Compare password against hash stored in internal user table.
2917 * If necessary it also updates the stored hash to new format.
2919 * @param object user
2920 * @param string plain text password
2921 * @return bool is password valid?
2923 function validate_internal_user_password(&$user, $password) {
2924 global $CFG;
2926 if (!isset($CFG->passwordsaltmain)) {
2927 $CFG->passwordsaltmain = '';
2930 $validated = false;
2932 // get password original encoding in case it was not updated to unicode yet
2933 $textlib = textlib_get_instance();
2934 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2936 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2937 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
2938 $validated = true;
2939 } else {
2940 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
2941 $alt = 'passwordsaltalt'.$i;
2942 if (!empty($CFG->$alt)) {
2943 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2944 $validated = true;
2945 break;
2951 if ($validated) {
2952 // force update of password hash using latest main password salt and encoding if needed
2953 update_internal_user_password($user, $password);
2956 return $validated;
2960 * Calculate hashed value from password using current hash mechanism.
2962 * @param string password
2963 * @return string password hash
2965 function hash_internal_user_password($password) {
2966 global $CFG;
2968 if (isset($CFG->passwordsaltmain)) {
2969 return md5($password.$CFG->passwordsaltmain);
2970 } else {
2971 return md5($password);
2976 * Update pssword hash in user object.
2978 * @param object user
2979 * @param string plain text password
2980 * @param bool store changes also in db, default true
2981 * @return true if hash changed
2983 function update_internal_user_password(&$user, $password) {
2984 global $CFG;
2986 $authplugin = get_auth_plugin($user->auth);
2987 if (!empty($authplugin->config->preventpassindb)) {
2988 $hashedpassword = 'not cached';
2989 } else {
2990 $hashedpassword = hash_internal_user_password($password);
2993 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
2997 * Get a complete user record, which includes all the info
2998 * in the user record
2999 * Intended for setting as $USER session variable
3001 * @uses $CFG
3002 * @uses SITEID
3003 * @param string $field The user field to be checked for a given value.
3004 * @param string $value The value to match for $field.
3005 * @return user A {@link $USER} object.
3007 function get_complete_user_data($field, $value, $mnethostid=null) {
3009 global $CFG;
3011 if (!$field || !$value) {
3012 return false;
3015 /// Build the WHERE clause for an SQL query
3017 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
3019 if (is_null($mnethostid)) {
3020 // if null, we restrict to local users
3021 // ** testing for local user can be done with
3022 // mnethostid = $CFG->mnet_localhost_id
3023 // or with
3024 // auth != 'mnet'
3025 // but the first one is FAST with our indexes
3026 $mnethostid = $CFG->mnet_localhost_id;
3028 $mnethostid = (int)$mnethostid;
3029 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
3031 /// Get all the basic user data
3033 if (! $user = get_record_select('user', $constraints)) {
3034 return false;
3037 /// Get various settings and preferences
3039 if ($displays = get_records('course_display', 'userid', $user->id)) {
3040 foreach ($displays as $display) {
3041 $user->display[$display->course] = $display->display;
3045 $user->preference = get_user_preferences(null, null, $user->id);
3047 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
3048 foreach ($lastaccesses as $lastaccess) {
3049 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
3053 $sql = "SELECT g.id, g.courseid
3054 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
3055 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
3057 // this is a special hack to speedup calendar display
3058 $user->groupmember = array();
3059 if ($groups = get_records_sql($sql)) {
3060 foreach ($groups as $group) {
3061 if (!array_key_exists($group->courseid, $user->groupmember)) {
3062 $user->groupmember[$group->courseid] = array();
3064 $user->groupmember[$group->courseid][$group->id] = $group->id;
3068 /// Rewrite some variables if necessary
3069 if (!empty($user->description)) {
3070 $user->description = true; // No need to cart all of it around
3072 if ($user->username == 'guest') {
3073 $user->lang = $CFG->lang; // Guest language always same as site
3074 $user->firstname = get_string('guestuser'); // Name always in current language
3075 $user->lastname = ' ';
3078 $user->sesskey = random_string(10);
3079 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
3081 return $user;
3085 * @uses $CFG
3086 * @param string $password the password to be checked agains the password policy
3087 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
3088 * @return bool true if the password is valid according to the policy. false otherwise.
3090 function check_password_policy($password, &$errmsg) {
3091 global $CFG;
3093 if (empty($CFG->passwordpolicy)) {
3094 return true;
3097 $textlib = textlib_get_instance();
3098 $errmsg = '';
3099 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
3100 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
3102 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
3103 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
3105 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
3106 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
3108 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
3109 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
3111 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
3112 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
3114 } else if ($password == 'admin' or $password == 'password') {
3115 $errmsg = get_string('unsafepassword');
3118 if ($errmsg == '') {
3119 return true;
3120 } else {
3121 return false;
3127 * When logging in, this function is run to set certain preferences
3128 * for the current SESSION
3130 function set_login_session_preferences() {
3131 global $SESSION, $CFG;
3133 $SESSION->justloggedin = true;
3135 unset($SESSION->lang);
3137 // Restore the calendar filters, if saved
3138 if (intval(get_user_preferences('calendar_persistflt', 0))) {
3139 include_once($CFG->dirroot.'/calendar/lib.php');
3140 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
3146 * Delete a course, including all related data from the database,
3147 * and any associated files from the moodledata folder.
3149 * @param int $courseid The id of the course to delete.
3150 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3151 * @return bool true if all the removals succeeded. false if there were any failures. If this
3152 * method returns false, some of the removals will probably have succeeded, and others
3153 * failed, but you have no way of knowing which.
3155 function delete_course($courseid, $showfeedback = true) {
3156 global $CFG;
3157 require_once($CFG->libdir.'/gradelib.php');
3158 $result = true;
3160 if (!remove_course_contents($courseid, $showfeedback)) {
3161 if ($showfeedback) {
3162 notify("An error occurred while deleting some of the course contents.");
3164 $result = false;
3167 remove_course_grades($courseid, $showfeedback);
3169 if (!delete_records("course", "id", $courseid)) {
3170 if ($showfeedback) {
3171 notify("An error occurred while deleting the main course record.");
3173 $result = false;
3176 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE, 'instanceid', $courseid)) {
3177 if ($showfeedback) {
3178 notify("An error occurred while deleting the main context record.");
3180 $result = false;
3183 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
3184 if ($showfeedback) {
3185 notify("An error occurred while deleting the course files.");
3187 $result = false;
3190 return $result;
3194 * Clear a course out completely, deleting all content
3195 * but don't delete the course itself
3197 * @uses $CFG
3198 * @param int $courseid The id of the course that is being deleted
3199 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3200 * @return bool true if all the removals succeeded. false if there were any failures. If this
3201 * method returns false, some of the removals will probably have succeeded, and others
3202 * failed, but you have no way of knowing which.
3204 function remove_course_contents($courseid, $showfeedback=true) {
3206 global $CFG;
3207 include_once($CFG->libdir.'/questionlib.php');
3209 $result = true;
3211 if (! $course = get_record('course', 'id', $courseid)) {
3212 error('Course ID was incorrect (can\'t find it)');
3215 $strdeleted = get_string('deleted');
3217 /// First delete every instance of every module
3219 if ($allmods = get_records('modules') ) {
3220 foreach ($allmods as $mod) {
3221 $modname = $mod->name;
3222 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3223 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3224 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3225 $count=0;
3226 if (file_exists($modfile)) {
3227 include_once($modfile);
3228 if (function_exists($moddelete)) {
3229 if ($instances = get_records($modname, 'course', $course->id)) {
3230 foreach ($instances as $instance) {
3231 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
3232 /// Delete activity context questions and question categories
3233 question_delete_activity($cm, $showfeedback);
3234 delete_context(CONTEXT_MODULE, $cm->id);
3236 if ($moddelete($instance->id)) {
3237 $count++;
3239 } else {
3240 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
3241 $result = false;
3245 } else {
3246 notify('Function '. $moddelete() .'doesn\'t exist!');
3247 $result = false;
3250 if (function_exists($moddeletecourse)) {
3251 $moddeletecourse($course, $showfeedback);
3254 if ($showfeedback) {
3255 notify($strdeleted .' '. $count .' x '. $modname);
3258 } else {
3259 error('No modules are installed!');
3262 /// Give local code a chance to delete its references to this course.
3263 require_once('locallib.php');
3264 notify_local_delete_course($courseid, $showfeedback);
3266 /// Delete course blocks
3268 if ($blocks = get_records_sql("SELECT *
3269 FROM {$CFG->prefix}block_instance
3270 WHERE pagetype = '".PAGE_COURSE_VIEW."'
3271 AND pageid = $course->id")) {
3272 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
3273 if ($showfeedback) {
3274 notify($strdeleted .' block_instance');
3277 require_once($CFG->libdir.'/blocklib.php');
3278 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3280 // Block instances are rarely created. Since the block instance is gone from the above delete
3281 // statement, calling delete_context() will generate a warning as get_context_instance could
3282 // no longer create the context as the block is already gone.
3283 if (record_exists('context', 'contextlevel', CONTEXT_BLOCK, 'instanceid', $block->id)) {
3284 delete_context(CONTEXT_BLOCK, $block->id);
3287 // fix for MDL-7164
3288 // Get the block object and call instance_delete()
3289 if (!$record = blocks_get_record($block->blockid)) {
3290 $result = false;
3291 continue;
3293 if (!$obj = block_instance($record->name, $block)) {
3294 $result = false;
3295 continue;
3297 // Return value ignored, in core mods this does not do anything, but just in case
3298 // third party blocks might have stuff to clean up
3299 // we execute this anyway
3300 $obj->instance_delete();
3302 } else {
3303 $result = false;
3307 /// Delete any groups, removing members and grouping/course links first.
3308 require_once($CFG->dirroot.'/group/lib.php');
3309 groups_delete_groupings($courseid, true);
3310 groups_delete_groups($courseid, true);
3312 /// Delete all related records in other tables that may have a courseid
3313 /// This array stores the tables that need to be cleared, as
3314 /// table_name => column_name that contains the course id.
3316 $tablestoclear = array(
3317 'event' => 'courseid', // Delete events
3318 'log' => 'course', // Delete logs
3319 'course_sections' => 'course', // Delete any course stuff
3320 'course_modules' => 'course',
3321 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3322 'backup_log' => 'courseid'
3324 foreach ($tablestoclear as $table => $col) {
3325 if (delete_records($table, $col, $course->id)) {
3326 if ($showfeedback) {
3327 notify($strdeleted . ' ' . $table);
3329 } else {
3330 $result = false;
3335 /// Clean up metacourse stuff
3337 if ($course->metacourse) {
3338 delete_records("course_meta","parent_course",$course->id);
3339 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3340 if ($showfeedback) {
3341 notify("$strdeleted course_meta");
3343 } else {
3344 if ($parents = get_records("course_meta","child_course",$course->id)) {
3345 foreach ($parents as $parent) {
3346 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3348 if ($showfeedback) {
3349 notify("$strdeleted course_meta");
3354 /// Delete questions and question categories
3355 question_delete_course($course, $showfeedback);
3357 /// Delete all roles and overiddes in the course context (but keep the course context)
3358 if ($courseid != SITEID) {
3359 delete_context(CONTEXT_COURSE, $course->id);
3362 return $result;
3367 * This function will empty a course of USER data as much as
3368 /// possible. It will retain the activities and the structure
3369 /// of the course.
3371 * @uses $USER
3372 * @uses $SESSION
3373 * @uses $CFG
3374 * @param object $data an object containing all the boolean settings and courseid
3375 * @param bool $showfeedback if false then do it all silently
3376 * @return bool
3377 * @todo Finish documenting this function
3379 function reset_course_userdata($data, $showfeedback=true) {
3381 global $CFG, $USER, $SESSION;
3382 require_once($CFG->dirroot.'/group/lib.php');
3384 $result = true;
3386 $strdeleted = get_string('deleted');
3388 // Look in every instance of every module for data to delete
3390 if ($allmods = get_records('modules') ) {
3391 foreach ($allmods as $mod) {
3392 $modname = $mod->name;
3393 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3394 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3395 if (file_exists($modfile)) {
3396 @include_once($modfile);
3397 if (function_exists($moddeleteuserdata)) {
3398 $moddeleteuserdata($data, $showfeedback);
3402 } else {
3403 error('No modules are installed!');
3406 // Delete other stuff
3407 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
3409 if (!empty($data->reset_students) or !empty($data->reset_teachers)) {
3410 $teachers = array_keys(get_users_by_capability($context, 'moodle/course:update'));
3411 $participants = array_keys(get_users_by_capability($context, 'moodle/course:view'));
3412 $students = array_diff($participants, $teachers);
3414 if (!empty($data->reset_students)) {
3415 foreach ($students as $studentid) {
3416 role_unassign(0, $studentid, 0, $context->id);
3418 if ($showfeedback) {
3419 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3422 /// Delete group members (but keep the groups)
3423 $result = groups_delete_group_members($data->courseid, $showfeedback) && $result;
3426 if (!empty($data->reset_teachers)) {
3427 foreach ($teachers as $teacherid) {
3428 role_unassign(0, $teacherid, 0, $context->id);
3430 if ($showfeedback) {
3431 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3436 if (!empty($data->reset_groups)) {
3437 $result = groups_delete_groupings($data->courseid, $showfeedback) && $result;
3438 $result = groups_delete_groups($data->courseid, $showfeedback) && $result;
3441 if (!empty($data->reset_events)) {
3442 if (delete_records('event', 'courseid', $data->courseid)) {
3443 if ($showfeedback) {
3444 notify($strdeleted .' event', 'notifysuccess');
3446 } else {
3447 $result = false;
3451 if (!empty($data->reset_logs)) {
3452 if (delete_records('log', 'course', $data->courseid)) {
3453 if ($showfeedback) {
3454 notify($strdeleted .' log', 'notifysuccess');
3456 } else {
3457 $result = false;
3461 // deletes all role assignments, and local override,
3462 // these have no courseid in table and needs separate process
3463 delete_records('role_capabilities', 'contextid', $context->id);
3465 // force accessinfo refresh for users visiting this context...
3466 mark_context_dirty($context->path);
3468 return $result;
3471 function generate_email_processing_address($modid,$modargs) {
3472 global $CFG;
3474 if (empty($CFG->siteidentifier)) { // Unique site identification code
3475 set_config('siteidentifier', random_string(32));
3478 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3479 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
3483 function moodle_process_email($modargs,$body) {
3484 // the first char should be an unencoded letter. We'll take this as an action
3485 switch ($modargs{0}) {
3486 case 'B': { // bounce
3487 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3488 if ($user = get_record_select("user","id=$userid","id,email")) {
3489 // check the half md5 of their email
3490 $md5check = substr(md5($user->email),0,16);
3491 if ($md5check == substr($modargs, -16)) {
3492 set_bounce_count($user);
3494 // else maybe they've already changed it?
3497 break;
3498 // maybe more later?
3502 /// CORRESPONDENCE ////////////////////////////////////////////////
3505 * Send an email to a specified user
3507 * @uses $CFG
3508 * @uses $FULLME
3509 * @uses SITEID
3510 * @param user $user A {@link $USER} object
3511 * @param user $from A {@link $USER} object
3512 * @param string $subject plain text subject line of the email
3513 * @param string $messagetext plain text version of the message
3514 * @param string $messagehtml complete html version of the message (optional)
3515 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3516 * @param string $attachname the name of the file (extension indicates MIME)
3517 * @param bool $usetrueaddress determines whether $from email address should
3518 * be sent out. Will be overruled by user profile setting for maildisplay
3519 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3520 * was blocked by user and "false" if there was another sort of error.
3522 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3524 global $CFG, $FULLME;
3526 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
3528 /// We are going to use textlib services here
3529 $textlib = textlib_get_instance();
3531 if (empty($user)) {
3532 return false;
3535 // skip mail to suspended users
3536 if (isset($user->auth) && $user->auth=='nologin') {
3537 return true;
3540 if (!empty($user->emailstop)) {
3541 return 'emailstop';
3544 if (over_bounce_threshold($user)) {
3545 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3546 return false;
3549 $mail = new phpmailer;
3551 $mail->Version = 'Moodle '. $CFG->version; // mailer version
3552 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
3554 $mail->CharSet = 'UTF-8';
3556 if ($CFG->smtphosts == 'qmail') {
3557 $mail->IsQmail(); // use Qmail system
3559 } else if (empty($CFG->smtphosts)) {
3560 $mail->IsMail(); // use PHP mail() = sendmail
3562 } else {
3563 $mail->IsSMTP(); // use SMTP directly
3564 if (!empty($CFG->debugsmtp)) {
3565 echo '<pre>' . "\n";
3566 $mail->SMTPDebug = true;
3568 $mail->Host = $CFG->smtphosts; // specify main and backup servers
3570 if ($CFG->smtpuser) { // Use SMTP authentication
3571 $mail->SMTPAuth = true;
3572 $mail->Username = $CFG->smtpuser;
3573 $mail->Password = $CFG->smtppass;
3577 $supportuser = generate_email_supportuser();
3580 // make up an email address for handling bounces
3581 if (!empty($CFG->handlebounces)) {
3582 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
3583 $mail->Sender = generate_email_processing_address(0,$modargs);
3584 } else {
3585 $mail->Sender = $supportuser->email;
3588 if (is_string($from)) { // So we can pass whatever we want if there is need
3589 $mail->From = $CFG->noreplyaddress;
3590 $mail->FromName = $from;
3591 } else if ($usetrueaddress and $from->maildisplay) {
3592 $mail->From = $from->email;
3593 $mail->FromName = fullname($from);
3594 } else {
3595 $mail->From = $CFG->noreplyaddress;
3596 $mail->FromName = fullname($from);
3597 if (empty($replyto)) {
3598 $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
3602 if (!empty($replyto)) {
3603 $mail->AddReplyTo($replyto,$replytoname);
3606 $mail->Subject = substr(stripslashes($subject), 0, 900);
3608 $mail->AddAddress($user->email, fullname($user) );
3610 $mail->WordWrap = 79; // set word wrap
3612 if (!empty($from->customheaders)) { // Add custom headers
3613 if (is_array($from->customheaders)) {
3614 foreach ($from->customheaders as $customheader) {
3615 $mail->AddCustomHeader($customheader);
3617 } else {
3618 $mail->AddCustomHeader($from->customheaders);
3622 if (!empty($from->priority)) {
3623 $mail->Priority = $from->priority;
3626 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
3627 $mail->IsHTML(true);
3628 $mail->Encoding = 'quoted-printable'; // Encoding to use
3629 $mail->Body = $messagehtml;
3630 $mail->AltBody = "\n$messagetext\n";
3631 } else {
3632 $mail->IsHTML(false);
3633 $mail->Body = "\n$messagetext\n";
3636 if ($attachment && $attachname) {
3637 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3638 $mail->AddAddress($supportuser->email, fullname($supportuser, true) );
3639 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3640 } else {
3641 require_once($CFG->libdir.'/filelib.php');
3642 $mimetype = mimeinfo('type', $attachname);
3643 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
3649 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3650 /// encoding to the specified one
3651 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
3652 /// Set it to site mail charset
3653 $charset = $CFG->sitemailcharset;
3654 /// Overwrite it with the user mail charset
3655 if (!empty($CFG->allowusermailcharset)) {
3656 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
3657 $charset = $useremailcharset;
3660 /// If it has changed, convert all the necessary strings
3661 $charsets = get_list_of_charsets();
3662 unset($charsets['UTF-8']);
3663 if (in_array($charset, $charsets)) {
3664 /// Save the new mail charset
3665 $mail->CharSet = $charset;
3666 /// And convert some strings
3667 $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
3668 foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names
3669 $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet);
3671 $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject
3672 foreach ($mail->to as $key => $to) {
3673 $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet); //To Names
3675 $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body
3676 $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject
3680 if ($mail->Send()) {
3681 set_send_count($user);
3682 $mail->IsSMTP(); // use SMTP directly
3683 if (!empty($CFG->debugsmtp)) {
3684 echo '</pre>';
3686 return true;
3687 } else {
3688 mtrace('ERROR: '. $mail->ErrorInfo);
3689 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
3690 if (!empty($CFG->debugsmtp)) {
3691 echo '</pre>';
3693 return false;
3698 * Generate a signoff for emails based on support settings
3701 function generate_email_signoff() {
3702 global $CFG;
3704 $signoff = "\n";
3705 if (!empty($CFG->supportname)) {
3706 $signoff .= $CFG->supportname."\n";
3708 if (!empty($CFG->supportemail)) {
3709 $signoff .= $CFG->supportemail."\n";
3711 if (!empty($CFG->supportpage)) {
3712 $signoff .= $CFG->supportpage."\n";
3714 return $signoff;
3718 * Generate a fake user for emails based on support settings
3721 function generate_email_supportuser() {
3723 global $CFG;
3725 static $supportuser;
3727 if (!empty($supportuser)) {
3728 return $supportuser;
3731 $supportuser = new object;
3732 $supportuser->email = $CFG->supportemail ? $CFG->supportemail : $CFG->noreplyaddress;
3733 $supportuser->firstname = $CFG->supportname ? $CFG->supportname : get_string('noreplyname');
3734 $supportuser->lastname = '';
3735 $supportuser->maildisplay = true;
3737 return $supportuser;
3742 * Sets specified user's password and send the new password to the user via email.
3744 * @uses $CFG
3745 * @param user $user A {@link $USER} object
3746 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3747 * was blocked by user and "false" if there was another sort of error.
3749 function setnew_password_and_mail($user) {
3751 global $CFG;
3753 $site = get_site();
3755 $supportuser = generate_email_supportuser();
3757 $newpassword = generate_password();
3759 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
3760 trigger_error('Could not set user password!');
3761 return false;
3764 $a = new object();
3765 $a->firstname = fullname($user, true);
3766 $a->sitename = format_string($site->fullname);
3767 $a->username = $user->username;
3768 $a->newpassword = $newpassword;
3769 $a->link = $CFG->wwwroot .'/login/';
3770 $a->signoff = generate_email_signoff();
3772 $message = get_string('newusernewpasswordtext', '', $a);
3774 $subject = format_string($site->fullname) .': '. get_string('newusernewpasswordsubj');
3776 return email_to_user($user, $supportuser, $subject, $message);
3781 * Resets specified user's password and send the new password to the user via email.
3783 * @uses $CFG
3784 * @param user $user A {@link $USER} object
3785 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3786 * was blocked by user and "false" if there was another sort of error.
3788 function reset_password_and_mail($user) {
3790 global $CFG;
3792 $site = get_site();
3793 $supportuser = generate_email_supportuser();
3795 $userauth = get_auth_plugin($user->auth);
3796 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
3797 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3798 return false;
3801 $newpassword = generate_password();
3803 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3804 error("Could not set user password!");
3807 $a = new object();
3808 $a->firstname = $user->firstname;
3809 $a->sitename = format_string($site->fullname);
3810 $a->username = $user->username;
3811 $a->newpassword = $newpassword;
3812 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
3813 $a->signoff = generate_email_signoff();
3815 $message = get_string('newpasswordtext', '', $a);
3817 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
3819 return email_to_user($user, $supportuser, $subject, $message);
3824 * Send email to specified user with confirmation text and activation link.
3826 * @uses $CFG
3827 * @param user $user A {@link $USER} object
3828 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3829 * was blocked by user and "false" if there was another sort of error.
3831 function send_confirmation_email($user) {
3833 global $CFG;
3835 $site = get_site();
3836 $supportuser = generate_email_supportuser();
3838 $data = new object();
3839 $data->firstname = fullname($user);
3840 $data->sitename = format_string($site->fullname);
3841 $data->admin = generate_email_signoff();
3843 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
3845 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. urlencode($user->username);
3846 $message = get_string('emailconfirmation', '', $data);
3847 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3849 $user->mailformat = 1; // Always send HTML version as well
3851 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
3856 * send_password_change_confirmation_email.
3858 * @uses $CFG
3859 * @param user $user A {@link $USER} object
3860 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3861 * was blocked by user and "false" if there was another sort of error.
3863 function send_password_change_confirmation_email($user) {
3865 global $CFG;
3867 $site = get_site();
3868 $supportuser = generate_email_supportuser();
3870 $data = new object();
3871 $data->firstname = $user->firstname;
3872 $data->sitename = format_string($site->fullname);
3873 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
3874 $data->admin = generate_email_signoff();
3876 $message = get_string('emailpasswordconfirmation', '', $data);
3877 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
3879 return email_to_user($user, $supportuser, $subject, $message);
3884 * send_password_change_info.
3886 * @uses $CFG
3887 * @param user $user A {@link $USER} object
3888 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3889 * was blocked by user and "false" if there was another sort of error.
3891 function send_password_change_info($user) {
3893 global $CFG;
3895 $site = get_site();
3896 $supportuser = generate_email_supportuser();
3897 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
3899 $data = new object();
3900 $data->firstname = $user->firstname;
3901 $data->sitename = format_string($site->fullname);
3902 $data->admin = generate_email_signoff();
3904 $userauth = get_auth_plugin($user->auth);
3906 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
3907 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
3908 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3909 return email_to_user($user, $supportuser, $subject, $message);
3912 if ($userauth->can_change_password() and $userauth->change_password_url()) {
3913 // we have some external url for password changing
3914 $data->link .= $userauth->change_password_url();
3916 } else {
3917 //no way to change password, sorry
3918 $data->link = '';
3921 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
3922 $message = get_string('emailpasswordchangeinfo', '', $data);
3923 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3924 } else {
3925 $message = get_string('emailpasswordchangeinfofail', '', $data);
3926 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3929 return email_to_user($user, $supportuser, $subject, $message);
3934 * Check that an email is allowed. It returns an error message if there
3935 * was a problem.
3937 * @uses $CFG
3938 * @param string $email Content of email
3939 * @return string|false
3941 function email_is_not_allowed($email) {
3943 global $CFG;
3945 if (!empty($CFG->allowemailaddresses)) {
3946 $allowed = explode(' ', $CFG->allowemailaddresses);
3947 foreach ($allowed as $allowedpattern) {
3948 $allowedpattern = trim($allowedpattern);
3949 if (!$allowedpattern) {
3950 continue;
3952 if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
3953 return false;
3956 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
3958 } else if (!empty($CFG->denyemailaddresses)) {
3959 $denied = explode(' ', $CFG->denyemailaddresses);
3960 foreach ($denied as $deniedpattern) {
3961 $deniedpattern = trim($deniedpattern);
3962 if (!$deniedpattern) {
3963 continue;
3965 if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
3966 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
3971 return false;
3974 function email_welcome_message_to_user($course, $user=NULL) {
3975 global $CFG, $USER;
3977 if (empty($user)) {
3978 if (!isloggedin()) {
3979 return false;
3981 $user = $USER;
3984 if (!empty($course->welcomemessage)) {
3985 $subject = get_string('welcometocourse', '', format_string($course->fullname));
3987 $a->coursename = $course->fullname;
3988 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3989 //$message = get_string("welcometocoursetext", "", $a);
3990 $message = $course->welcomemessage;
3992 if (! $teacher = get_teacher($course->id)) {
3993 $teacher = get_admin();
3995 email_to_user($user, $teacher, $subject, $message);
3999 /// FILE HANDLING /////////////////////////////////////////////
4003 * Makes an upload directory for a particular module.
4005 * @uses $CFG
4006 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
4007 * @return string|false Returns full path to directory if successful, false if not
4009 function make_mod_upload_directory($courseid) {
4010 global $CFG;
4012 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
4013 return false;
4016 $strreadme = get_string('readme');
4018 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
4019 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4020 } else {
4021 copy($CFG->dirroot .'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
4023 return $moddata;
4027 * Returns current name of file on disk if it exists.
4029 * @param string $newfile File to be verified
4030 * @return string Current name of file on disk if true
4032 function valid_uploaded_file($newfile) {
4033 if (empty($newfile)) {
4034 return '';
4036 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
4037 return $newfile['tmp_name'];
4038 } else {
4039 return '';
4044 * Returns the maximum size for uploading files.
4046 * There are seven possible upload limits:
4047 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
4048 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
4049 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
4050 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
4051 * 5. by the Moodle admin in $CFG->maxbytes
4052 * 6. by the teacher in the current course $course->maxbytes
4053 * 7. by the teacher for the current module, eg $assignment->maxbytes
4055 * These last two are passed to this function as arguments (in bytes).
4056 * Anything defined as 0 is ignored.
4057 * The smallest of all the non-zero numbers is returned.
4059 * @param int $sizebytes ?
4060 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4061 * @param int $modulebytes Current module ->maxbytes (in bytes)
4062 * @return int The maximum size for uploading files.
4063 * @todo Finish documenting this function
4065 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4067 if (! $filesize = ini_get('upload_max_filesize')) {
4068 $filesize = '5M';
4070 $minimumsize = get_real_size($filesize);
4072 if ($postsize = ini_get('post_max_size')) {
4073 $postsize = get_real_size($postsize);
4074 if ($postsize < $minimumsize) {
4075 $minimumsize = $postsize;
4079 if ($sitebytes and $sitebytes < $minimumsize) {
4080 $minimumsize = $sitebytes;
4083 if ($coursebytes and $coursebytes < $minimumsize) {
4084 $minimumsize = $coursebytes;
4087 if ($modulebytes and $modulebytes < $minimumsize) {
4088 $minimumsize = $modulebytes;
4091 return $minimumsize;
4095 * Related to {@link get_max_upload_file_size()} - this function returns an
4096 * array of possible sizes in an array, translated to the
4097 * local language.
4099 * @uses SORT_NUMERIC
4100 * @param int $sizebytes ?
4101 * @param int $coursebytes Current course $course->maxbytes (in bytes)
4102 * @param int $modulebytes Current module ->maxbytes (in bytes)
4103 * @return int
4104 * @todo Finish documenting this function
4106 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4107 global $CFG;
4109 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
4110 return array();
4113 $filesize[$maxsize] = display_size($maxsize);
4115 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4116 5242880, 10485760, 20971520, 52428800, 104857600);
4118 // Allow maxbytes to be selected if it falls outside the above boundaries
4119 if( isset($CFG->maxbytes) && !in_array($CFG->maxbytes, $sizelist) ){
4120 $sizelist[] = $CFG->maxbytes;
4123 foreach ($sizelist as $sizebytes) {
4124 if ($sizebytes < $maxsize) {
4125 $filesize[$sizebytes] = display_size($sizebytes);
4129 krsort($filesize, SORT_NUMERIC);
4131 return $filesize;
4135 * If there has been an error uploading a file, print the appropriate error message
4136 * Numerical constants used as constant definitions not added until PHP version 4.2.0
4138 * $filearray is a 1-dimensional sub-array of the $_FILES array
4139 * eg $filearray = $_FILES['userfile1']
4140 * If left empty then the first element of the $_FILES array will be used
4142 * @uses $_FILES
4143 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
4144 * @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.
4145 * @return bool|string
4147 function print_file_upload_error($filearray = '', $returnerror = false) {
4149 if ($filearray == '' or !isset($filearray['error'])) {
4151 if (empty($_FILES)) return false;
4153 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
4154 $filearray = array_shift($files); /// use first element of array
4157 switch ($filearray['error']) {
4159 case 0: // UPLOAD_ERR_OK
4160 if ($filearray['size'] > 0) {
4161 $errmessage = get_string('uploadproblem', $filearray['name']);
4162 } else {
4163 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
4165 break;
4167 case 1: // UPLOAD_ERR_INI_SIZE
4168 $errmessage = get_string('uploadserverlimit');
4169 break;
4171 case 2: // UPLOAD_ERR_FORM_SIZE
4172 $errmessage = get_string('uploadformlimit');
4173 break;
4175 case 3: // UPLOAD_ERR_PARTIAL
4176 $errmessage = get_string('uploadpartialfile');
4177 break;
4179 case 4: // UPLOAD_ERR_NO_FILE
4180 $errmessage = get_string('uploadnofilefound');
4181 break;
4183 default:
4184 $errmessage = get_string('uploadproblem', $filearray['name']);
4187 if ($returnerror) {
4188 return $errmessage;
4189 } else {
4190 notify($errmessage);
4191 return true;
4197 * handy function to loop through an array of files and resolve any filename conflicts
4198 * both in the array of filenames and for what is already on disk.
4199 * not really compatible with the similar function in uploadlib.php
4200 * but this could be used for files/index.php for moving files around.
4203 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4204 foreach ($files as $k => $f) {
4205 if (check_potential_filename($destination,$f,$files)) {
4206 $bits = explode('.', $f);
4207 for ($i = 1; true; $i++) {
4208 $try = sprintf($format, $bits[0], $i, $bits[1]);
4209 if (!check_potential_filename($destination,$try,$files)) {
4210 $files[$k] = $try;
4211 break;
4216 return $files;
4220 * @used by resolve_filename_collisions
4222 function check_potential_filename($destination,$filename,$files) {
4223 if (file_exists($destination.'/'.$filename)) {
4224 return true;
4226 if (count(array_keys($files,$filename)) > 1) {
4227 return true;
4229 return false;
4234 * Returns an array with all the filenames in
4235 * all subdirectories, relative to the given rootdir.
4236 * If excludefile is defined, then that file/directory is ignored
4237 * If getdirs is true, then (sub)directories are included in the output
4238 * If getfiles is true, then files are included in the output
4239 * (at least one of these must be true!)
4241 * @param string $rootdir ?
4242 * @param string $excludefile If defined then the specified file/directory is ignored
4243 * @param bool $descend ?
4244 * @param bool $getdirs If true then (sub)directories are included in the output
4245 * @param bool $getfiles If true then files are included in the output
4246 * @return array An array with all the filenames in
4247 * all subdirectories, relative to the given rootdir
4248 * @todo Finish documenting this function. Add examples of $excludefile usage.
4250 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4252 $dirs = array();
4254 if (!$getdirs and !$getfiles) { // Nothing to show
4255 return $dirs;
4258 if (!is_dir($rootdir)) { // Must be a directory
4259 return $dirs;
4262 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4263 return $dirs;
4266 if (!is_array($excludefiles)) {
4267 $excludefiles = array($excludefiles);
4270 while (false !== ($file = readdir($dir))) {
4271 $firstchar = substr($file, 0, 1);
4272 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4273 continue;
4275 $fullfile = $rootdir .'/'. $file;
4276 if (filetype($fullfile) == 'dir') {
4277 if ($getdirs) {
4278 $dirs[] = $file;
4280 if ($descend) {
4281 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4282 foreach ($subdirs as $subdir) {
4283 $dirs[] = $file .'/'. $subdir;
4286 } else if ($getfiles) {
4287 $dirs[] = $file;
4290 closedir($dir);
4292 asort($dirs);
4294 return $dirs;
4299 * Adds up all the files in a directory and works out the size.
4301 * @param string $rootdir ?
4302 * @param string $excludefile ?
4303 * @return array
4304 * @todo Finish documenting this function
4306 function get_directory_size($rootdir, $excludefile='') {
4308 global $CFG;
4310 // do it this way if we can, it's much faster
4311 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
4312 $command = trim($CFG->pathtodu).' -sk --apparent-size '.escapeshellarg($rootdir);
4313 $output = null;
4314 $return = null;
4315 exec($command,$output,$return);
4316 if (is_array($output)) {
4317 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4321 if (!is_dir($rootdir)) { // Must be a directory
4322 return 0;
4325 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
4326 return 0;
4329 $size = 0;
4331 while (false !== ($file = readdir($dir))) {
4332 $firstchar = substr($file, 0, 1);
4333 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4334 continue;
4336 $fullfile = $rootdir .'/'. $file;
4337 if (filetype($fullfile) == 'dir') {
4338 $size += get_directory_size($fullfile, $excludefile);
4339 } else {
4340 $size += filesize($fullfile);
4343 closedir($dir);
4345 return $size;
4349 * Converts bytes into display form
4351 * @param string $size ?
4352 * @return string
4353 * @staticvar string $gb Localized string for size in gigabytes
4354 * @staticvar string $mb Localized string for size in megabytes
4355 * @staticvar string $kb Localized string for size in kilobytes
4356 * @staticvar string $b Localized string for size in bytes
4357 * @todo Finish documenting this function. Verify return type.
4359 function display_size($size) {
4361 static $gb, $mb, $kb, $b;
4363 if (empty($gb)) {
4364 $gb = get_string('sizegb');
4365 $mb = get_string('sizemb');
4366 $kb = get_string('sizekb');
4367 $b = get_string('sizeb');
4370 if ($size >= 1073741824) {
4371 $size = round($size / 1073741824 * 10) / 10 . $gb;
4372 } else if ($size >= 1048576) {
4373 $size = round($size / 1048576 * 10) / 10 . $mb;
4374 } else if ($size >= 1024) {
4375 $size = round($size / 1024 * 10) / 10 . $kb;
4376 } else {
4377 $size = $size .' '. $b;
4379 return $size;
4383 * Cleans a given filename by removing suspicious or troublesome characters
4384 * Only these are allowed: alphanumeric _ - .
4385 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4387 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4388 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4390 * @param string $string file name
4391 * @return string cleaned file name
4393 function clean_filename($string) {
4394 global $CFG;
4395 if (empty($CFG->unicodecleanfilename)) {
4396 $textlib = textlib_get_instance();
4397 $string = $textlib->specialtoascii($string);
4398 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4399 } else {
4400 //clean only ascii range
4401 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4403 $string = preg_replace("/_+/", '_', $string);
4404 $string = preg_replace("/\.\.+/", '.', $string);
4405 return $string;
4409 /// STRING TRANSLATION ////////////////////////////////////////
4412 * Returns the code for the current language
4414 * @uses $CFG
4415 * @param $USER
4416 * @param $SESSION
4417 * @return string
4419 function current_language() {
4420 global $CFG, $USER, $SESSION, $COURSE;
4422 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
4423 $return = $COURSE->lang;
4425 } else if (!empty($SESSION->lang)) { // Session language can override other settings
4426 $return = $SESSION->lang;
4428 } else if (!empty($USER->lang)) {
4429 $return = $USER->lang;
4431 } else {
4432 $return = $CFG->lang;
4435 if ($return == 'en') {
4436 $return = 'en_utf8';
4439 return $return;
4443 * Prints out a translated string.
4445 * Prints out a translated string using the return value from the {@link get_string()} function.
4447 * Example usage of this function when the string is in the moodle.php file:<br/>
4448 * <code>
4449 * echo '<strong>';
4450 * print_string('wordforstudent');
4451 * echo '</strong>';
4452 * </code>
4454 * Example usage of this function when the string is not in the moodle.php file:<br/>
4455 * <code>
4456 * echo '<h1>';
4457 * print_string('typecourse', 'calendar');
4458 * echo '</h1>';
4459 * </code>
4461 * @param string $identifier The key identifier for the localized string
4462 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4463 * @param mixed $a An object, string or number that can be used
4464 * within translation strings
4466 function print_string($identifier, $module='', $a=NULL) {
4467 echo get_string($identifier, $module, $a);
4471 * fix up the optional data in get_string()/print_string() etc
4472 * ensure possible sprintf() format characters are escaped correctly
4473 * needs to handle arbitrary strings and objects
4474 * @param mixed $a An object, string or number that can be used
4475 * @return mixed the supplied parameter 'cleaned'
4477 function clean_getstring_data( $a ) {
4478 if (is_string($a)) {
4479 return str_replace( '%','%%',$a );
4481 elseif (is_object($a)) {
4482 $a_vars = get_object_vars( $a );
4483 $new_a_vars = array();
4484 foreach ($a_vars as $fname => $a_var) {
4485 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4487 return (object)$new_a_vars;
4489 else {
4490 return $a;
4495 * @return array places to look for lang strings based on the prefix to the
4496 * module name. For example qtype_ in question/type. Used by get_string and
4497 * help.php.
4499 function places_to_search_for_lang_strings() {
4500 global $CFG;
4502 return array(
4503 '__exceptions' => array('moodle', 'langconfig'),
4504 'assignment_' => array('mod/assignment/type'),
4505 'auth_' => array('auth'),
4506 'block_' => array('blocks'),
4507 'datafield_' => array('mod/data/field'),
4508 'datapreset_' => array('mod/data/preset'),
4509 'enrol_' => array('enrol'),
4510 'format_' => array('course/format'),
4511 'qtype_' => array('question/type'),
4512 'report_' => array($CFG->admin.'/report', 'course/report', 'mod/quiz/report'),
4513 'resource_' => array('mod/resource/type'),
4514 'gradereport_' => array('grade/report'),
4515 'gradeimport_' => array('grade/import'),
4516 'gradeexport_' => array('grade/export'),
4517 '' => array('mod')
4522 * Returns a localized string.
4524 * Returns the translated string specified by $identifier as
4525 * for $module. Uses the same format files as STphp.
4526 * $a is an object, string or number that can be used
4527 * within translation strings
4529 * eg "hello \$a->firstname \$a->lastname"
4530 * or "hello \$a"
4532 * If you would like to directly echo the localized string use
4533 * the function {@link print_string()}
4535 * Example usage of this function involves finding the string you would
4536 * like a local equivalent of and using its identifier and module information
4537 * to retrive it.<br/>
4538 * If you open moodle/lang/en/moodle.php and look near line 1031
4539 * you will find a string to prompt a user for their word for student
4540 * <code>
4541 * $string['wordforstudent'] = 'Your word for Student';
4542 * </code>
4543 * So if you want to display the string 'Your word for student'
4544 * in any language that supports it on your site
4545 * you just need to use the identifier 'wordforstudent'
4546 * <code>
4547 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4549 * </code>
4550 * If the string you want is in another file you'd take a slightly
4551 * different approach. Looking in moodle/lang/en/calendar.php you find
4552 * around line 75:
4553 * <code>
4554 * $string['typecourse'] = 'Course event';
4555 * </code>
4556 * If you want to display the string "Course event" in any language
4557 * supported you would use the identifier 'typecourse' and the module 'calendar'
4558 * (because it is in the file calendar.php):
4559 * <code>
4560 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4561 * </code>
4563 * As a last resort, should the identifier fail to map to a string
4564 * the returned string will be [[ $identifier ]]
4566 * @uses $CFG
4567 * @param string $identifier The key identifier for the localized string
4568 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4569 * @param mixed $a An object, string or number that can be used
4570 * within translation strings
4571 * @param array $extralocations An array of strings with other locations to look for string files
4572 * @return string The localized string.
4574 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4576 global $CFG;
4578 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4579 $langconfigstrs = array('alphabet', 'backupnameformat', 'decsep', 'firstdayofweek', 'listsep', 'locale',
4580 'localewin', 'localewincharset', 'oldcharset',
4581 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4582 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4583 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4584 'thischarset', 'thisdirection', 'thislanguage');
4586 $filetocheck = 'langconfig.php';
4587 $defaultlang = 'en_utf8';
4588 if (in_array($identifier, $langconfigstrs)) {
4589 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4592 $lang = current_language();
4594 if ($module == '') {
4595 $module = 'moodle';
4598 // if $a happens to have % in it, double it so sprintf() doesn't break
4599 if ($a) {
4600 $a = clean_getstring_data( $a );
4603 /// Define the two or three major locations of language strings for this module
4604 $locations = array();
4606 if (!empty($extralocations)) { // Calling code has a good idea where to look
4607 if (is_array($extralocations)) {
4608 $locations += $extralocations;
4609 } else if (is_string($extralocations)) {
4610 $locations[] = $extralocations;
4611 } else {
4612 debugging('Bad lang path provided');
4616 if (isset($CFG->running_installer)) {
4617 $module = 'installer';
4618 $filetocheck = 'installer.php';
4619 $locations[] = $CFG->dirroot.'/install/lang/';
4620 $locations[] = $CFG->dataroot.'/lang/';
4621 $locations[] = $CFG->dirroot.'/lang/';
4622 $defaultlang = 'en_utf8';
4623 } else {
4624 $locations[] = $CFG->dataroot.'/lang/';
4625 $locations[] = $CFG->dirroot.'/lang/';
4628 /// Add extra places to look for strings for particular plugin types.
4629 $rules = places_to_search_for_lang_strings();
4630 $exceptions = $rules['__exceptions'];
4631 unset($rules['__exceptions']);
4633 if (!in_array($module, $exceptions)) {
4634 $dividerpos = strpos($module, '_');
4635 if ($dividerpos === false) {
4636 $type = '';
4637 $plugin = $module;
4638 } else {
4639 $type = substr($module, 0, $dividerpos + 1);
4640 $plugin = substr($module, $dividerpos + 1);
4642 if (!empty($rules[$type])) {
4643 foreach ($rules[$type] as $location) {
4644 $locations[] = $CFG->dirroot . "/$location/$plugin/lang/";
4649 /// First check all the normal locations for the string in the current language
4650 $resultstring = '';
4651 foreach ($locations as $location) {
4652 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4653 if (file_exists($locallangfile)) {
4654 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4655 eval($result);
4656 return $resultstring;
4659 //if local directory not found, or particular string does not exist in local direcotry
4660 $langfile = $location.$lang.'/'.$module.'.php';
4661 if (file_exists($langfile)) {
4662 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4663 eval($result);
4664 return $resultstring;
4669 /// If the preferred language was English (utf8) we can abort now
4670 /// saving some checks beacuse it's the only "root" lang
4671 if ($lang == 'en_utf8') {
4672 return '[['. $identifier .']]';
4675 /// Is a parent language defined? If so, try to find this string in a parent language file
4677 foreach ($locations as $location) {
4678 $langfile = $location.$lang.'/'.$filetocheck;
4679 if (file_exists($langfile)) {
4680 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4681 eval($result);
4682 if (!empty($parentlang)) { // found it!
4684 //first, see if there's a local file for parent
4685 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4686 if (file_exists($locallangfile)) {
4687 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4688 eval($result);
4689 return $resultstring;
4693 //if local directory not found, or particular string does not exist in local direcotry
4694 $langfile = $location.$parentlang.'/'.$module.'.php';
4695 if (file_exists($langfile)) {
4696 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4697 eval($result);
4698 return $resultstring;
4706 /// Our only remaining option is to try English
4708 foreach ($locations as $location) {
4709 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4710 if (file_exists($locallangfile)) {
4711 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4712 eval($result);
4713 return $resultstring;
4717 //if local_en not found, or string not found in local_en
4718 $langfile = $location.$defaultlang.'/'.$module.'.php';
4720 if (file_exists($langfile)) {
4721 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4722 eval($result);
4723 return $resultstring;
4728 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4729 /// if it hasn't been queried before.
4730 if ($defaultlang == 'en') {
4731 $defaultlang = 'en_utf8';
4732 foreach ($locations as $location) {
4733 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4734 if (file_exists($locallangfile)) {
4735 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4736 eval($result);
4737 return $resultstring;
4741 //if local_en not found, or string not found in local_en
4742 $langfile = $location.$defaultlang.'/'.$module.'.php';
4744 if (file_exists($langfile)) {
4745 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4746 eval($result);
4747 return $resultstring;
4753 return '[['.$identifier.']]'; // Last resort
4757 * This function is only used from {@link get_string()}.
4759 * @internal Only used from get_string, not meant to be public API
4760 * @param string $identifier ?
4761 * @param string $langfile ?
4762 * @param string $destination ?
4763 * @return string|false ?
4764 * @staticvar array $strings Localized strings
4765 * @access private
4766 * @todo Finish documenting this function.
4768 function get_string_from_file($identifier, $langfile, $destination) {
4770 static $strings; // Keep the strings cached in memory.
4772 if (empty($strings[$langfile])) {
4773 $string = array();
4774 include ($langfile);
4775 $strings[$langfile] = $string;
4776 } else {
4777 $string = &$strings[$langfile];
4780 if (!isset ($string[$identifier])) {
4781 return false;
4784 return $destination .'= sprintf("'. $string[$identifier] .'");';
4788 * Converts an array of strings to their localized value.
4790 * @param array $array An array of strings
4791 * @param string $module The language module that these strings can be found in.
4792 * @return string
4794 function get_strings($array, $module='') {
4796 $string = NULL;
4797 foreach ($array as $item) {
4798 $string->$item = get_string($item, $module);
4800 return $string;
4804 * Returns a list of language codes and their full names
4805 * hides the _local files from everyone.
4806 * @param bool refreshcache force refreshing of lang cache
4807 * @param bool returnall ignore langlist, return all languages available
4808 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4810 function get_list_of_languages($refreshcache=false, $returnall=false) {
4812 global $CFG;
4814 $languages = array();
4816 $filetocheck = 'langconfig.php';
4818 if (!$refreshcache && !$returnall && !empty($CFG->langcache) && file_exists($CFG->dataroot .'/cache/languages')) {
4819 /// read available langs from cache
4821 $lines = file($CFG->dataroot .'/cache/languages');
4822 foreach ($lines as $line) {
4823 $line = trim($line);
4824 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4825 $languages[$matches[1]] = $matches[2];
4828 unset($lines); unset($line); unset($matches);
4829 return $languages;
4832 if (!$returnall && !empty($CFG->langlist)) {
4833 /// return only languages allowed in langlist admin setting
4835 $langlist = explode(',', $CFG->langlist);
4836 // fix short lang names first - non existing langs are skipped anyway...
4837 foreach ($langlist as $lang) {
4838 if (strpos($lang, '_utf8') === false) {
4839 $langlist[] = $lang.'_utf8';
4842 // find existing langs from langlist
4843 foreach ($langlist as $lang) {
4844 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4845 if (strstr($lang, '_local')!==false) {
4846 continue;
4848 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4849 $shortlang = substr($lang, 0, -5);
4850 } else {
4851 $shortlang = $lang;
4853 /// Search under dirroot/lang
4854 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4855 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4856 if (!empty($string['thislanguage'])) {
4857 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4859 unset($string);
4861 /// And moodledata/lang
4862 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4863 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4864 if (!empty($string['thislanguage'])) {
4865 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4867 unset($string);
4871 } else {
4872 /// return all languages available in system
4873 /// Fetch langs from moodle/lang directory
4874 $langdirs = get_list_of_plugins('lang');
4875 /// Fetch langs from moodledata/lang directory
4876 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot);
4877 /// Merge both lists of langs
4878 $langdirs = array_merge($langdirs, $langdirs2);
4879 /// Sort all
4880 asort($langdirs);
4881 /// Get some info from each lang (first from moodledata, then from moodle)
4882 foreach ($langdirs as $lang) {
4883 if (strstr($lang, '_local')!==false) {
4884 continue;
4886 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4887 $shortlang = substr($lang, 0, -5);
4888 } else {
4889 $shortlang = $lang;
4891 /// Search under moodledata/lang
4892 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4893 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4894 if (!empty($string['thislanguage'])) {
4895 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4897 unset($string);
4899 /// And dirroot/lang
4900 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4901 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4902 if (!empty($string['thislanguage'])) {
4903 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4905 unset($string);
4910 if ($refreshcache && !empty($CFG->langcache)) {
4911 if ($returnall) {
4912 // we have a list of all langs only, just delete old cache
4913 @unlink($CFG->dataroot.'/cache/languages');
4915 } else {
4916 // store the list of allowed languages
4917 if ($file = fopen($CFG->dataroot .'/cache/languages', 'w')) {
4918 foreach ($languages as $key => $value) {
4919 fwrite($file, "$key $value\n");
4921 fclose($file);
4926 return $languages;
4930 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4931 * (cheking that such charset is supported by the texlib library!)
4933 * @return array And associative array with contents in the form of charset => charset
4935 function get_list_of_charsets() {
4937 $charsets = array(
4938 'EUC-JP' => 'EUC-JP',
4939 'ISO-2022-JP'=> 'ISO-2022-JP',
4940 'ISO-8859-1' => 'ISO-8859-1',
4941 'SHIFT-JIS' => 'SHIFT-JIS',
4942 'GB2312' => 'GB2312',
4943 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4944 'UTF-8' => 'UTF-8');
4946 asort($charsets);
4948 return $charsets;
4952 * Returns a list of country names in the current language
4954 * @uses $CFG
4955 * @uses $USER
4956 * @return array
4958 function get_list_of_countries() {
4959 global $CFG, $USER;
4961 $lang = current_language();
4963 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php') &&
4964 !file_exists($CFG->dataroot.'/lang/'. $lang .'/countries.php')) {
4965 if ($parentlang = get_string('parentlanguage')) {
4966 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/countries.php') ||
4967 file_exists($CFG->dataroot.'/lang/'. $parentlang .'/countries.php')) {
4968 $lang = $parentlang;
4969 } else {
4970 $lang = 'en_utf8'; // countries.php must exist in this pack
4972 } else {
4973 $lang = 'en_utf8'; // countries.php must exist in this pack
4977 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/countries.php')) {
4978 include($CFG->dataroot .'/lang/'. $lang .'/countries.php');
4979 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
4980 include($CFG->dirroot .'/lang/'. $lang .'/countries.php');
4983 if (!empty($string)) {
4984 asort($string);
4987 return $string;
4991 * Returns a list of valid and compatible themes
4993 * @uses $CFG
4994 * @return array
4996 function get_list_of_themes() {
4998 global $CFG;
5000 $themes = array();
5002 if (!empty($CFG->themelist)) { // use admin's list of themes
5003 $themelist = explode(',', $CFG->themelist);
5004 } else {
5005 $themelist = get_list_of_plugins("theme");
5008 foreach ($themelist as $key => $theme) {
5009 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
5010 continue;
5012 $THEME = new object(); // Note this is not the global one!! :-)
5013 include("$CFG->themedir/$theme/config.php");
5014 if (!isset($THEME->sheets)) { // Not a valid 1.5 theme
5015 continue;
5017 $themes[$theme] = $theme;
5019 asort($themes);
5021 return $themes;
5026 * Returns a list of picture names in the current or specified language
5028 * @uses $CFG
5029 * @return array
5031 function get_list_of_pixnames($lang = '') {
5032 global $CFG;
5034 if (empty($lang)) {
5035 $lang = current_language();
5038 $string = array();
5040 $path = $CFG->dirroot .'/lang/en_utf8/pix.php'; // always exists
5042 if (file_exists($CFG->dataroot .'/lang/'. $lang .'_local/pix.php')) {
5043 $path = $CFG->dataroot .'/lang/'. $lang .'_local/pix.php';
5045 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
5046 $path = $CFG->dirroot .'/lang/'. $lang .'/pix.php';
5048 } else if (file_exists($CFG->dataroot .'/lang/'. $lang .'/pix.php')) {
5049 $path = $CFG->dataroot .'/lang/'. $lang .'/pix.php';
5051 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
5052 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
5055 include($path);
5057 return $string;
5061 * Returns a list of timezones in the current language
5063 * @uses $CFG
5064 * @return array
5066 function get_list_of_timezones() {
5067 global $CFG;
5069 static $timezones;
5071 if (!empty($timezones)) { // This function has been called recently
5072 return $timezones;
5075 $timezones = array();
5077 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix.'timezone GROUP BY name')) {
5078 foreach($rawtimezones as $timezone) {
5079 if (!empty($timezone->name)) {
5080 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
5081 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
5082 $timezones[$timezone->name] = $timezone->name;
5088 asort($timezones);
5090 for ($i = -13; $i <= 13; $i += .5) {
5091 $tzstring = 'GMT';
5092 if ($i < 0) {
5093 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
5094 } else if ($i > 0) {
5095 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
5096 } else {
5097 $timezones[sprintf("%.1f", $i)] = $tzstring;
5101 return $timezones;
5105 * Returns a list of currencies in the current language
5107 * @uses $CFG
5108 * @uses $USER
5109 * @return array
5111 function get_list_of_currencies() {
5112 global $CFG, $USER;
5114 $lang = current_language();
5116 if (!file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
5117 if ($parentlang = get_string('parentlanguage')) {
5118 if (file_exists($CFG->dataroot .'/lang/'. $parentlang .'/currencies.php')) {
5119 $lang = $parentlang;
5120 } else {
5121 $lang = 'en_utf8'; // currencies.php must exist in this pack
5123 } else {
5124 $lang = 'en_utf8'; // currencies.php must exist in this pack
5128 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
5129 include_once($CFG->dataroot .'/lang/'. $lang .'/currencies.php');
5130 } else { //if en_utf8 is not installed in dataroot
5131 include_once($CFG->dirroot .'/lang/'. $lang .'/currencies.php');
5134 if (!empty($string)) {
5135 asort($string);
5138 return $string;
5144 * Can include a given document file (depends on second
5145 * parameter) or just return info about it.
5147 * @uses $CFG
5148 * @param string $file ?
5149 * @param bool $include ?
5150 * @return ?
5151 * @todo Finish documenting this function
5153 function document_file($file, $include=true) {
5154 global $CFG;
5156 $file = clean_filename($file);
5158 if (empty($file)) {
5159 return false;
5162 $langs = array(current_language(), get_string('parentlanguage'), 'en');
5164 foreach ($langs as $lang) {
5165 $info = new object();
5166 $info->filepath = $CFG->dirroot .'/lang/'. $lang .'/docs/'. $file;
5167 $info->urlpath = $CFG->wwwroot .'/lang/'. $lang .'/docs/'. $file;
5169 if (file_exists($info->filepath)) {
5170 if ($include) {
5171 include($info->filepath);
5173 return $info;
5177 return false;
5180 /// ENCRYPTION ////////////////////////////////////////////////
5183 * rc4encrypt
5185 * @param string $data ?
5186 * @return string
5187 * @todo Finish documenting this function
5189 function rc4encrypt($data) {
5190 $password = 'nfgjeingjk';
5191 return endecrypt($password, $data, '');
5195 * rc4decrypt
5197 * @param string $data ?
5198 * @return string
5199 * @todo Finish documenting this function
5201 function rc4decrypt($data) {
5202 $password = 'nfgjeingjk';
5203 return endecrypt($password, $data, 'de');
5207 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5209 * @param string $pwd ?
5210 * @param string $data ?
5211 * @param string $case ?
5212 * @return string
5213 * @todo Finish documenting this function
5215 function endecrypt ($pwd, $data, $case) {
5217 if ($case == 'de') {
5218 $data = urldecode($data);
5221 $key[] = '';
5222 $box[] = '';
5223 $temp_swap = '';
5224 $pwd_length = 0;
5226 $pwd_length = strlen($pwd);
5228 for ($i = 0; $i <= 255; $i++) {
5229 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
5230 $box[$i] = $i;
5233 $x = 0;
5235 for ($i = 0; $i <= 255; $i++) {
5236 $x = ($x + $box[$i] + $key[$i]) % 256;
5237 $temp_swap = $box[$i];
5238 $box[$i] = $box[$x];
5239 $box[$x] = $temp_swap;
5242 $temp = '';
5243 $k = '';
5245 $cipherby = '';
5246 $cipher = '';
5248 $a = 0;
5249 $j = 0;
5251 for ($i = 0; $i < strlen($data); $i++) {
5252 $a = ($a + 1) % 256;
5253 $j = ($j + $box[$a]) % 256;
5254 $temp = $box[$a];
5255 $box[$a] = $box[$j];
5256 $box[$j] = $temp;
5257 $k = $box[(($box[$a] + $box[$j]) % 256)];
5258 $cipherby = ord(substr($data, $i, 1)) ^ $k;
5259 $cipher .= chr($cipherby);
5262 if ($case == 'de') {
5263 $cipher = urldecode(urlencode($cipher));
5264 } else {
5265 $cipher = urlencode($cipher);
5268 return $cipher;
5272 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5276 * Call this function to add an event to the calendar table
5277 * and to call any calendar plugins
5279 * @uses $CFG
5280 * @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:
5281 * <ul>
5282 * <li><b>$event->name</b> - Name for the event
5283 * <li><b>$event->description</b> - Description of the event (defaults to '')
5284 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5285 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5286 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5287 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5288 * <li><b>$event->modulename</b> - Name of the module that creates this event
5289 * <li><b>$event->instance</b> - Instance of the module that owns this event
5290 * <li><b>$event->eventtype</b> - The type info together with the module info could
5291 * be used by calendar plugins to decide how to display event
5292 * <li><b>$event->timestart</b>- Timestamp for start of event
5293 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5294 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5295 * </ul>
5296 * @return int The id number of the resulting record
5298 function add_event($event) {
5300 global $CFG;
5302 $event->timemodified = time();
5304 if (!$event->id = insert_record('event', $event)) {
5305 return false;
5308 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
5309 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5310 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5311 $calendar_add_event = $CFG->calendar.'_add_event';
5312 if (function_exists($calendar_add_event)) {
5313 $calendar_add_event($event);
5318 return $event->id;
5322 * Call this function to update an event in the calendar table
5323 * the event will be identified by the id field of the $event object.
5325 * @uses $CFG
5326 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5327 * @return bool
5329 function update_event($event) {
5331 global $CFG;
5333 $event->timemodified = time();
5335 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5336 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5337 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5338 $calendar_update_event = $CFG->calendar.'_update_event';
5339 if (function_exists($calendar_update_event)) {
5340 $calendar_update_event($event);
5344 return update_record('event', $event);
5348 * Call this function to delete the event with id $id from calendar table.
5350 * @uses $CFG
5351 * @param int $id The id of an event from the 'calendar' table.
5352 * @return array An associative array with the results from the SQL call.
5353 * @todo Verify return type
5355 function delete_event($id) {
5357 global $CFG;
5359 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
5360 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5361 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5362 $calendar_delete_event = $CFG->calendar.'_delete_event';
5363 if (function_exists($calendar_delete_event)) {
5364 $calendar_delete_event($id);
5368 return delete_records('event', 'id', $id);
5372 * Call this function to hide an event in the calendar table
5373 * the event will be identified by the id field of the $event object.
5375 * @uses $CFG
5376 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5377 * @return array An associative array with the results from the SQL call.
5378 * @todo Verify return type
5380 function hide_event($event) {
5381 global $CFG;
5383 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5384 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5385 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5386 $calendar_hide_event = $CFG->calendar.'_hide_event';
5387 if (function_exists($calendar_hide_event)) {
5388 $calendar_hide_event($event);
5392 return set_field('event', 'visible', 0, 'id', $event->id);
5396 * Call this function to unhide an event in the calendar table
5397 * the event will be identified by the id field of the $event object.
5399 * @uses $CFG
5400 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5401 * @return array An associative array with the results from the SQL call.
5402 * @todo Verify return type
5404 function show_event($event) {
5405 global $CFG;
5407 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5408 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5409 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5410 $calendar_show_event = $CFG->calendar.'_show_event';
5411 if (function_exists($calendar_show_event)) {
5412 $calendar_show_event($event);
5416 return set_field('event', 'visible', 1, 'id', $event->id);
5420 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5423 * Lists plugin directories within some directory
5425 * @uses $CFG
5426 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5427 * @param string $exclude dir name to exclude from the list (defaults to none)
5428 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5429 * @return array of plugins found under the requested parameters
5431 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5433 global $CFG;
5435 $plugins = array();
5437 if (empty($basedir)) {
5439 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5440 switch ($plugin) {
5441 case "theme":
5442 $basedir = $CFG->themedir;
5443 break;
5445 default:
5446 $basedir = $CFG->dirroot .'/'. $plugin;
5449 } else {
5450 $basedir = $basedir .'/'. $plugin;
5453 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5454 $dirhandle = opendir($basedir);
5455 while (false !== ($dir = readdir($dirhandle))) {
5456 $firstchar = substr($dir, 0, 1);
5457 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5458 continue;
5460 if (filetype($basedir .'/'. $dir) != 'dir') {
5461 continue;
5463 $plugins[] = $dir;
5465 closedir($dirhandle);
5467 if ($plugins) {
5468 asort($plugins);
5470 return $plugins;
5474 * Returns true if the current version of PHP is greater that the specified one.
5476 * @param string $version The version of php being tested.
5477 * @return bool
5479 function check_php_version($version='4.1.0') {
5480 return (version_compare(phpversion(), $version) >= 0);
5485 * Checks to see if is a browser matches the specified
5486 * brand and is equal or better version.
5488 * @uses $_SERVER
5489 * @param string $brand The browser identifier being tested
5490 * @param int $version The version of the browser
5491 * @return bool true if the given version is below that of the detected browser
5493 function check_browser_version($brand='MSIE', $version=5.5) {
5494 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5495 return false;
5498 $agent = $_SERVER['HTTP_USER_AGENT'];
5500 switch ($brand) {
5502 case 'Camino': /// Mozilla Firefox browsers
5504 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5505 if (version_compare($match[1], $version) >= 0) {
5506 return true;
5509 break;
5512 case 'Firefox': /// Mozilla Firefox browsers
5514 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5515 if (version_compare($match[1], $version) >= 0) {
5516 return true;
5519 break;
5522 case 'Gecko': /// Gecko based browsers
5524 if (substr_count($agent, 'Camino')) {
5525 // MacOS X Camino support
5526 $version = 20041110;
5529 // the proper string - Gecko/CCYYMMDD Vendor/Version
5530 // Faster version and work-a-round No IDN problem.
5531 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5532 if ($match[1] > $version) {
5533 return true;
5536 break;
5539 case 'MSIE': /// Internet Explorer
5541 if (strpos($agent, 'Opera')) { // Reject Opera
5542 return false;
5544 $string = explode(';', $agent);
5545 if (!isset($string[1])) {
5546 return false;
5548 $string = explode(' ', trim($string[1]));
5549 if (!isset($string[0]) and !isset($string[1])) {
5550 return false;
5552 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5553 return true;
5555 break;
5557 case 'Opera': /// Opera
5559 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5560 if (version_compare($match[1], $version) >= 0) {
5561 return true;
5564 break;
5566 case 'Safari': /// Safari
5567 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5568 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5569 return false;
5570 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5571 return false;
5572 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5573 return false;
5576 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5577 if (version_compare($match[1], $version) >= 0) {
5578 return true;
5582 break;
5586 return false;
5590 * This function makes the return value of ini_get consistent if you are
5591 * setting server directives through the .htaccess file in apache.
5592 * Current behavior for value set from php.ini On = 1, Off = [blank]
5593 * Current behavior for value set from .htaccess On = On, Off = Off
5594 * Contributed by jdell @ unr.edu
5596 * @param string $ini_get_arg ?
5597 * @return bool
5598 * @todo Finish documenting this function
5600 function ini_get_bool($ini_get_arg) {
5601 $temp = ini_get($ini_get_arg);
5603 if ($temp == '1' or strtolower($temp) == 'on') {
5604 return true;
5606 return false;
5610 * Compatibility stub to provide backward compatibility
5612 * Determines if the HTML editor is enabled.
5613 * @deprecated Use {@link can_use_html_editor()} instead.
5615 function can_use_richtext_editor() {
5616 return can_use_html_editor();
5620 * Determines if the HTML editor is enabled.
5622 * This depends on site and user
5623 * settings, as well as the current browser being used.
5625 * @return string|false Returns false if editor is not being used, otherwise
5626 * returns 'MSIE' or 'Gecko'.
5628 function can_use_html_editor() {
5629 global $USER, $CFG;
5631 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
5632 if (check_browser_version('MSIE', 5.5)) {
5633 return 'MSIE';
5634 } else if (check_browser_version('Gecko', 20030516)) {
5635 return 'Gecko';
5638 return false;
5642 * Hack to find out the GD version by parsing phpinfo output
5644 * @return int GD version (1, 2, or 0)
5646 function check_gd_version() {
5647 $gdversion = 0;
5649 if (function_exists('gd_info')){
5650 $gd_info = gd_info();
5651 if (substr_count($gd_info['GD Version'], '2.')) {
5652 $gdversion = 2;
5653 } else if (substr_count($gd_info['GD Version'], '1.')) {
5654 $gdversion = 1;
5657 } else {
5658 ob_start();
5659 phpinfo(8);
5660 $phpinfo = ob_get_contents();
5661 ob_end_clean();
5663 $phpinfo = explode("\n", $phpinfo);
5666 foreach ($phpinfo as $text) {
5667 $parts = explode('</td>', $text);
5668 foreach ($parts as $key => $val) {
5669 $parts[$key] = trim(strip_tags($val));
5671 if ($parts[0] == 'GD Version') {
5672 if (substr_count($parts[1], '2.0')) {
5673 $parts[1] = '2.0';
5675 $gdversion = intval($parts[1]);
5680 return $gdversion; // 1, 2 or 0
5684 * Determine if moodle installation requires update
5686 * Checks version numbers of main code and all modules to see
5687 * if there are any mismatches
5689 * @uses $CFG
5690 * @return bool
5692 function moodle_needs_upgrading() {
5693 global $CFG;
5695 $version = null;
5696 include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
5697 if ($CFG->version) {
5698 if ($version > $CFG->version) {
5699 return true;
5701 if ($mods = get_list_of_plugins('mod')) {
5702 foreach ($mods as $mod) {
5703 $fullmod = $CFG->dirroot .'/mod/'. $mod;
5704 $module = new object();
5705 if (!is_readable($fullmod .'/version.php')) {
5706 notify('Module "'. $mod .'" is not readable - check permissions');
5707 continue;
5709 include_once($fullmod .'/version.php'); # defines $module with version etc
5710 if ($currmodule = get_record('modules', 'name', $mod)) {
5711 if ($module->version > $currmodule->version) {
5712 return true;
5717 } else {
5718 return true;
5720 return false;
5724 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5727 * Notify admin users or admin user of any failed logins (since last notification).
5729 * @uses $CFG
5730 * @uses $db
5731 * @uses HOURSECS
5733 function notify_login_failures() {
5734 global $CFG, $db;
5736 switch ($CFG->notifyloginfailures) {
5737 case 'mainadmin' :
5738 $recip = array(get_admin());
5739 break;
5740 case 'alladmins':
5741 $recip = get_admins();
5742 break;
5745 if (empty($CFG->lastnotifyfailure)) {
5746 $CFG->lastnotifyfailure=0;
5749 // we need to deal with the threshold stuff first.
5750 if (empty($CFG->notifyloginthreshold)) {
5751 $CFG->notifyloginthreshold = 10; // default to something sensible.
5754 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5755 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold);
5757 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5758 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold);
5760 if ($notifyipsrs) {
5761 $ipstr = '';
5762 while ($row = rs_fetch_next_record($notifyipsrs)) {
5763 $ipstr .= "'". $row->ip ."',";
5765 rs_close($notifyipsrs);
5766 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5768 if ($notifyusersrs) {
5769 $userstr = '';
5770 while ($row = rs_fetch_next_record($notifyusersrs)) {
5771 $userstr .= "'". $row->info ."',";
5773 rs_close($notifyusersrs);
5774 $userstr = substr($userstr,0,strlen($userstr)-1);
5777 if (strlen($userstr) > 0 || strlen($ipstr) > 0) {
5778 $count = 0;
5779 $logs = get_logs('time > '. $CFG->lastnotifyfailure .' AND module=\'login\' AND action=\'error\' '
5780 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ? ' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5781 : ((strlen($ipstr) != 0) ? ' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5783 // if we haven't run in the last hour and we have something useful to report and we are actually supposed to be reporting to somebody
5784 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS) > $CFG->lastnotifyfailure)
5785 and is_array($logs) and count($logs) > 0) {
5787 $message = '';
5788 $site = get_site();
5789 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
5790 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot)
5791 .(($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n";
5792 foreach ($logs as $log) {
5793 $log->time = userdate($log->time);
5794 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5796 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
5797 foreach ($recip as $admin) {
5798 mtrace('Emailing '. $admin->username .' about '. count($logs) .' failed login attempts');
5799 email_to_user($admin,get_admin(),$subject,$message);
5801 $conf = new object();
5802 $conf->name = 'lastnotifyfailure';
5803 $conf->value = time();
5804 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5805 $conf->id = $current->id;
5806 if (! update_record('config', $conf)) {
5807 mtrace('Could not update last notify time');
5810 } else if (! insert_record('config', $conf)) {
5811 mtrace('Could not set last notify time');
5818 * moodle_setlocale
5820 * @uses $CFG
5821 * @param string $locale ?
5822 * @todo Finish documenting this function
5824 function moodle_setlocale($locale='') {
5826 global $CFG;
5828 static $currentlocale = ''; // last locale caching
5830 $oldlocale = $currentlocale;
5832 /// Fetch the correct locale based on ostype
5833 if($CFG->ostype == 'WINDOWS') {
5834 $stringtofetch = 'localewin';
5835 } else {
5836 $stringtofetch = 'locale';
5839 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5840 if (!empty($locale)) {
5841 $currentlocale = $locale;
5842 } else if (!empty($CFG->locale)) { // override locale for all language packs
5843 $currentlocale = $CFG->locale;
5844 } else {
5845 $currentlocale = get_string($stringtofetch);
5848 /// do nothing if locale already set up
5849 if ($oldlocale == $currentlocale) {
5850 return;
5853 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5854 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5855 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5857 /// Get current values
5858 $monetary= setlocale (LC_MONETARY, 0);
5859 $numeric = setlocale (LC_NUMERIC, 0);
5860 $ctype = setlocale (LC_CTYPE, 0);
5861 if ($CFG->ostype != 'WINDOWS') {
5862 $messages= setlocale (LC_MESSAGES, 0);
5864 /// Set locale to all
5865 setlocale (LC_ALL, $currentlocale);
5866 /// Set old values
5867 setlocale (LC_MONETARY, $monetary);
5868 setlocale (LC_NUMERIC, $numeric);
5869 if ($CFG->ostype != 'WINDOWS') {
5870 setlocale (LC_MESSAGES, $messages);
5872 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5873 setlocale (LC_CTYPE, $ctype);
5878 * Converts string to lowercase using most compatible function available.
5880 * @param string $string The string to convert to all lowercase characters.
5881 * @param string $encoding The encoding on the string.
5882 * @return string
5883 * @todo Add examples of calling this function with/without encoding types
5884 * @deprecated Use textlib->strtolower($text) instead.
5886 function moodle_strtolower ($string, $encoding='') {
5888 //If not specified use utf8
5889 if (empty($encoding)) {
5890 $encoding = 'UTF-8';
5892 //Use text services
5893 $textlib = textlib_get_instance();
5895 return $textlib->strtolower($string, $encoding);
5899 * Count words in a string.
5901 * Words are defined as things between whitespace.
5903 * @param string $string The text to be searched for words.
5904 * @return int The count of words in the specified string
5906 function count_words($string) {
5907 $string = strip_tags($string);
5908 return count(preg_split("/\w\b/", $string)) - 1;
5911 /** Count letters in a string.
5913 * Letters are defined as chars not in tags and different from whitespace.
5915 * @param string $string The text to be searched for letters.
5916 * @return int The count of letters in the specified text.
5918 function count_letters($string) {
5919 /// Loading the textlib singleton instance. We are going to need it.
5920 $textlib = textlib_get_instance();
5922 $string = strip_tags($string); // Tags are out now
5923 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5925 return $textlib->strlen($string);
5929 * Generate and return a random string of the specified length.
5931 * @param int $length The length of the string to be created.
5932 * @return string
5934 function random_string ($length=15) {
5935 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5936 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5937 $pool .= '0123456789';
5938 $poollen = strlen($pool);
5939 mt_srand ((double) microtime() * 1000000);
5940 $string = '';
5941 for ($i = 0; $i < $length; $i++) {
5942 $string .= substr($pool, (mt_rand()%($poollen)), 1);
5944 return $string;
5948 * Given some text (which may contain HTML) and an ideal length,
5949 * this function truncates the text neatly on a word boundary if possible
5951 function shorten_text($text, $ideal=30) {
5953 global $CFG;
5956 $i = 0;
5957 $tag = false;
5958 $length = strlen($text);
5959 $count = 0;
5960 $stopzone = false;
5961 $truncate = 0;
5963 if ($length <= $ideal) {
5964 return $text;
5967 for ($i=0; $i<$length; $i++) {
5968 $char = $text[$i];
5970 switch ($char) {
5971 case "<":
5972 $tag = true;
5973 break;
5974 case ">":
5975 $tag = false;
5976 break;
5977 default:
5978 if (!$tag) {
5979 if ($stopzone) {
5980 if ($char == '.' or $char == ' ') {
5981 $truncate = $i+1;
5982 break 2;
5983 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5984 $truncate = $i; // can be truncated at any UTF-8
5985 break 2; // character boundary.
5988 $count++;
5990 break;
5992 if (!$stopzone) {
5993 if ($count > $ideal) {
5994 $stopzone = true;
5999 if (!$truncate) {
6000 $truncate = $i;
6003 $ellipse = ($truncate < $length) ? '...' : '';
6005 return substr($text, 0, $truncate).$ellipse;
6010 * Given dates in seconds, how many weeks is the date from startdate
6011 * The first week is 1, the second 2 etc ...
6013 * @uses WEEKSECS
6014 * @param ? $startdate ?
6015 * @param ? $thedate ?
6016 * @return string
6017 * @todo Finish documenting this function
6019 function getweek ($startdate, $thedate) {
6020 if ($thedate < $startdate) { // error
6021 return 0;
6024 return floor(($thedate - $startdate) / WEEKSECS) + 1;
6028 * returns a randomly generated password of length $maxlen. inspired by
6029 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
6031 * @param int $maxlength The maximum size of the password being generated.
6032 * @return string
6034 function generate_password($maxlen=10) {
6035 global $CFG;
6037 $fillers = '1234567890!$-+';
6038 $wordlist = file($CFG->wordlist);
6040 srand((double) microtime() * 1000000);
6041 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6042 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
6043 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
6045 return substr($word1 . $filler1 . $word2, 0, $maxlen);
6049 * Given a float, prints it nicely.
6050 * Localized floats must not be used in calculations!
6052 * @param float $flaot The float to print
6053 * @param int $places The number of decimal places to print.
6054 * @param bool $localized use localized decimal separator
6055 * @return string locale float
6057 function format_float($float, $decimalpoints=1, $localized=true) {
6058 if (is_null($float)) {
6059 return '';
6061 if ($localized) {
6062 return number_format($float, $decimalpoints, get_string('decsep'), '');
6063 } else {
6064 return number_format($float, $decimalpoints, '.', '');
6069 * Converts locale specific floating point/comma number back to standard PHP float value
6070 * Do NOT try to do any math operations before this conversion on any user submitted floats!
6072 * @param string $locale_float locale aware float representation
6074 function unformat_float($locale_float) {
6075 $locale_float = trim($locale_float);
6077 if ($locale_float == '') {
6078 return null;
6081 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
6083 return (float)str_replace(get_string('decsep'), '.', $locale_float);
6087 * Given a simple array, this shuffles it up just like shuffle()
6088 * Unlike PHP's shuffle() this function works on any machine.
6090 * @param array $array The array to be rearranged
6091 * @return array
6093 function swapshuffle($array) {
6095 srand ((double) microtime() * 10000000);
6096 $last = count($array) - 1;
6097 for ($i=0;$i<=$last;$i++) {
6098 $from = rand(0,$last);
6099 $curr = $array[$i];
6100 $array[$i] = $array[$from];
6101 $array[$from] = $curr;
6103 return $array;
6107 * Like {@link swapshuffle()}, but works on associative arrays
6109 * @param array $array The associative array to be rearranged
6110 * @return array
6112 function swapshuffle_assoc($array) {
6115 $newkeys = swapshuffle(array_keys($array));
6116 foreach ($newkeys as $newkey) {
6117 $newarray[$newkey] = $array[$newkey];
6119 return $newarray;
6123 * Given an arbitrary array, and a number of draws,
6124 * this function returns an array with that amount
6125 * of items. The indexes are retained.
6127 * @param array $array ?
6128 * @param ? $draws ?
6129 * @return ?
6130 * @todo Finish documenting this function
6132 function draw_rand_array($array, $draws) {
6133 srand ((double) microtime() * 10000000);
6135 $return = array();
6137 $last = count($array);
6139 if ($draws > $last) {
6140 $draws = $last;
6143 while ($draws > 0) {
6144 $last--;
6146 $keys = array_keys($array);
6147 $rand = rand(0, $last);
6149 $return[$keys[$rand]] = $array[$keys[$rand]];
6150 unset($array[$keys[$rand]]);
6152 $draws--;
6155 return $return;
6159 * microtime_diff
6161 * @param string $a ?
6162 * @param string $b ?
6163 * @return string
6164 * @todo Finish documenting this function
6166 function microtime_diff($a, $b) {
6167 list($a_dec, $a_sec) = explode(' ', $a);
6168 list($b_dec, $b_sec) = explode(' ', $b);
6169 return $b_sec - $a_sec + $b_dec - $a_dec;
6173 * Given a list (eg a,b,c,d,e) this function returns
6174 * an array of 1->a, 2->b, 3->c etc
6176 * @param array $list ?
6177 * @param string $separator ?
6178 * @todo Finish documenting this function
6180 function make_menu_from_list($list, $separator=',') {
6182 $array = array_reverse(explode($separator, $list), true);
6183 foreach ($array as $key => $item) {
6184 $outarray[$key+1] = trim($item);
6186 return $outarray;
6190 * Creates an array that represents all the current grades that
6191 * can be chosen using the given grading type. Negative numbers
6192 * are scales, zero is no grade, and positive numbers are maximum
6193 * grades.
6195 * @param int $gradingtype ?
6196 * return int
6197 * @todo Finish documenting this function
6199 function make_grades_menu($gradingtype) {
6200 $grades = array();
6201 if ($gradingtype < 0) {
6202 if ($scale = get_record('scale', 'id', - $gradingtype)) {
6203 return make_menu_from_list($scale->scale);
6205 } else if ($gradingtype > 0) {
6206 for ($i=$gradingtype; $i>=0; $i--) {
6207 $grades[$i] = $i .' / '. $gradingtype;
6209 return $grades;
6211 return $grades;
6215 * This function returns the nummber of activities
6216 * using scaleid in a courseid
6218 * @param int $courseid ?
6219 * @param int $scaleid ?
6220 * @return int
6221 * @todo Finish documenting this function
6223 function course_scale_used($courseid, $scaleid) {
6225 global $CFG;
6227 $return = 0;
6229 if (!empty($scaleid)) {
6230 if ($cms = get_course_mods($courseid)) {
6231 foreach ($cms as $cm) {
6232 //Check cm->name/lib.php exists
6233 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
6234 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
6235 $function_name = $cm->modname.'_scale_used';
6236 if (function_exists($function_name)) {
6237 if ($function_name($cm->instance,$scaleid)) {
6238 $return++;
6245 // check if any course grade item makes use of the scale
6246 $return += count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
6248 return $return;
6252 * This function returns the nummber of activities
6253 * using scaleid in the entire site
6255 * @param int $scaleid ?
6256 * @return int
6257 * @todo Finish documenting this function. Is return type correct?
6259 function site_scale_used($scaleid,&$courses) {
6261 global $CFG;
6263 $return = 0;
6265 if (!is_array($courses) || count($courses) == 0) {
6266 $courses = get_courses("all",false,"c.id,c.shortname");
6269 if (!empty($scaleid)) {
6270 if (is_array($courses) && count($courses) > 0) {
6271 foreach ($courses as $course) {
6272 $return += course_scale_used($course->id,$scaleid);
6276 return $return;
6280 * make_unique_id_code
6282 * @param string $extra ?
6283 * @return string
6284 * @todo Finish documenting this function
6286 function make_unique_id_code($extra='') {
6288 $hostname = 'unknownhost';
6289 if (!empty($_SERVER['HTTP_HOST'])) {
6290 $hostname = $_SERVER['HTTP_HOST'];
6291 } else if (!empty($_ENV['HTTP_HOST'])) {
6292 $hostname = $_ENV['HTTP_HOST'];
6293 } else if (!empty($_SERVER['SERVER_NAME'])) {
6294 $hostname = $_SERVER['SERVER_NAME'];
6295 } else if (!empty($_ENV['SERVER_NAME'])) {
6296 $hostname = $_ENV['SERVER_NAME'];
6299 $date = gmdate("ymdHis");
6301 $random = random_string(6);
6303 if ($extra) {
6304 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6305 } else {
6306 return $hostname .'+'. $date .'+'. $random;
6312 * Function to check the passed address is within the passed subnet
6314 * The parameter is a comma separated string of subnet definitions.
6315 * Subnet strings can be in one of three formats:
6316 * 1: xxx.xxx.xxx.xxx/xx
6317 * 2: xxx.xxx
6318 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
6319 * Code for type 1 modified from user posted comments by mediator at
6320 * {@link http://au.php.net/manual/en/function.ip2long.php}
6322 * @param string $addr The address you are checking
6323 * @param string $subnetstr The string of subnet addresses
6324 * @return bool
6326 function address_in_subnet($addr, $subnetstr) {
6328 $subnets = explode(',', $subnetstr);
6329 $found = false;
6330 $addr = trim($addr);
6332 foreach ($subnets as $subnet) {
6333 $subnet = trim($subnet);
6334 if (strpos($subnet, '/') !== false) { /// type 1
6335 list($ip, $mask) = explode('/', $subnet);
6336 $mask = 0xffffffff << (32 - $mask);
6337 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
6338 } else if (strpos($subnet, '-') !== false) {/// type 3
6339 $subnetparts = explode('.', $subnet);
6340 $addrparts = explode('.', $addr);
6341 $subnetrange = explode('-', array_pop($subnetparts));
6342 if (count($subnetrange) == 2) {
6343 $lastaddrpart = array_pop($addrparts);
6344 $found = ($subnetparts == $addrparts &&
6345 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
6347 } else { /// type 2
6348 $found = (strpos($addr, $subnet) === 0);
6351 if ($found) {
6352 break;
6355 return $found;
6359 * This function sets the $HTTPSPAGEREQUIRED global
6360 * (used in some parts of moodle to change some links)
6361 * and calculate the proper wwwroot to be used
6363 * By using this function properly, we can ensure 100% https-ized pages
6364 * at our entire discretion (login, forgot_password, change_password)
6366 function httpsrequired() {
6368 global $CFG, $HTTPSPAGEREQUIRED;
6370 if (!empty($CFG->loginhttps)) {
6371 $HTTPSPAGEREQUIRED = true;
6372 $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
6373 $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
6375 // change theme URLs to https
6376 theme_setup();
6378 } else {
6379 $CFG->httpswwwroot = $CFG->wwwroot;
6380 $CFG->httpsthemewww = $CFG->themewww;
6385 * For outputting debugging info
6387 * @uses STDOUT
6388 * @param string $string ?
6389 * @param string $eol ?
6390 * @todo Finish documenting this function
6392 function mtrace($string, $eol="\n", $sleep=0) {
6394 if (defined('STDOUT')) {
6395 fwrite(STDOUT, $string.$eol);
6396 } else {
6397 echo $string . $eol;
6400 flush();
6402 //delay to keep message on user's screen in case of subsequent redirect
6403 if ($sleep) {
6404 sleep($sleep);
6408 //Replace 1 or more slashes or backslashes to 1 slash
6409 function cleardoubleslashes ($path) {
6410 return preg_replace('/(\/|\\\){1,}/','/',$path);
6413 function zip_files ($originalfiles, $destination) {
6414 //Zip an array of files/dirs to a destination zip file
6415 //Both parameters must be FULL paths to the files/dirs
6417 global $CFG;
6419 //Extract everything from destination
6420 $path_parts = pathinfo(cleardoubleslashes($destination));
6421 $destpath = $path_parts["dirname"]; //The path of the zip file
6422 $destfilename = $path_parts["basename"]; //The name of the zip file
6423 $extension = $path_parts["extension"]; //The extension of the file
6425 //If no file, error
6426 if (empty($destfilename)) {
6427 return false;
6430 //If no extension, add it
6431 if (empty($extension)) {
6432 $extension = 'zip';
6433 $destfilename = $destfilename.'.'.$extension;
6436 //Check destination path exists
6437 if (!is_dir($destpath)) {
6438 return false;
6441 //Check destination path is writable. TODO!!
6443 //Clean destination filename
6444 $destfilename = clean_filename($destfilename);
6446 //Now check and prepare every file
6447 $files = array();
6448 $origpath = NULL;
6450 foreach ($originalfiles as $file) { //Iterate over each file
6451 //Check for every file
6452 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6453 //Calculate the base path for all files if it isn't set
6454 if ($origpath === NULL) {
6455 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6457 //See if the file is readable
6458 if (!is_readable($tempfile)) { //Is readable
6459 continue;
6461 //See if the file/dir is in the same directory than the rest
6462 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6463 continue;
6465 //Add the file to the array
6466 $files[] = $tempfile;
6469 //Everything is ready:
6470 // -$origpath is the path where ALL the files to be compressed reside (dir).
6471 // -$destpath is the destination path where the zip file will go (dir).
6472 // -$files is an array of files/dirs to compress (fullpath)
6473 // -$destfilename is the name of the zip file (without path)
6475 //print_object($files); //Debug
6477 if (empty($CFG->zip)) { // Use built-in php-based zip function
6479 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6480 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6481 $zipfiles = array();
6482 $start = strlen($origpath)+1;
6483 foreach($files as $file) {
6484 $tf = array();
6485 $tf[PCLZIP_ATT_FILE_NAME] = $file;
6486 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME] = substr($file, $start);
6487 $zipfiles[] = $tf;
6489 //create the archive
6490 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6491 if (($list = $archive->create($zipfiles) == 0)) {
6492 notice($archive->errorInfo(true));
6493 return false;
6496 } else { // Use external zip program
6498 $filestozip = "";
6499 foreach ($files as $filetozip) {
6500 $filestozip .= escapeshellarg(basename($filetozip));
6501 $filestozip .= " ";
6503 //Construct the command
6504 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6505 $command = 'cd '.escapeshellarg($origpath).$separator.
6506 escapeshellarg($CFG->zip).' -r '.
6507 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6508 //All converted to backslashes in WIN
6509 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6510 $command = str_replace('/','\\',$command);
6512 Exec($command);
6514 return true;
6517 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6518 //Unzip one zip file to a destination dir
6519 //Both parameters must be FULL paths
6520 //If destination isn't specified, it will be the
6521 //SAME directory where the zip file resides.
6523 global $CFG;
6525 //Extract everything from zipfile
6526 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6527 $zippath = $path_parts["dirname"]; //The path of the zip file
6528 $zipfilename = $path_parts["basename"]; //The name of the zip file
6529 $extension = $path_parts["extension"]; //The extension of the file
6531 //If no file, error
6532 if (empty($zipfilename)) {
6533 return false;
6536 //If no extension, error
6537 if (empty($extension)) {
6538 return false;
6541 //Clear $zipfile
6542 $zipfile = cleardoubleslashes($zipfile);
6544 //Check zipfile exists
6545 if (!file_exists($zipfile)) {
6546 return false;
6549 //If no destination, passed let's go with the same directory
6550 if (empty($destination)) {
6551 $destination = $zippath;
6554 //Clear $destination
6555 $destpath = rtrim(cleardoubleslashes($destination), "/");
6557 //Check destination path exists
6558 if (!is_dir($destpath)) {
6559 return false;
6562 //Check destination path is writable. TODO!!
6564 //Everything is ready:
6565 // -$zippath is the path where the zip file resides (dir)
6566 // -$zipfilename is the name of the zip file (without path)
6567 // -$destpath is the destination path where the zip file will uncompressed (dir)
6569 $list = null;
6571 if (empty($CFG->unzip)) { // Use built-in php-based unzip function
6573 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6574 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6575 if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
6576 PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename',
6577 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $destpath)) {
6578 notice($archive->errorInfo(true));
6579 return false;
6582 } else { // Use external unzip program
6584 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6585 $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
6587 $command = 'cd '.escapeshellarg($zippath).$separator.
6588 escapeshellarg($CFG->unzip).' -o '.
6589 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6590 escapeshellarg($destpath).$redirection;
6591 //All converted to backslashes in WIN
6592 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6593 $command = str_replace('/','\\',$command);
6595 Exec($command,$list);
6598 //Display some info about the unzip execution
6599 if ($showstatus) {
6600 unzip_show_status($list,$destpath);
6603 return true;
6606 function unzip_cleanfilename ($p_event, &$p_header) {
6607 //This function is used as callback in unzip_file() function
6608 //to clean illegal characters for given platform and to prevent directory traversal.
6609 //Produces the same result as info-zip unzip.
6610 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6611 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6612 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6613 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6614 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6615 } else {
6616 //Add filtering for other systems here
6617 // BSD: none (tested)
6618 // Linux: ??
6619 // MacosX: ??
6621 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6622 return 1;
6625 function unzip_show_status ($list,$removepath) {
6626 //This function shows the results of the unzip execution
6627 //depending of the value of the $CFG->zip, results will be
6628 //text or an array of files.
6630 global $CFG;
6632 if (empty($CFG->unzip)) { // Use built-in php-based zip function
6633 $strname = get_string("name");
6634 $strsize = get_string("size");
6635 $strmodified = get_string("modified");
6636 $strstatus = get_string("status");
6637 echo "<table width=\"640\">";
6638 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6639 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6640 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6641 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6642 foreach ($list as $item) {
6643 echo "<tr>";
6644 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6645 print_cell("left", s($item['filename']));
6646 if (! $item['folder']) {
6647 print_cell("right", display_size($item['size']));
6648 } else {
6649 echo "<td>&nbsp;</td>";
6651 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6652 print_cell("right", $filedate);
6653 print_cell("right", $item['status']);
6654 echo "</tr>";
6656 echo "</table>";
6658 } else { // Use external zip program
6659 print_simple_box_start("center");
6660 echo "<pre>";
6661 foreach ($list as $item) {
6662 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6664 echo "</pre>";
6665 print_simple_box_end();
6670 * Returns most reliable client address
6672 * @return string The remote IP address
6674 function getremoteaddr() {
6675 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6676 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6678 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6679 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6681 if (!empty($_SERVER['REMOTE_ADDR'])) {
6682 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6684 return '';
6688 * Cleans a remote address ready to put into the log table
6690 function cleanremoteaddr($addr) {
6691 $originaladdr = $addr;
6692 $matches = array();
6693 // first get all things that look like IP addresses.
6694 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER)) {
6695 return '';
6697 $goodmatches = array();
6698 $lanmatches = array();
6699 foreach ($matches as $match) {
6700 // print_r($match);
6701 // check to make sure it's not an internal address.
6702 // the following are reserved for private lans...
6703 // 10.0.0.0 - 10.255.255.255
6704 // 172.16.0.0 - 172.31.255.255
6705 // 192.168.0.0 - 192.168.255.255
6706 // 169.254.0.0 -169.254.255.255
6707 $bits = explode('.',$match[0]);
6708 if (count($bits) != 4) {
6709 // weird, preg match shouldn't give us it.
6710 continue;
6712 if (($bits[0] == 10)
6713 || ($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6714 || ($bits[0] == 192 && $bits[1] == 168)
6715 || ($bits[0] == 169 && $bits[1] == 254)) {
6716 $lanmatches[] = $match[0];
6717 continue;
6719 // finally, it's ok
6720 $goodmatches[] = $match[0];
6722 if (!count($goodmatches)) {
6723 // perhaps we have a lan match, it's probably better to return that.
6724 if (!count($lanmatches)) {
6725 return '';
6726 } else {
6727 return array_pop($lanmatches);
6730 if (count($goodmatches) == 1) {
6731 return $goodmatches[0];
6733 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6734 // we need to return something, so
6735 return array_pop($goodmatches);
6739 * file_put_contents is only supported by php 5.0 and higher
6740 * so if it is not predefined, define it here
6742 * @param $file full path of the file to write
6743 * @param $contents contents to be sent
6744 * @return number of bytes written (false on error)
6746 if(!function_exists('file_put_contents')) {
6747 function file_put_contents($file, $contents) {
6748 $result = false;
6749 if ($f = fopen($file, 'w')) {
6750 $result = fwrite($f, $contents);
6751 fclose($f);
6753 return $result;
6758 * The clone keyword is only supported from PHP 5 onwards.
6759 * The behaviour of $obj2 = $obj1 differs fundamentally
6760 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6761 * created, in PHP 5 $obj1 is referenced. To create a copy
6762 * in PHP 5 the clone keyword was introduced. This function
6763 * simulates this behaviour for PHP < 5.0.0.
6764 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6766 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6767 * Found a better implementation (more checks and possibilities) from PEAR:
6768 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6770 * @param object $obj
6771 * @return object
6773 if(!check_php_version('5.0.0')) {
6774 // the eval is needed to prevent PHP 5 from getting a parse error!
6775 eval('
6776 function clone($obj) {
6777 /// Sanity check
6778 if (!is_object($obj)) {
6779 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6780 return;
6783 /// Use serialize/unserialize trick to deep copy the object
6784 $obj = unserialize(serialize($obj));
6786 /// If there is a __clone method call it on the "new" class
6787 if (method_exists($obj, \'__clone\')) {
6788 $obj->__clone();
6791 return $obj;
6794 // Supply the PHP5 function scandir() to older versions.
6795 function scandir($directory) {
6796 $files = array();
6797 if ($dh = opendir($directory)) {
6798 while (($file = readdir($dh)) !== false) {
6799 $files[] = $file;
6801 closedir($dh);
6803 return $files;
6806 // Supply the PHP5 function array_combine() to older versions.
6807 function array_combine($keys, $values) {
6808 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6809 return false;
6811 reset($values);
6812 $result = array();
6813 foreach ($keys as $key) {
6814 $result[$key] = current($values);
6815 next($values);
6817 return $result;
6823 * This function will make a complete copy of anything it's given,
6824 * regardless of whether it's an object or not.
6825 * @param mixed $thing
6826 * @return mixed
6828 function fullclone($thing) {
6829 return unserialize(serialize($thing));
6834 * This function expects to called during shutdown
6835 * should be set via register_shutdown_function()
6836 * in lib/setup.php .
6838 * Right now we do it only if we are under apache, to
6839 * make sure apache children that hog too much mem are
6840 * killed.
6843 function moodle_request_shutdown() {
6845 global $CFG;
6847 // initially, we are only ever called under apache
6848 // but check just in case
6849 if (function_exists('apache_child_terminate')
6850 && function_exists('memory_get_usage')
6851 && ini_get_bool('child_terminate')) {
6852 if (empty($CFG->apachemaxmem)) {
6853 $CFG->apachemaxmem = 25000000; // default 25MiB
6855 if (memory_get_usage() > (int)$CFG->apachemaxmem) {
6856 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
6857 @apache_child_terminate();
6860 if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
6861 if (defined('MDL_PERFTOLOG')) {
6862 $perf = get_performance_info();
6863 error_log("PERF: " . $perf['txt']);
6865 if (defined('MDL_PERFINC')) {
6866 $inc = get_included_files();
6867 $ts = 0;
6868 foreach($inc as $f) {
6869 if (preg_match(':^/:', $f)) {
6870 $fs = filesize($f);
6871 $ts += $fs;
6872 $hfs = display_size($fs);
6873 error_log(substr($f,strlen($CFG->dirroot)) . " size: $fs ($hfs)"
6874 , NULL, NULL, 0);
6875 } else {
6876 error_log($f , NULL, NULL, 0);
6879 if ($ts > 0 ) {
6880 $hts = display_size($ts);
6881 error_log("Total size of files included: $ts ($hts)");
6888 * If new messages are waiting for the current user, then return
6889 * Javascript code to create a popup window
6891 * @return string Javascript code
6893 function message_popup_window() {
6894 global $USER;
6896 $popuplimit = 30; // Minimum seconds between popups
6898 if (!defined('MESSAGE_WINDOW')) {
6899 if (isset($USER->id) and !isguestuser()) {
6900 if (!isset($USER->message_lastpopup)) {
6901 $USER->message_lastpopup = 0;
6903 if ((time() - $USER->message_lastpopup) > $popuplimit) { /// It's been long enough
6904 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6905 if (count_records_select('message', 'useridto = \''.$USER->id.'\' AND timecreated > \''.$USER->message_lastpopup.'\'')) {
6906 $USER->message_lastpopup = time();
6907 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6908 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6915 return '';
6918 // Used to make sure that $min <= $value <= $max
6919 function bounded_number($min, $value, $max) {
6920 if($value < $min) {
6921 return $min;
6923 if($value > $max) {
6924 return $max;
6926 return $value;
6929 function array_is_nested($array) {
6930 foreach ($array as $value) {
6931 if (is_array($value)) {
6932 return true;
6935 return false;
6939 *** get_performance_info() pairs up with init_performance_info()
6940 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6941 *** values ready for use, and each of the individual stats provided
6942 *** separately as well.
6945 function get_performance_info() {
6946 global $CFG, $PERF, $rcache;
6948 $info = array();
6949 $info['html'] = ''; // holds userfriendly HTML representation
6950 $info['txt'] = me() . ' '; // holds log-friendly representation
6952 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
6954 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6955 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6957 if (function_exists('memory_get_usage')) {
6958 $info['memory_total'] = memory_get_usage();
6959 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
6960 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6961 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6964 $inc = get_included_files();
6965 //error_log(print_r($inc,1));
6966 $info['includecount'] = count($inc);
6967 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6968 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6970 if (!empty($PERF->dbqueries)) {
6971 $info['dbqueries'] = $PERF->dbqueries;
6972 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6973 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6976 if (!empty($PERF->logwrites)) {
6977 $info['logwrites'] = $PERF->logwrites;
6978 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6979 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6982 if (!empty($PERF->profiling) && $PERF->profiling) {
6983 require_once($CFG->dirroot .'/lib/profilerlib.php');
6984 $info['html'] .= '<span class="profilinginfo">'.Profiler::get_profiling(array('-R')).'</span>';
6987 if (function_exists('posix_times')) {
6988 $ptimes = posix_times();
6989 if (is_array($ptimes)) {
6990 foreach ($ptimes as $key => $val) {
6991 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
6993 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6994 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6998 // Grab the load average for the last minute
6999 // /proc will only work under some linux configurations
7000 // while uptime is there under MacOSX/Darwin and other unices
7001 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
7002 list($server_load) = explode(' ', $loadavg[0]);
7003 unset($loadavg);
7004 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
7005 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
7006 $server_load = $matches[1];
7007 } else {
7008 trigger_error('Could not parse uptime output!');
7011 if (!empty($server_load)) {
7012 $info['serverload'] = $server_load;
7013 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
7014 $info['txt'] .= "serverload: {$info['serverload']} ";
7017 if (isset($rcache->hits) && isset($rcache->misses)) {
7018 $info['rcachehits'] = $rcache->hits;
7019 $info['rcachemisses'] = $rcache->misses;
7020 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
7021 "{$rcache->hits}/{$rcache->misses}</span> ";
7022 $info['txt'] .= 'rcache: '.
7023 "{$rcache->hits}/{$rcache->misses} ";
7025 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
7026 return $info;
7029 function apd_get_profiling() {
7030 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
7033 function remove_dir($dir, $content_only=false) {
7034 // if content_only=true then delete all but
7035 // the directory itself
7037 $handle = opendir($dir);
7038 while (false!==($item = readdir($handle))) {
7039 if($item != '.' && $item != '..') {
7040 if(is_dir($dir.'/'.$item)) {
7041 remove_dir($dir.'/'.$item);
7042 }else{
7043 unlink($dir.'/'.$item);
7047 closedir($handle);
7048 if ($content_only) {
7049 return true;
7051 return rmdir($dir);
7055 * Function to check if a directory exists and optionally create it.
7057 * @param string absolute directory path
7058 * @param boolean create directory if does not exist
7059 * @param boolean create directory recursively
7061 * @return boolean true if directory exists or created
7063 function check_dir_exists($dir, $create=false, $recursive=false) {
7065 global $CFG;
7067 $status = true;
7069 if(!is_dir($dir)) {
7070 if (!$create) {
7071 $status = false;
7072 } else {
7073 umask(0000);
7074 if ($recursive) {
7075 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
7076 $dir = str_replace('\\', '/', $dir); //windows compatibility
7077 $dirs = explode('/', $dir);
7078 $dir = array_shift($dirs).'/'; //skip root or drive letter
7079 foreach ($dirs as $part) {
7080 if ($part == '') {
7081 continue;
7083 $dir .= $part.'/';
7084 if (!is_dir($dir)) {
7085 if (!mkdir($dir, $CFG->directorypermissions)) {
7086 $status = false;
7087 break;
7091 } else {
7092 $status = mkdir($dir, $CFG->directorypermissions);
7096 return $status;
7099 function report_session_error() {
7100 global $CFG, $FULLME;
7102 if (empty($CFG->lang)) {
7103 $CFG->lang = "en";
7105 // Set up default theme and locale
7106 theme_setup();
7107 moodle_setlocale();
7109 //clear session cookies
7110 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
7111 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
7112 //increment database error counters
7113 if (isset($CFG->session_error_counter)) {
7114 set_config('session_error_counter', 1 + $CFG->session_error_counter);
7115 } else {
7116 set_config('session_error_counter', 1);
7118 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
7123 * Detect if an object or a class contains a given property
7124 * will take an actual object or the name of a class
7125 * @param mix $obj Name of class or real object to test
7126 * @param string $property name of property to find
7127 * @return bool true if property exists
7129 function object_property_exists( $obj, $property ) {
7130 if (is_string( $obj )) {
7131 $properties = get_class_vars( $obj );
7133 else {
7134 $properties = get_object_vars( $obj );
7136 return array_key_exists( $property, $properties );
7141 * Detect a custom script replacement in the data directory that will
7142 * replace an existing moodle script
7143 * @param string $urlpath path to the original script
7144 * @return string full path name if a custom script exists
7145 * @return bool false if no custom script exists
7147 function custom_script_path($urlpath='') {
7148 global $CFG;
7150 // set default $urlpath, if necessary
7151 if (empty($urlpath)) {
7152 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
7155 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
7156 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot) === false )) {
7157 return false;
7160 // replace wwwroot with the path to the customscripts folder and clean path
7161 $scriptpath = $CFG->customscripts . clean_param(substr($urlpath, strlen($CFG->wwwroot)), PARAM_PATH);
7163 // remove the query string, if any
7164 if (($strpos = strpos($scriptpath, '?')) !== false) {
7165 $scriptpath = substr($scriptpath, 0, $strpos);
7168 // remove trailing slashes, if any
7169 $scriptpath = rtrim($scriptpath, '/\\');
7171 // append index.php, if necessary
7172 if (is_dir($scriptpath)) {
7173 $scriptpath .= '/index.php';
7176 // check the custom script exists
7177 if (file_exists($scriptpath)) {
7178 return $scriptpath;
7179 } else {
7180 return false;
7185 * Wrapper function to load necessary editor scripts
7186 * to $CFG->editorsrc array. Params can be coursei id
7187 * or associative array('courseid' => value, 'name' => 'editorname').
7188 * @uses $CFG
7189 * @param mixed $args Courseid or associative array.
7191 function loadeditor($args) {
7192 global $CFG;
7193 include($CFG->libdir .'/editorlib.php');
7194 return editorObject::loadeditor($args);
7198 * Returns whether or not the user object is a remote MNET user. This function
7199 * is in moodlelib because it does not rely on loading any of the MNET code.
7201 * @param object $user A valid user object
7202 * @return bool True if the user is from a remote Moodle.
7204 function is_mnet_remote_user($user) {
7205 global $CFG;
7207 if (!isset($CFG->mnet_localhost_id)) {
7208 include_once $CFG->dirroot . '/mnet/lib.php';
7209 $env = new mnet_environment();
7210 $env->init();
7211 unset($env);
7214 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
7218 * Checks if a given plugin is in the list of enabled enrolment plugins.
7220 * @param string $auth Enrolment plugin.
7221 * @return boolean Whether the plugin is enabled.
7223 function is_enabled_enrol($enrol='') {
7224 global $CFG;
7226 // use the global default if not specified
7227 if ($enrol == '') {
7228 $enrol = $CFG->enrol;
7230 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
7234 * This function will search for browser prefereed languages, setting Moodle
7235 * to use the best one available if $SESSION->lang is undefined
7237 function setup_lang_from_browser() {
7239 global $CFG, $SESSION, $USER;
7241 if (!empty($SESSION->lang) or !empty($USER->lang)) {
7242 // Lang is defined in session or user profile, nothing to do
7243 return;
7246 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
7247 return;
7250 /// Extract and clean langs from headers
7251 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
7252 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
7253 $rawlangs = explode(',', $rawlangs); // Convert to array
7254 $langs = array();
7256 $order = 1.0;
7257 foreach ($rawlangs as $lang) {
7258 if (strpos($lang, ';') === false) {
7259 $langs[(string)$order] = $lang;
7260 $order = $order-0.01;
7261 } else {
7262 $parts = explode(';', $lang);
7263 $pos = strpos($parts[1], '=');
7264 $langs[substr($parts[1], $pos+1)] = $parts[0];
7267 krsort($langs, SORT_NUMERIC);
7269 $langlist = get_list_of_languages();
7271 /// Look for such langs under standard locations
7272 foreach ($langs as $lang) {
7273 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR)); // clean it properly for include
7274 if (!array_key_exists($lang, $langlist)) {
7275 continue; // language not allowed, try next one
7277 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
7278 $SESSION->lang = $lang; /// Lang exists, set it in session
7279 break; /// We have finished. Go out
7282 return;
7286 ////////////////////////////////////////////////////////////////////////////////
7288 function is_newnav($navigation) {
7289 if (is_array($navigation) && !empty($navigation['newnav'])) {
7290 return true;
7291 } else {
7292 return false;
7297 * Checks whether the given variable name is defined as a variable within the given object.
7298 * @note This will NOT work with stdClass objects, which have no class variables.
7299 * @param string $var The variable name
7300 * @param object $object The object to check
7301 * @return boolean
7303 function in_object_vars($var, $object) {
7304 $class_vars = get_class_vars(get_class($object));
7305 $class_vars = array_keys($class_vars);
7306 return in_array($var, $class_vars);
7310 * Returns an array without repeated objects.
7311 * This function is similar to array_unique, but for arrays that have objects as values
7313 * @param unknown_type $array
7314 * @param unknown_type $keep_key_assoc
7315 * @return unknown
7317 function object_array_unique($array, $keep_key_assoc = true) {
7318 $duplicate_keys = array();
7319 $tmp = array();
7321 foreach ($array as $key=>$val) {
7322 // convert objects to arrays, in_array() does not support objects
7323 if (is_object($val)) {
7324 $val = (array)$val;
7327 if (!in_array($val, $tmp)) {
7328 $tmp[] = $val;
7329 } else {
7330 $duplicate_keys[] = $key;
7334 foreach ($duplicate_keys as $key) {
7335 unset($array[$key]);
7338 return $keep_key_assoc ? $array : array_values($array);
7341 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: