MDL-10234
[moodle-linuxchix.git] / lib / moodlelib.php
blob90c00a7363bcceb457de784e25e775b7af109af9
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 /**
47 * No groups used?
49 define('NOGROUPS', 0);
51 /**
52 * Groups used?
54 define('SEPARATEGROUPS', 1);
56 /**
57 * Groups visible?
59 define('VISIBLEGROUPS', 2);
61 /// Date and time constants ///
62 /**
63 * Time constant - the number of seconds in a year
66 define('YEARSECS', 31536000);
68 /**
69 * Time constant - the number of seconds in a week
71 define('WEEKSECS', 604800);
73 /**
74 * Time constant - the number of seconds in a day
76 define('DAYSECS', 86400);
78 /**
79 * Time constant - the number of seconds in an hour
81 define('HOURSECS', 3600);
83 /**
84 * Time constant - the number of seconds in a minute
86 define('MINSECS', 60);
88 /**
89 * Time constant - the number of minutes in a day
91 define('DAYMINS', 1440);
93 /**
94 * Time constant - the number of minutes in an hour
96 define('HOURMINS', 60);
98 /// Parameter constants - every call to optional_param(), required_param() ///
99 /// or clean_param() should have a specified type of parameter. //////////////
102 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
103 * originally was 0, but changed because we need to detect unknown
104 * parameter types and swiched order in clean_param().
106 define('PARAM_RAW', 666);
109 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
110 * It was one of the first types, that is why it is abused so much ;-)
112 define('PARAM_CLEAN', 0x0001);
115 * PARAM_INT - integers only, use when expecting only numbers.
117 define('PARAM_INT', 0x0002);
120 * PARAM_INTEGER - an alias for PARAM_INT
122 define('PARAM_INTEGER', 0x0002);
125 * PARAM_NUMBER - a real/floating point number.
127 define('PARAM_NUMBER', 0x000a);
130 * PARAM_ALPHA - contains only english letters.
132 define('PARAM_ALPHA', 0x0004);
135 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
136 * @TODO: should we alias it to PARAM_ALPHANUM ?
138 define('PARAM_ACTION', 0x0004);
141 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
142 * @TODO: should we alias it to PARAM_ALPHANUM ?
144 define('PARAM_FORMAT', 0x0004);
147 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
149 define('PARAM_NOTAGS', 0x0008);
152 * PARAM_MULTILANG - alias of PARAM_TEXT.
154 define('PARAM_MULTILANG', 0x0009);
157 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
159 define('PARAM_TEXT', 0x0009);
162 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
164 define('PARAM_FILE', 0x0010);
167 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
168 * note: the leading slash is not removed, window drive letter is not allowed
170 define('PARAM_PATH', 0x0020);
173 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
175 define('PARAM_HOST', 0x0040);
178 * PARAM_URL - expected properly formatted URL.
180 define('PARAM_URL', 0x0080);
183 * 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!)
185 define('PARAM_LOCALURL', 0x0180);
188 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
189 * use when you want to store a new file submitted by students
191 define('PARAM_CLEANFILE',0x0200);
194 * PARAM_ALPHANUM - expected numbers and letters only.
196 define('PARAM_ALPHANUM', 0x0400);
199 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
201 define('PARAM_BOOL', 0x0800);
204 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
205 * note: do not forget to addslashes() before storing into database!
207 define('PARAM_CLEANHTML',0x1000);
210 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
211 * suitable for include() and require()
212 * @TODO: should we rename this function to PARAM_SAFEDIRS??
214 define('PARAM_ALPHAEXT', 0x2000);
217 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
219 define('PARAM_SAFEDIR', 0x4000);
222 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
224 define('PARAM_SEQUENCE', 0x8000);
227 * PARAM_PEM - Privacy Enhanced Mail format
229 define('PARAM_PEM', 0x10000);
232 * PARAM_BASE64 - Base 64 encoded format
234 define('PARAM_BASE64', 0x20000);
237 /// Page types ///
239 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
241 define('PAGE_COURSE_VIEW', 'course-view');
243 /// Debug levels ///
244 /** no warnings at all */
245 define ('DEBUG_NONE', 0);
246 /** E_ERROR | E_PARSE */
247 define ('DEBUG_MINIMAL', 5);
248 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
249 define ('DEBUG_NORMAL', 15);
250 /** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
251 define ('DEBUG_ALL', 2047);
252 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
253 define ('DEBUG_DEVELOPER', 34815);
256 * Blog access level constant declaration
258 define ('BLOG_USER_LEVEL', 1);
259 define ('BLOG_GROUP_LEVEL', 2);
260 define ('BLOG_COURSE_LEVEL', 3);
261 define ('BLOG_SITE_LEVEL', 4);
262 define ('BLOG_GLOBAL_LEVEL', 5);
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;
503 case PARAM_PEM:
504 $param = trim($param);
505 // PEM formatted strings may contain letters/numbers and the symbols
506 // forward slash: /
507 // plus sign: +
508 // equal sign: =
509 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
510 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
511 list($wholething, $body) = $matches;
512 unset($wholething, $matches);
513 $b64 = clean_param($body, PARAM_BASE64);
514 if (!empty($b64)) {
515 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
516 } else {
517 return '';
520 return '';
521 case PARAM_BASE64:
522 if (!empty($param)) {
523 // PEM formatted strings may contain letters/numbers and the symbols
524 // forward slash: /
525 // plus sign: +
526 // equal sign: =
527 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
528 return '';
530 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
531 // Each line of base64 encoded data must be 64 characters in
532 // length, except for the last line which may be less than (or
533 // equal to) 64 characters long.
534 for ($i=0, $j=count($lines); $i < $j; $i++) {
535 if ($i + 1 == $j) {
536 if (64 < strlen($lines[$i])) {
537 return '';
539 continue;
542 if (64 != strlen($lines[$i])) {
543 return '';
546 return implode("\n",$lines);
547 } else {
548 return '';
550 default: // throw error, switched parameters in optional_param or another serious problem
551 error("Unknown parameter type: $type");
558 * Set a key in global configuration
560 * Set a key/value pair in both this session's {@link $CFG} global variable
561 * and in the 'config' database table for future sessions.
563 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
564 * In that case it doesn't affect $CFG.
566 * @param string $name the key to set
567 * @param string $value the value to set (without magic quotes)
568 * @param string $plugin (optional) the plugin scope
569 * @uses $CFG
570 * @return bool
572 function set_config($name, $value, $plugin=NULL) {
573 /// No need for get_config because they are usually always available in $CFG
575 global $CFG;
577 if (empty($plugin)) {
578 $CFG->$name = $value; // So it's defined for this invocation at least
580 if (get_field('config', 'name', 'name', $name)) {
581 return set_field('config', 'value', addslashes($value), 'name', $name);
582 } else {
583 $config = new object();
584 $config->name = $name;
585 $config->value = addslashes($value);
586 return insert_record('config', $config);
588 } else { // plugin scope
589 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
590 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
591 } else {
592 $config = new object();
593 $config->plugin = addslashes($plugin);
594 $config->name = $name;
595 $config->value = addslashes($value);
596 return insert_record('config_plugins', $config);
602 * Get configuration values from the global config table
603 * or the config_plugins table.
605 * If called with no parameters it will do the right thing
606 * generating $CFG safely from the database without overwriting
607 * existing values.
609 * If called with 2 parameters it will return a $string single
610 * value or false of the value is not found.
612 * @param string $plugin
613 * @param string $name
614 * @uses $CFG
615 * @return hash-like object or single value
618 function get_config($plugin=NULL, $name=NULL) {
620 global $CFG;
622 if (!empty($name)) { // the user is asking for a specific value
623 if (!empty($plugin)) {
624 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
625 } else {
626 return get_field('config', 'value', 'name', $name);
630 // the user is after a recordset
631 if (!empty($plugin)) {
632 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
633 $configs = (array)$configs;
634 $localcfg = array();
635 foreach ($configs as $config) {
636 $localcfg[$config->name] = $config->value;
638 return (object)$localcfg;
639 } else {
640 return false;
642 } else {
643 // this was originally in setup.php
644 if ($configs = get_records('config')) {
645 $localcfg = (array)$CFG;
646 foreach ($configs as $config) {
647 if (!isset($localcfg[$config->name])) {
648 $localcfg[$config->name] = $config->value;
649 } else {
650 if ($localcfg[$config->name] != $config->value ) {
651 // complain if the DB has a different
652 // value than config.php does
653 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
658 $localcfg = (object)$localcfg;
659 return $localcfg;
660 } else {
661 // preserve $CFG if DB returns nothing or error
662 return $CFG;
669 * Removes a key from global configuration
671 * @param string $name the key to set
672 * @param string $plugin (optional) the plugin scope
673 * @uses $CFG
674 * @return bool
676 function unset_config($name, $plugin=NULL) {
678 global $CFG;
680 unset($CFG->$name);
682 if (empty($plugin)) {
683 return delete_records('config', 'name', $name);
684 } else {
685 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
691 * Refresh current $USER session global variable with all their current preferences.
692 * @uses $USER
694 function reload_user_preferences() {
696 global $USER;
698 //reset preference
699 $USER->preference = array();
701 if (!isloggedin() or isguestuser()) {
702 // no pernament storage for not-logged-in user and guest
704 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
705 foreach ($preferences as $preference) {
706 $USER->preference[$preference->name] = $preference->value;
710 return true;
714 * Sets a preference for the current user
715 * Optionally, can set a preference for a different user object
716 * @uses $USER
717 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
719 * @param string $name The key to set as preference for the specified user
720 * @param string $value The value to set forthe $name key in the specified user's record
721 * @param int $otheruserid A moodle user ID
722 * @return bool
724 function set_user_preference($name, $value, $otheruserid=NULL) {
726 global $USER;
728 if (!isset($USER->preference)) {
729 reload_user_preferences();
732 if (empty($name)) {
733 return false;
736 $nostore = false;
738 if (empty($otheruserid)){
739 if (!isloggedin() or isguestuser()) {
740 $nostore = true;
742 $userid = $USER->id;
743 } else {
744 if (isguestuser($otheruserid)) {
745 $nostore = true;
747 $userid = $otheruserid;
750 $return = true;
751 if ($nostore) {
752 // no pernament storage for not-logged-in user and guest
754 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
755 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
756 $return = false;
759 } else {
760 $preference = new object();
761 $preference->userid = $userid;
762 $preference->name = addslashes($name);
763 $preference->value = addslashes((string)$value);
764 if (!insert_record('user_preferences', $preference)) {
765 $return = false;
769 // update value in USER session if needed
770 if ($userid == $USER->id) {
771 $USER->preference[$name] = (string)$value;
774 return $return;
778 * Unsets a preference completely by deleting it from the database
779 * Optionally, can set a preference for a different user id
780 * @uses $USER
781 * @param string $name The key to unset as preference for the specified user
782 * @param int $otheruserid A moodle user ID
784 function unset_user_preference($name, $otheruserid=NULL) {
786 global $USER;
788 if (!isset($USER->preference)) {
789 reload_user_preferences();
792 if (empty($otheruserid)){
793 $userid = $USER->id;
794 } else {
795 $userid = $otheruserid;
798 //Delete the preference from $USER if needed
799 if ($userid == $USER->id) {
800 unset($USER->preference[$name]);
803 //Then from DB
804 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
809 * Sets a whole array of preferences for the current user
810 * @param array $prefarray An array of key/value pairs to be set
811 * @param int $otheruserid A moodle user ID
812 * @return bool
814 function set_user_preferences($prefarray, $otheruserid=NULL) {
816 if (!is_array($prefarray) or empty($prefarray)) {
817 return false;
820 $return = true;
821 foreach ($prefarray as $name => $value) {
822 // The order is important; test for return is done first
823 $return = (set_user_preference($name, $value, $otheruserid) && $return);
825 return $return;
829 * If no arguments are supplied this function will return
830 * all of the current user preferences as an array.
831 * If a name is specified then this function
832 * attempts to return that particular preference value. If
833 * none is found, then the optional value $default is returned,
834 * otherwise NULL.
835 * @param string $name Name of the key to use in finding a preference value
836 * @param string $default Value to be returned if the $name key is not set in the user preferences
837 * @param int $otheruserid A moodle user ID
838 * @uses $USER
839 * @return string
841 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
842 global $USER;
844 if (!isset($USER->preference)) {
845 reload_user_preferences();
848 if (empty($otheruserid)){
849 $userid = $USER->id;
850 } else {
851 $userid = $otheruserid;
854 if ($userid == $USER->id) {
855 $preference = $USER->preference;
857 } else {
858 $preference = array();
859 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
860 foreach ($prefdata as $pref) {
861 $preference[$pref->name] = $pref->value;
866 if (empty($name)) {
867 return $preference; // All values
869 } else if (array_key_exists($name, $preference)) {
870 return $preference[$name]; // The single value
872 } else {
873 return $default; // Default value (or NULL)
878 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
881 * Given date parts in user time produce a GMT timestamp.
883 * @param int $year The year part to create timestamp of
884 * @param int $month The month part to create timestamp of
885 * @param int $day The day part to create timestamp of
886 * @param int $hour The hour part to create timestamp of
887 * @param int $minute The minute part to create timestamp of
888 * @param int $second The second part to create timestamp of
889 * @param float $timezone ?
890 * @param bool $applydst ?
891 * @return int timestamp
892 * @todo Finish documenting this function
894 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
896 $timezone = get_user_timezone_offset($timezone);
898 if (abs($timezone) > 13) {
899 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
900 } else {
901 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
902 $time = usertime($time, $timezone);
903 if($applydst) {
904 $time -= dst_offset_on($time);
908 return $time;
913 * Given an amount of time in seconds, returns string
914 * formatted nicely as weeks, days, hours etc as needed
916 * @uses MINSECS
917 * @uses HOURSECS
918 * @uses DAYSECS
919 * @uses YEARSECS
920 * @param int $totalsecs ?
921 * @param array $str ?
922 * @return string
924 function format_time($totalsecs, $str=NULL) {
926 $totalsecs = abs($totalsecs);
928 if (!$str) { // Create the str structure the slow way
929 $str->day = get_string('day');
930 $str->days = get_string('days');
931 $str->hour = get_string('hour');
932 $str->hours = get_string('hours');
933 $str->min = get_string('min');
934 $str->mins = get_string('mins');
935 $str->sec = get_string('sec');
936 $str->secs = get_string('secs');
937 $str->year = get_string('year');
938 $str->years = get_string('years');
942 $years = floor($totalsecs/YEARSECS);
943 $remainder = $totalsecs - ($years*YEARSECS);
944 $days = floor($remainder/DAYSECS);
945 $remainder = $totalsecs - ($days*DAYSECS);
946 $hours = floor($remainder/HOURSECS);
947 $remainder = $remainder - ($hours*HOURSECS);
948 $mins = floor($remainder/MINSECS);
949 $secs = $remainder - ($mins*MINSECS);
951 $ss = ($secs == 1) ? $str->sec : $str->secs;
952 $sm = ($mins == 1) ? $str->min : $str->mins;
953 $sh = ($hours == 1) ? $str->hour : $str->hours;
954 $sd = ($days == 1) ? $str->day : $str->days;
955 $sy = ($years == 1) ? $str->year : $str->years;
957 $oyears = '';
958 $odays = '';
959 $ohours = '';
960 $omins = '';
961 $osecs = '';
963 if ($years) $oyears = $years .' '. $sy;
964 if ($days) $odays = $days .' '. $sd;
965 if ($hours) $ohours = $hours .' '. $sh;
966 if ($mins) $omins = $mins .' '. $sm;
967 if ($secs) $osecs = $secs .' '. $ss;
969 if ($years) return trim($oyears .' '. $odays);
970 if ($days) return trim($odays .' '. $ohours);
971 if ($hours) return trim($ohours .' '. $omins);
972 if ($mins) return trim($omins .' '. $osecs);
973 if ($secs) return $osecs;
974 return get_string('now');
978 * Returns a formatted string that represents a date in user time
979 * <b>WARNING: note that the format is for strftime(), not date().</b>
980 * Because of a bug in most Windows time libraries, we can't use
981 * the nicer %e, so we have to use %d which has leading zeroes.
982 * A lot of the fuss in the function is just getting rid of these leading
983 * zeroes as efficiently as possible.
985 * If parameter fixday = true (default), then take off leading
986 * zero from %d, else mantain it.
988 * @uses HOURSECS
989 * @param int $date timestamp in GMT
990 * @param string $format strftime format
991 * @param float $timezone
992 * @param bool $fixday If true (default) then the leading
993 * zero from %d is removed. If false then the leading zero is mantained.
994 * @return string
996 function userdate($date, $format='', $timezone=99, $fixday = true) {
998 global $CFG;
1000 if (empty($format)) {
1001 $format = get_string('strftimedaydatetime');
1004 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1005 $fixday = false;
1006 } else if ($fixday) {
1007 $formatnoday = str_replace('%d', 'DD', $format);
1008 $fixday = ($formatnoday != $format);
1011 $date += dst_offset_on($date);
1013 $timezone = get_user_timezone_offset($timezone);
1015 if (abs($timezone) > 13) { /// Server time
1016 if ($fixday) {
1017 $datestring = strftime($formatnoday, $date);
1018 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1019 $datestring = str_replace('DD', $daystring, $datestring);
1020 } else {
1021 $datestring = strftime($format, $date);
1023 } else {
1024 $date += (int)($timezone * 3600);
1025 if ($fixday) {
1026 $datestring = gmstrftime($formatnoday, $date);
1027 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1028 $datestring = str_replace('DD', $daystring, $datestring);
1029 } else {
1030 $datestring = gmstrftime($format, $date);
1034 /// If we are running under Windows convert from windows encoding to UTF-8
1035 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1037 if ($CFG->ostype == 'WINDOWS') {
1038 if ($localewincharset = get_string('localewincharset')) {
1039 $textlib = textlib_get_instance();
1040 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1044 return $datestring;
1048 * Given a $time timestamp in GMT (seconds since epoch),
1049 * returns an array that represents the date in user time
1051 * @uses HOURSECS
1052 * @param int $time Timestamp in GMT
1053 * @param float $timezone ?
1054 * @return array An array that represents the date in user time
1055 * @todo Finish documenting this function
1057 function usergetdate($time, $timezone=99) {
1059 $timezone = get_user_timezone_offset($timezone);
1061 if (abs($timezone) > 13) { // Server time
1062 return getdate($time);
1065 // There is no gmgetdate so we use gmdate instead
1066 $time += dst_offset_on($time);
1067 $time += intval((float)$timezone * HOURSECS);
1069 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1071 list(
1072 $getdate['seconds'],
1073 $getdate['minutes'],
1074 $getdate['hours'],
1075 $getdate['mday'],
1076 $getdate['mon'],
1077 $getdate['year'],
1078 $getdate['wday'],
1079 $getdate['yday'],
1080 $getdate['weekday'],
1081 $getdate['month']
1082 ) = explode('_', $datestring);
1084 return $getdate;
1088 * Given a GMT timestamp (seconds since epoch), offsets it by
1089 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1091 * @uses HOURSECS
1092 * @param int $date Timestamp in GMT
1093 * @param float $timezone
1094 * @return int
1096 function usertime($date, $timezone=99) {
1098 $timezone = get_user_timezone_offset($timezone);
1100 if (abs($timezone) > 13) {
1101 return $date;
1103 return $date - (int)($timezone * HOURSECS);
1107 * Given a time, return the GMT timestamp of the most recent midnight
1108 * for the current user.
1110 * @param int $date Timestamp in GMT
1111 * @param float $timezone ?
1112 * @return ?
1114 function usergetmidnight($date, $timezone=99) {
1116 $timezone = get_user_timezone_offset($timezone);
1117 $userdate = usergetdate($date, $timezone);
1119 // Time of midnight of this user's day, in GMT
1120 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1125 * Returns a string that prints the user's timezone
1127 * @param float $timezone The user's timezone
1128 * @return string
1130 function usertimezone($timezone=99) {
1132 $tz = get_user_timezone($timezone);
1134 if (!is_float($tz)) {
1135 return $tz;
1138 if(abs($tz) > 13) { // Server time
1139 return get_string('serverlocaltime');
1142 if($tz == intval($tz)) {
1143 // Don't show .0 for whole hours
1144 $tz = intval($tz);
1147 if($tz == 0) {
1148 return 'GMT';
1150 else if($tz > 0) {
1151 return 'GMT+'.$tz;
1153 else {
1154 return 'GMT'.$tz;
1160 * Returns a float which represents the user's timezone difference from GMT in hours
1161 * Checks various settings and picks the most dominant of those which have a value
1163 * @uses $CFG
1164 * @uses $USER
1165 * @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
1166 * @return int
1168 function get_user_timezone_offset($tz = 99) {
1170 global $USER, $CFG;
1172 $tz = get_user_timezone($tz);
1174 if (is_float($tz)) {
1175 return $tz;
1176 } else {
1177 $tzrecord = get_timezone_record($tz);
1178 if (empty($tzrecord)) {
1179 return 99.0;
1181 return (float)$tzrecord->gmtoff / HOURMINS;
1186 * Returns a float or a string which denotes the user's timezone
1187 * 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)
1188 * means that for this timezone there are also DST rules to be taken into account
1189 * Checks various settings and picks the most dominant of those which have a value
1191 * @uses $USER
1192 * @uses $CFG
1193 * @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
1194 * @return mixed
1196 function get_user_timezone($tz = 99) {
1197 global $USER, $CFG;
1199 $timezones = array(
1200 $tz,
1201 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1202 isset($USER->timezone) ? $USER->timezone : 99,
1203 isset($CFG->timezone) ? $CFG->timezone : 99,
1206 $tz = 99;
1208 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1209 $tz = $next['value'];
1212 return is_numeric($tz) ? (float) $tz : $tz;
1218 * @uses $CFG
1219 * @uses $db
1220 * @param string $timezonename ?
1221 * @return object
1223 function get_timezone_record($timezonename) {
1224 global $CFG, $db;
1225 static $cache = NULL;
1227 if ($cache === NULL) {
1228 $cache = array();
1231 if (isset($cache[$timezonename])) {
1232 return $cache[$timezonename];
1235 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1236 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1242 * @uses $CFG
1243 * @uses $USER
1244 * @param ? $fromyear ?
1245 * @param ? $to_year ?
1246 * @return bool
1248 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1249 global $CFG, $SESSION;
1251 $usertz = get_user_timezone();
1253 if (is_float($usertz)) {
1254 // Trivial timezone, no DST
1255 return false;
1258 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1259 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1260 unset($SESSION->dst_offsets);
1261 unset($SESSION->dst_range);
1264 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1265 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1266 // This will be the return path most of the time, pretty light computationally
1267 return true;
1270 // Reaching here means we either need to extend our table or create it from scratch
1272 // Remember which TZ we calculated these changes for
1273 $SESSION->dst_offsettz = $usertz;
1275 if(empty($SESSION->dst_offsets)) {
1276 // If we 're creating from scratch, put the two guard elements in there
1277 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1279 if(empty($SESSION->dst_range)) {
1280 // If creating from scratch
1281 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1282 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1284 // Fill in the array with the extra years we need to process
1285 $yearstoprocess = array();
1286 for($i = $from; $i <= $to; ++$i) {
1287 $yearstoprocess[] = $i;
1290 // Take note of which years we have processed for future calls
1291 $SESSION->dst_range = array($from, $to);
1293 else {
1294 // If needing to extend the table, do the same
1295 $yearstoprocess = array();
1297 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1298 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1300 if($from < $SESSION->dst_range[0]) {
1301 // Take note of which years we need to process and then note that we have processed them for future calls
1302 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1303 $yearstoprocess[] = $i;
1305 $SESSION->dst_range[0] = $from;
1307 if($to > $SESSION->dst_range[1]) {
1308 // Take note of which years we need to process and then note that we have processed them for future calls
1309 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1310 $yearstoprocess[] = $i;
1312 $SESSION->dst_range[1] = $to;
1316 if(empty($yearstoprocess)) {
1317 // This means that there was a call requesting a SMALLER range than we have already calculated
1318 return true;
1321 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1322 // Also, the array is sorted in descending timestamp order!
1324 // Get DB data
1325 $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');
1326 if(empty($presetrecords)) {
1327 return false;
1330 // Remove ending guard (first element of the array)
1331 reset($SESSION->dst_offsets);
1332 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1334 // Add all required change timestamps
1335 foreach($yearstoprocess as $y) {
1336 // Find the record which is in effect for the year $y
1337 foreach($presetrecords as $year => $preset) {
1338 if($year <= $y) {
1339 break;
1343 $changes = dst_changes_for_year($y, $preset);
1345 if($changes === NULL) {
1346 continue;
1348 if($changes['dst'] != 0) {
1349 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1351 if($changes['std'] != 0) {
1352 $SESSION->dst_offsets[$changes['std']] = 0;
1356 // Put in a guard element at the top
1357 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1358 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1360 // Sort again
1361 krsort($SESSION->dst_offsets);
1363 return true;
1366 function dst_changes_for_year($year, $timezone) {
1368 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1369 return NULL;
1372 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1373 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1375 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1376 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1378 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1379 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1381 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1382 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1383 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1385 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1386 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1388 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1391 // $time must NOT be compensated at all, it has to be a pure timestamp
1392 function dst_offset_on($time) {
1393 global $SESSION;
1395 if(!calculate_user_dst_table() || empty($SESSION->dst_offsets)) {
1396 return 0;
1399 reset($SESSION->dst_offsets);
1400 while(list($from, $offset) = each($SESSION->dst_offsets)) {
1401 if($from <= $time) {
1402 break;
1406 // This is the normal return path
1407 if($offset !== NULL) {
1408 return $offset;
1411 // Reaching this point means we haven't calculated far enough, do it now:
1412 // Calculate extra DST changes if needed and recurse. The recursion always
1413 // moves toward the stopping condition, so will always end.
1415 if($from == 0) {
1416 // We need a year smaller than $SESSION->dst_range[0]
1417 if($SESSION->dst_range[0] == 1971) {
1418 return 0;
1420 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL);
1421 return dst_offset_on($time);
1423 else {
1424 // We need a year larger than $SESSION->dst_range[1]
1425 if($SESSION->dst_range[1] == 2035) {
1426 return 0;
1428 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5);
1429 return dst_offset_on($time);
1433 function find_day_in_month($startday, $weekday, $month, $year) {
1435 $daysinmonth = days_in_month($month, $year);
1437 if($weekday == -1) {
1438 // Don't care about weekday, so return:
1439 // abs($startday) if $startday != -1
1440 // $daysinmonth otherwise
1441 return ($startday == -1) ? $daysinmonth : abs($startday);
1444 // From now on we 're looking for a specific weekday
1446 // Give "end of month" its actual value, since we know it
1447 if($startday == -1) {
1448 $startday = -1 * $daysinmonth;
1451 // Starting from day $startday, the sign is the direction
1453 if($startday < 1) {
1455 $startday = abs($startday);
1456 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1458 // This is the last such weekday of the month
1459 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1460 if($lastinmonth > $daysinmonth) {
1461 $lastinmonth -= 7;
1464 // Find the first such weekday <= $startday
1465 while($lastinmonth > $startday) {
1466 $lastinmonth -= 7;
1469 return $lastinmonth;
1472 else {
1474 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1476 $diff = $weekday - $indexweekday;
1477 if($diff < 0) {
1478 $diff += 7;
1481 // This is the first such weekday of the month equal to or after $startday
1482 $firstfromindex = $startday + $diff;
1484 return $firstfromindex;
1490 * Calculate the number of days in a given month
1492 * @param int $month The month whose day count is sought
1493 * @param int $year The year of the month whose day count is sought
1494 * @return int
1496 function days_in_month($month, $year) {
1497 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1501 * Calculate the position in the week of a specific calendar day
1503 * @param int $day The day of the date whose position in the week is sought
1504 * @param int $month The month of the date whose position in the week is sought
1505 * @param int $year The year of the date whose position in the week is sought
1506 * @return int
1508 function dayofweek($day, $month, $year) {
1509 // I wonder if this is any different from
1510 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1511 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1514 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1517 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1518 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1519 * sesskey string if $USER exists, or boolean false if not.
1521 * @uses $USER
1522 * @return string
1524 function sesskey() {
1525 global $USER;
1527 if(!isset($USER)) {
1528 return false;
1531 if (empty($USER->sesskey)) {
1532 $USER->sesskey = random_string(10);
1535 return $USER->sesskey;
1540 * For security purposes, this function will check that the currently
1541 * given sesskey (passed as a parameter to the script or this function)
1542 * matches that of the current user.
1544 * @param string $sesskey optionally provided sesskey
1545 * @return bool
1547 function confirm_sesskey($sesskey=NULL) {
1548 global $USER;
1550 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1551 return true;
1554 if (empty($sesskey)) {
1555 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
1558 if (!isset($USER->sesskey)) {
1559 return false;
1562 return ($USER->sesskey === $sesskey);
1566 * Setup all global $CFG course variables, set locale and also themes
1567 * This function can be used on pages that do not require login instead of require_login()
1569 * @param mixed $courseorid id of the course or course object
1571 function course_setup($courseorid=0) {
1572 global $COURSE, $CFG, $SITE;
1574 /// Redefine global $COURSE if needed
1575 if (empty($courseorid)) {
1576 // no change in global $COURSE - for backwards compatibiltiy
1577 // if require_rogin() used after require_login($courseid);
1578 } else if (is_object($courseorid)) {
1579 $COURSE = clone($courseorid);
1580 } else {
1581 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1582 if (!empty($course->id) and $course->id == SITEID) {
1583 $COURSE = clone($SITE);
1584 } else if (!empty($course->id) and $course->id == $courseorid) {
1585 $COURSE = clone($course);
1586 } else {
1587 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1588 error('Invalid course ID');
1593 /// set locale and themes
1594 moodle_setlocale();
1595 theme_setup();
1600 * This function checks that the current user is logged in and has the
1601 * required privileges
1603 * This function checks that the current user is logged in, and optionally
1604 * whether they are allowed to be in a particular course and view a particular
1605 * course module.
1606 * If they are not logged in, then it redirects them to the site login unless
1607 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1608 * case they are automatically logged in as guests.
1609 * If $courseid is given and the user is not enrolled in that course then the
1610 * user is redirected to the course enrolment page.
1611 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1612 * in the course then the user is redirected to the course home page.
1614 * @uses $CFG
1615 * @uses $SESSION
1616 * @uses $USER
1617 * @uses $FULLME
1618 * @uses SITEID
1619 * @uses $COURSE
1620 * @param mixed $courseorid id of the course or course object
1621 * @param bool $autologinguest
1622 * @param object $cm course module object
1624 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1626 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1628 /// setup global $COURSE, themes, language and locale
1629 course_setup($courseorid);
1631 /// If the user is not even logged in yet then make sure they are
1632 if (!isloggedin()) {
1633 //NOTE: $USER->site check was obsoleted by session test cookie,
1634 // $USER->confirmed test is in login/index.php
1635 $SESSION->wantsurl = $FULLME;
1636 if (!empty($_SERVER['HTTP_REFERER'])) {
1637 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
1639 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
1640 $loginguest = '?loginguest=true';
1641 } else {
1642 $loginguest = '';
1644 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
1645 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
1646 } else {
1647 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1648 redirect($wwwroot .'/login/index.php');
1650 exit;
1653 /// loginas as redirection if needed
1654 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1655 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1656 if ($USER->loginascontext->instanceid != $COURSE->id) {
1657 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
1663 /// check whether the user should be changing password (but only if it is REALLY them)
1664 $userauth = get_auth_plugin($USER->auth);
1665 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
1666 if ($userauth->can_change_password()) {
1667 $SESSION->wantsurl = $FULLME;
1668 if ($changeurl = $userauth->change_password_url()) {
1669 //use plugin custom url
1670 redirect($changeurl);
1671 } else {
1672 //use moodle internal method
1673 if (empty($CFG->loginhttps)) {
1674 redirect($CFG->wwwroot .'/login/change_password.php');
1675 } else {
1676 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1677 redirect($wwwroot .'/login/change_password.php');
1680 } else {
1681 error(get_string('nopasswordchangeforced', 'auth'));
1685 /// Check that the user account is properly set up
1686 if (user_not_fully_set_up($USER)) {
1687 $SESSION->wantsurl = $FULLME;
1688 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
1691 /// Make sure current IP matches the one for this session (if required)
1692 if (!empty($CFG->tracksessionip)) {
1693 if ($USER->sessionIP != md5(getremoteaddr())) {
1694 error(get_string('sessionipnomatch', 'error'));
1698 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1699 sesskey();
1701 // Check that the user has agreed to a site policy if there is one
1702 if (!empty($CFG->sitepolicy)) {
1703 if (!$USER->policyagreed) {
1704 $SESSION->wantsurl = $FULLME;
1705 redirect($CFG->wwwroot .'/user/policy.php');
1709 /// If the site is currently under maintenance, then print a message
1710 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1711 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1712 print_maintenance_message();
1713 exit;
1718 if ($COURSE->id == SITEID) {
1719 /// We can eliminate hidden site activities straight away
1720 if (!empty($cm) && !$cm->visible and !has_capability('moodle/course:viewhiddenactivities',
1721 get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1722 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
1724 return;
1726 } else {
1727 /// Check if the user can be in a particular course
1728 if (!$context = get_context_instance(CONTEXT_COURSE, $COURSE->id)) {
1729 print_error('nocontext');
1732 if (empty($USER->switchrole[$context->id]) &&
1733 !($COURSE->visible && course_parent_visible($COURSE)) &&
1734 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $COURSE->id)) ){
1735 print_header_simple();
1736 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1739 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1741 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $context)) {
1742 if ($COURSE->guest == 1) {
1743 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1744 has_capability('clearcache'); // Must clear cache
1745 $guestcaps = get_role_context_caps($CFG->guestroleid, $context);
1746 $USER->capabilities = merge_role_caps($USER->capabilities, $guestcaps);
1750 /// If the user is a guest then treat them according to the course policy about guests
1752 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1753 switch ($COURSE->guest) { /// Check course policy about guest access
1755 case 1: /// Guests always allowed
1756 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1757 print_header_simple();
1758 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1760 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1761 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1762 get_string('activityiscurrentlyhidden'));
1765 return; // User is allowed to see this course
1767 break;
1769 case 2: /// Guests allowed with key
1770 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
1771 return true;
1773 // otherwise drop through to logic below (--> enrol.php)
1774 break;
1776 default: /// Guests not allowed
1777 print_header_simple('', '', get_string('loggedinasguest'));
1778 if (empty($USER->switchrole[$context->id])) { // Normal guest
1779 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1780 } else {
1781 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
1782 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
1783 print_footer($COURSE);
1784 exit;
1786 break;
1789 /// For non-guests, check if they have course view access
1791 } else if (has_capability('moodle/course:view', $context)) {
1792 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
1793 if (!has_capability('moodle/course:view', $context, $USER->realuser)) {
1794 print_header_simple();
1795 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
1799 /// Make sure they can read this activity too, if specified
1801 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
1802 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1804 return; // User is allowed to see this course
1809 /// Currently not enrolled in the course, so see if they want to enrol
1810 $SESSION->wantsurl = $FULLME;
1811 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
1812 die;
1819 * This function just makes sure a user is logged out.
1821 * @uses $CFG
1822 * @uses $USER
1824 function require_logout() {
1826 global $USER, $CFG, $SESSION;
1828 if (isloggedin()) {
1829 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1831 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1832 foreach($authsequence as $authname) {
1833 $authplugin = get_auth_plugin($authname);
1834 $authplugin->prelogout_hook();
1838 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1839 // This method is just to try to avoid silly warnings from PHP 4.3.0
1840 session_unregister("USER");
1841 session_unregister("SESSION");
1844 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
1845 $file = $line = null;
1846 if (headers_sent($file, $line)) {
1847 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
1848 error_log('Headers were already sent in file: '.$file.' on line '.$line);
1849 } else {
1850 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
1853 unset($_SESSION['USER']);
1854 unset($_SESSION['SESSION']);
1856 unset($SESSION);
1857 unset($USER);
1862 * This is a weaker version of {@link require_login()} which only requires login
1863 * when called from within a course rather than the site page, unless
1864 * the forcelogin option is turned on.
1866 * @uses $CFG
1867 * @param mixed $courseorid The course object or id in question
1868 * @param bool $autologinguest Allow autologin guests if that is wanted
1869 * @param object $cm Course activity module if known
1871 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1872 global $CFG;
1873 if (!empty($CFG->forcelogin)) {
1874 // login required for both SITE and courses
1875 require_login($courseorid, $autologinguest, $cm);
1877 } else if (!empty($cm) and !$cm->visible) {
1878 // always login for hidden activities
1879 require_login($courseorid, $autologinguest, $cm);
1881 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
1882 or (!is_object($courseorid) and $courseorid == SITEID)) {
1883 //login for SITE not required
1884 return;
1886 } else {
1887 // course login always required
1888 require_login($courseorid, $autologinguest, $cm);
1893 * Modify the user table by setting the currently logged in user's
1894 * last login to now.
1896 * @uses $USER
1897 * @return bool
1899 function update_user_login_times() {
1900 global $USER;
1902 $user = new object();
1903 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
1904 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1906 $user->id = $USER->id;
1908 return update_record('user', $user);
1912 * Determines if a user has completed setting up their account.
1914 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
1915 * @return bool
1917 function user_not_fully_set_up($user) {
1918 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1921 function over_bounce_threshold($user) {
1923 global $CFG;
1925 if (empty($CFG->handlebounces)) {
1926 return false;
1928 // set sensible defaults
1929 if (empty($CFG->minbounces)) {
1930 $CFG->minbounces = 10;
1932 if (empty($CFG->bounceratio)) {
1933 $CFG->bounceratio = .20;
1935 $bouncecount = 0;
1936 $sendcount = 0;
1937 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1938 $bouncecount = $bounce->value;
1940 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1941 $sendcount = $send->value;
1943 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
1947 * @param $user - object containing an id
1948 * @param $reset - will reset the count to 0
1950 function set_send_count($user,$reset=false) {
1951 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1952 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1953 update_record('user_preferences',$pref);
1955 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1956 // make a new one
1957 $pref->name = 'email_send_count';
1958 $pref->value = 1;
1959 $pref->userid = $user->id;
1960 insert_record('user_preferences',$pref, false);
1965 * @param $user - object containing an id
1966 * @param $reset - will reset the count to 0
1968 function set_bounce_count($user,$reset=false) {
1969 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1970 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1971 update_record('user_preferences',$pref);
1973 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1974 // make a new one
1975 $pref->name = 'email_bounce_count';
1976 $pref->value = 1;
1977 $pref->userid = $user->id;
1978 insert_record('user_preferences',$pref, false);
1983 * Keeps track of login attempts
1985 * @uses $SESSION
1987 function update_login_count() {
1989 global $SESSION;
1991 $max_logins = 10;
1993 if (empty($SESSION->logincount)) {
1994 $SESSION->logincount = 1;
1995 } else {
1996 $SESSION->logincount++;
1999 if ($SESSION->logincount > $max_logins) {
2000 unset($SESSION->wantsurl);
2001 error(get_string('errortoomanylogins'));
2006 * Resets login attempts
2008 * @uses $SESSION
2010 function reset_login_count() {
2011 global $SESSION;
2013 $SESSION->logincount = 0;
2016 function sync_metacourses() {
2018 global $CFG;
2020 if (!$courses = get_records('course', 'metacourse', 1)) {
2021 return;
2024 foreach ($courses as $course) {
2025 sync_metacourse($course);
2030 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2032 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2034 function sync_metacourse($course) {
2035 global $CFG;
2037 // Check the course is valid.
2038 if (!is_object($course)) {
2039 if (!$course = get_record('course', 'id', $course)) {
2040 return false; // invalid course id
2044 // Check that we actually have a metacourse.
2045 if (empty($course->metacourse)) {
2046 return false;
2049 // Get a list of roles that should not be synced.
2050 if (!empty($CFG->nonmetacoursesyncroleids)) {
2051 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2052 } else {
2053 $roleexclusions = '';
2056 // Get the context of the metacourse.
2057 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2059 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2060 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2061 $managers = array_keys($users);
2062 } else {
2063 $managers = array();
2066 // Get assignments of a user to a role that exist in a child course, but
2067 // not in the meta coure. That is, get a list of the assignments that need to be made.
2068 if (!$assignments = get_records_sql("
2069 SELECT
2070 ra.id, ra.roleid, ra.userid
2071 FROM
2072 {$CFG->prefix}role_assignments ra,
2073 {$CFG->prefix}context con,
2074 {$CFG->prefix}course_meta cm
2075 WHERE
2076 ra.contextid = con.id AND
2077 con.contextlevel = " . CONTEXT_COURSE . " AND
2078 con.instanceid = cm.child_course AND
2079 cm.parent_course = {$course->id} AND
2080 $roleexclusions
2081 NOT EXISTS (
2082 SELECT 1 FROM
2083 {$CFG->prefix}role_assignments ra2
2084 WHERE
2085 ra2.userid = ra.userid AND
2086 ra2.roleid = ra.roleid AND
2087 ra2.contextid = {$context->id}
2089 ")) {
2090 $assignments = array();
2093 // Get assignments of a user to a role that exist in the meta course, but
2094 // not in any child courses. That is, get a list of the unassignments that need to be made.
2095 if (!$unassignments = get_records_sql("
2096 SELECT
2097 ra.id, ra.roleid, ra.userid
2098 FROM
2099 {$CFG->prefix}role_assignments ra
2100 WHERE
2101 ra.contextid = {$context->id} AND
2102 $roleexclusions
2103 NOT EXISTS (
2104 SELECT 1 FROM
2105 {$CFG->prefix}role_assignments ra2,
2106 {$CFG->prefix}context con2,
2107 {$CFG->prefix}course_meta cm
2108 WHERE
2109 ra2.userid = ra.userid AND
2110 ra2.roleid = ra.roleid AND
2111 ra2.contextid = con2.id AND
2112 con2.contextlevel = " . CONTEXT_COURSE . " AND
2113 con2.instanceid = cm.child_course AND
2114 cm.parent_course = {$course->id}
2116 ")) {
2117 $unassignments = array();
2120 $success = true;
2122 // Make the unassignments, if they are not managers.
2123 foreach ($unassignments as $unassignment) {
2124 if (!in_array($unassignment->userid, $managers)) {
2125 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
2129 // Make the assignments.
2130 foreach ($assignments as $assignment) {
2131 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
2134 return $success;
2136 // TODO: finish timeend and timestart
2137 // maybe we could rely on cron job to do the cleaning from time to time
2141 * Adds a record to the metacourse table and calls sync_metacoures
2143 function add_to_metacourse ($metacourseid, $courseid) {
2145 if (!$metacourse = get_record("course","id",$metacourseid)) {
2146 return false;
2149 if (!$course = get_record("course","id",$courseid)) {
2150 return false;
2153 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2154 $rec = new object();
2155 $rec->parent_course = $metacourseid;
2156 $rec->child_course = $courseid;
2157 if (!insert_record('course_meta',$rec)) {
2158 return false;
2160 return sync_metacourse($metacourseid);
2162 return true;
2167 * Removes the record from the metacourse table and calls sync_metacourse
2169 function remove_from_metacourse($metacourseid, $courseid) {
2171 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2172 return sync_metacourse($metacourseid);
2174 return false;
2179 * Determines if a user is currently logged in
2181 * @uses $USER
2182 * @return bool
2184 function isloggedin() {
2185 global $USER;
2187 return (!empty($USER->id));
2191 * Determines if a user is logged in as real guest user with username 'guest'.
2192 * This function is similar to original isguest() in 1.6 and earlier.
2193 * Current isguest() is deprecated - do not use it anymore.
2195 * @param $user mixed user object or id, $USER if not specified
2196 * @return bool true if user is the real guest user, false if not logged in or other user
2198 function isguestuser($user=NULL) {
2199 global $USER;
2200 if ($user === NULL) {
2201 $user = $USER;
2202 } else if (is_numeric($user)) {
2203 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2206 if (empty($user->id)) {
2207 return false; // not logged in, can not be guest
2210 return ($user->username == 'guest');
2214 * Determines if the currently logged in user is in editing mode
2216 * @uses $USER
2217 * @param int $courseid The id of the course being tested
2218 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
2219 * @return bool
2221 function isediting($courseid, $user=NULL) {
2222 global $USER;
2223 if (!$user) {
2224 $user = $USER;
2226 if (empty($user->editing)) {
2227 return false;
2230 $capcheck = false;
2231 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
2233 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
2234 has_capability('moodle/site:manageblocks', $coursecontext)) {
2235 $capcheck = true;
2236 } else {
2237 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
2238 if ($children = get_child_contexts($coursecontext)) {
2239 foreach ($children as $child) {
2240 $childcontext = get_record('context', 'id', $child);
2241 if (has_capability('moodle/course:manageactivities', $childcontext) ||
2242 has_capability('moodle/site:manageblocks', $childcontext)) {
2243 $capcheck = true;
2244 break;
2250 return ($user->editing && $capcheck);
2251 //return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2255 * Determines if the logged in user is currently moving an activity
2257 * @uses $USER
2258 * @param int $courseid The id of the course being tested
2259 * @return bool
2261 function ismoving($courseid) {
2262 global $USER;
2264 if (!empty($USER->activitycopy)) {
2265 return ($USER->activitycopycourse == $courseid);
2267 return false;
2271 * Given an object containing firstname and lastname
2272 * values, this function returns a string with the
2273 * full name of the person.
2274 * The result may depend on system settings
2275 * or language. 'override' will force both names
2276 * to be used even if system settings specify one.
2278 * @uses $CFG
2279 * @uses $SESSION
2280 * @param object $user A {@link $USER} object to get full name of
2281 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2283 function fullname($user, $override=false) {
2285 global $CFG, $SESSION;
2287 if (!isset($user->firstname) and !isset($user->lastname)) {
2288 return '';
2291 if (!$override) {
2292 if (!empty($CFG->forcefirstname)) {
2293 $user->firstname = $CFG->forcefirstname;
2295 if (!empty($CFG->forcelastname)) {
2296 $user->lastname = $CFG->forcelastname;
2300 if (!empty($SESSION->fullnamedisplay)) {
2301 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2304 if ($CFG->fullnamedisplay == 'firstname lastname') {
2305 return $user->firstname .' '. $user->lastname;
2307 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
2308 return $user->lastname .' '. $user->firstname;
2310 } else if ($CFG->fullnamedisplay == 'firstname') {
2311 if ($override) {
2312 return get_string('fullnamedisplay', '', $user);
2313 } else {
2314 return $user->firstname;
2318 return get_string('fullnamedisplay', '', $user);
2322 * Sets a moodle cookie with an encrypted string
2324 * @uses $CFG
2325 * @uses DAYSECS
2326 * @uses HOURSECS
2327 * @param string $thing The string to encrypt and place in a cookie
2329 function set_moodle_cookie($thing) {
2330 global $CFG;
2332 if ($thing == 'guest') { // Ignore guest account
2333 return;
2336 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2338 $days = 60;
2339 $seconds = DAYSECS*$days;
2341 setCookie($cookiename, '', time() - HOURSECS, '/');
2342 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
2346 * Gets a moodle cookie with an encrypted string
2348 * @uses $CFG
2349 * @return string
2351 function get_moodle_cookie() {
2352 global $CFG;
2354 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2356 if (empty($_COOKIE[$cookiename])) {
2357 return '';
2358 } else {
2359 $thing = rc4decrypt($_COOKIE[$cookiename]);
2360 return ($thing == 'guest') ? '': $thing; // Ignore guest account
2365 * Returns whether a given authentication plugin exists.
2367 * @uses $CFG
2368 * @param string $auth Form of authentication to check for. Defaults to the
2369 * global setting in {@link $CFG}.
2370 * @return boolean Whether the plugin is available.
2372 function exists_auth_plugin($auth) {
2373 global $CFG;
2375 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2376 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2378 return false;
2382 * Checks if a given plugin is in the list of enabled authentication plugins.
2384 * @param string $auth Authentication plugin.
2385 * @return boolean Whether the plugin is enabled.
2387 function is_enabled_auth($auth) {
2388 if (empty($auth)) {
2389 return false;
2392 $enabled = get_enabled_auth_plugins();
2394 return in_array($auth, $enabled);
2398 * Returns an authentication plugin instance.
2400 * @uses $CFG
2401 * @param string $auth name of authentication plugin
2402 * @return object An instance of the required authentication plugin.
2404 function get_auth_plugin($auth) {
2405 global $CFG;
2407 // check the plugin exists first
2408 if (! exists_auth_plugin($auth)) {
2409 error("Authentication plugin '$auth' not found.");
2412 // return auth plugin instance
2413 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2414 $class = "auth_plugin_$auth";
2415 return new $class;
2419 * Returns array of active auth plugins.
2421 * @param bool $fix fix $CFG->auth if needed
2422 * @return array
2424 function get_enabled_auth_plugins($fix=false) {
2425 global $CFG;
2427 $default = array('manual', 'nologin');
2429 if (empty($CFG->auth)) {
2430 $auths = array();
2431 } else {
2432 $auths = explode(',', $CFG->auth);
2435 if ($fix) {
2436 $auths = array_unique($auths);
2437 foreach($auths as $k=>$authname) {
2438 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2439 unset($auths[$k]);
2442 $newconfig = implode(',', $auths);
2443 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2444 set_config('auth', $newconfig);
2448 return (array_merge($default, $auths));
2452 * Returns true if an internal authentication method is being used.
2453 * if method not specified then, global default is assumed
2455 * @uses $CFG
2456 * @param string $auth Form of authentication required
2457 * @return bool
2459 function is_internal_auth($auth) {
2460 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2461 return $authplugin->is_internal();
2465 * Returns an array of user fields
2467 * @uses $CFG
2468 * @uses $db
2469 * @return array User field/column names
2471 function get_user_fieldnames() {
2473 global $CFG, $db;
2475 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2476 unset($fieldarray['ID']);
2478 return $fieldarray;
2482 * Creates a bare-bones user record
2484 * @uses $CFG
2485 * @param string $username New user's username to add to record
2486 * @param string $password New user's password to add to record
2487 * @param string $auth Form of authentication required
2488 * @return object A {@link $USER} object
2489 * @todo Outline auth types and provide code example
2491 function create_user_record($username, $password, $auth='manual') {
2492 global $CFG;
2494 //just in case check text case
2495 $username = trim(moodle_strtolower($username));
2497 $authplugin = get_auth_plugin($auth);
2499 if ($newinfo = $authplugin->get_userinfo($username)) {
2500 $newinfo = truncate_userinfo($newinfo);
2501 foreach ($newinfo as $key => $value){
2502 $newuser->$key = addslashes($value);
2506 if (!empty($newuser->email)) {
2507 if (email_is_not_allowed($newuser->email)) {
2508 unset($newuser->email);
2512 $newuser->auth = $auth;
2513 $newuser->username = $username;
2515 // fix for MDL-8480
2516 // user CFG lang for user if $newuser->lang is empty
2517 // or $user->lang is not an installed language
2518 $sitelangs = array_keys(get_list_of_languages());
2519 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2520 $newuser -> lang = $CFG->lang;
2522 $newuser->confirmed = 1;
2523 $newuser->lastip = getremoteaddr();
2524 $newuser->timemodified = time();
2525 $newuser->mnethostid = $CFG->mnet_localhost_id;
2527 if (insert_record('user', $newuser)) {
2528 $user = get_complete_user_data('username', $newuser->username);
2529 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
2530 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2532 update_internal_user_password($user, $password);
2533 return $user;
2535 return false;
2539 * Will update a local user record from an external source
2541 * @uses $CFG
2542 * @param string $username New user's username to add to record
2543 * @return user A {@link $USER} object
2545 function update_user_record($username, $authplugin) {
2546 $username = trim(moodle_strtolower($username)); /// just in case check text case
2548 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2549 $userauth = get_auth_plugin($oldinfo->auth);
2551 if ($newinfo = $userauth->get_userinfo($username)) {
2552 $newinfo = truncate_userinfo($newinfo);
2553 foreach ($newinfo as $key => $value){
2554 $confkey = 'field_updatelocal_' . $key;
2555 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2556 $value = addslashes(stripslashes($value)); // Just in case
2557 set_field('user', $key, $value, 'username', $username)
2558 or error_log("Error updating $key for $username");
2563 return get_complete_user_data('username', $username);
2566 function truncate_userinfo($info) {
2567 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2568 /// which may have large fields
2570 // define the limits
2571 $limit = array(
2572 'username' => 100,
2573 'idnumber' => 64,
2574 'firstname' => 100,
2575 'lastname' => 100,
2576 'email' => 100,
2577 'icq' => 15,
2578 'phone1' => 20,
2579 'phone2' => 20,
2580 'institution' => 40,
2581 'department' => 30,
2582 'address' => 70,
2583 'city' => 20,
2584 'country' => 2,
2585 'url' => 255,
2588 // apply where needed
2589 foreach (array_keys($info) as $key) {
2590 if (!empty($limit[$key])) {
2591 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2595 return $info;
2599 * Retrieve the guest user object
2601 * @uses $CFG
2602 * @return user A {@link $USER} object
2604 function guest_user() {
2605 global $CFG;
2607 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
2608 $newuser->confirmed = 1;
2609 $newuser->lang = $CFG->lang;
2610 $newuser->lastip = getremoteaddr();
2613 return $newuser;
2617 * Given a username and password, this function looks them
2618 * up using the currently selected authentication mechanism,
2619 * and if the authentication is successful, it returns a
2620 * valid $user object from the 'user' table.
2622 * Uses auth_ functions from the currently active auth module
2624 * @uses $CFG
2625 * @param string $username User's username (with system magic quotes)
2626 * @param string $password User's password (with system magic quotes)
2627 * @return user|flase A {@link $USER} object or false if error
2629 function authenticate_user_login($username, $password) {
2631 global $CFG;
2633 $authsenabled = get_enabled_auth_plugins();
2635 if ($user = get_complete_user_data('username', $username)) {
2636 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
2637 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2638 add_to_log(0, 'login', 'error', 'index.php', $username);
2639 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2640 return false;
2642 if (!empty($user->deleted)) {
2643 add_to_log(0, 'login', 'error', 'index.php', $username);
2644 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2645 return false;
2647 $auths = array($auth);
2649 } else {
2650 $auths = $authsenabled;
2651 $user = new object();
2652 $user->id = 0; // User does not exist
2655 foreach ($auths as $auth) {
2656 $authplugin = get_auth_plugin($auth);
2658 // on auth fail fall through to the next plugin
2659 if (!$authplugin->user_login($username, $password)) {
2660 continue;
2663 // successful authentication
2664 if ($user->id) { // User already exists in database
2665 if (empty($user->auth)) { // For some reason auth isn't set yet
2666 set_field('user', 'auth', $auth, 'username', $username);
2667 $user->auth = $auth;
2670 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2672 if (!$authplugin->is_internal()) { // update user record from external DB
2673 $user = update_user_record($username, get_auth_plugin($user->auth));
2675 } else {
2676 // if user not found, create him
2677 $user = create_user_record($username, $password, $auth);
2680 $authplugin->sync_roles($user);
2682 foreach ($authsenabled as $hau) {
2683 $hauth = get_auth_plugin($hau);
2684 $hauth->user_authenticated_hook($user, $username, $password);
2687 /// Log in to a second system if necessary
2688 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2689 if (!empty($CFG->sso)) {
2690 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2691 if (function_exists('sso_user_login')) {
2692 if (!sso_user_login($username, $password)) { // Perform the signon process
2693 notify('Second sign-on failed');
2698 return $user;
2702 // failed if all the plugins have failed
2703 add_to_log(0, 'login', 'error', 'index.php', $username);
2704 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2705 return false;
2709 * Compare password against hash stored in internal user table.
2710 * If necessary it also updates the stored hash to new format.
2712 * @param object user
2713 * @param string plain text password
2714 * @return bool is password valid?
2716 function validate_internal_user_password(&$user, $password) {
2717 global $CFG;
2719 if (!isset($CFG->passwordsaltmain)) {
2720 $CFG->passwordsaltmain = '';
2723 $validated = false;
2725 // get password original encoding in case it was not updated to unicode yet
2726 $textlib = textlib_get_instance();
2727 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2729 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2730 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
2731 $validated = true;
2732 } else {
2733 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
2734 $alt = 'passwordsaltalt'.$i;
2735 if (!empty($CFG->$alt)) {
2736 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2737 $validated = true;
2738 break;
2744 if ($validated) {
2745 // force update of password hash using latest main password salt and encoding if needed
2746 update_internal_user_password($user, $password);
2749 return $validated;
2753 * Calculate hashed value from password using current hash mechanism.
2755 * @param string password
2756 * @return string password hash
2758 function hash_internal_user_password($password) {
2759 global $CFG;
2761 if (isset($CFG->passwordsaltmain)) {
2762 return md5($password.$CFG->passwordsaltmain);
2763 } else {
2764 return md5($password);
2769 * Update pssword hash in user object.
2771 * @param object user
2772 * @param string plain text password
2773 * @param bool store changes also in db, default true
2774 * @return true if hash changed
2776 function update_internal_user_password(&$user, $password) {
2777 global $CFG;
2779 $authplugin = get_auth_plugin($user->auth);
2780 if (!empty($authplugin->config->preventpassindb)) {
2781 $hashedpassword = 'not cached';
2782 } else {
2783 $hashedpassword = hash_internal_user_password($password);
2786 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
2790 * Get a complete user record, which includes all the info
2791 * in the user record
2792 * Intended for setting as $USER session variable
2794 * @uses $CFG
2795 * @uses SITEID
2796 * @param string $field The user field to be checked for a given value.
2797 * @param string $value The value to match for $field.
2798 * @return user A {@link $USER} object.
2800 function get_complete_user_data($field, $value, $mnethostid=null) {
2802 global $CFG;
2804 if (!$field || !$value) {
2805 return false;
2808 /// Build the WHERE clause for an SQL query
2810 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2812 if (is_null($mnethostid)) {
2813 // if null, we restrict to local users
2814 // ** testing for local user can be done with
2815 // mnethostid = $CFG->mnet_localhost_id
2816 // or with
2817 // auth != 'mnet'
2818 // but the first one is FAST with our indexes
2819 $mnethostid = $CFG->mnet_localhost_id;
2821 $mnethostid = (int)$mnethostid;
2822 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2824 /// Get all the basic user data
2826 if (! $user = get_record_select('user', $constraints)) {
2827 return false;
2830 /// Get various settings and preferences
2832 if ($displays = get_records('course_display', 'userid', $user->id)) {
2833 foreach ($displays as $display) {
2834 $user->display[$display->course] = $display->display;
2838 $user->preference = get_user_preferences(null, null, $user->id);
2840 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
2841 foreach ($lastaccesses as $lastaccess) {
2842 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
2846 if ($groupids = groups_get_all_groups_for_user($user->id)) { //TODO:check.
2847 foreach ($groupids as $groupid) {
2848 $courseid = groups_get_course($groupid);
2849 //change this to 2D array so we can put multiple groups in a course
2850 $user->groupmember[$courseid][] = $groupid;
2854 /// Rewrite some variables if necessary
2855 if (!empty($user->description)) {
2856 $user->description = true; // No need to cart all of it around
2858 if ($user->username == 'guest') {
2859 $user->lang = $CFG->lang; // Guest language always same as site
2860 $user->firstname = get_string('guestuser'); // Name always in current language
2861 $user->lastname = ' ';
2864 $user->sesskey = random_string(10);
2865 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
2867 return $user;
2871 * @uses $CFG
2872 * @param string $password the password to be checked agains the password policy
2873 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
2874 * @return bool true if the password is valid according to the policy. false otherwise.
2876 function check_password_policy($password, &$errmsg) {
2877 global $CFG;
2879 if (empty($CFG->passwordpolicy)) {
2880 return true;
2883 $textlib = new textlib();
2884 $errmsg = '';
2885 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
2886 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
2888 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
2889 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
2891 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
2892 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
2894 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
2895 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
2897 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
2898 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
2900 } else if ($password == 'admin' or $password == 'password') {
2901 $errmsg = get_string('unsafepassword');
2904 if ($errmsg == '') {
2905 return true;
2906 } else {
2907 return false;
2913 * When logging in, this function is run to set certain preferences
2914 * for the current SESSION
2916 function set_login_session_preferences() {
2917 global $SESSION, $CFG;
2919 $SESSION->justloggedin = true;
2921 unset($SESSION->lang);
2923 // Restore the calendar filters, if saved
2924 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2925 include_once($CFG->dirroot.'/calendar/lib.php');
2926 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
2932 * Delete a course, including all related data from the database,
2933 * and any associated files from the moodledata folder.
2935 * @param int $courseid The id of the course to delete.
2936 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2937 * @return bool true if all the removals succeeded. false if there were any failures. If this
2938 * method returns false, some of the removals will probably have succeeded, and others
2939 * failed, but you have no way of knowing which.
2941 function delete_course($courseid, $showfeedback = true) {
2942 global $CFG;
2943 $result = true;
2945 if (!remove_course_contents($courseid, $showfeedback)) {
2946 if ($showfeedback) {
2947 notify("An error occurred while deleting some of the course contents.");
2949 $result = false;
2952 if (!delete_records("course", "id", $courseid)) {
2953 if ($showfeedback) {
2954 notify("An error occurred while deleting the main course record.");
2956 $result = false;
2959 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE, 'instanceid', $courseid)) {
2960 if ($showfeedback) {
2961 notify("An error occurred while deleting the main context record.");
2963 $result = false;
2966 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
2967 if ($showfeedback) {
2968 notify("An error occurred while deleting the course files.");
2970 $result = false;
2973 return $result;
2977 * Clear a course out completely, deleting all content
2978 * but don't delete the course itself
2980 * @uses $CFG
2981 * @param int $courseid The id of the course that is being deleted
2982 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2983 * @return bool true if all the removals succeeded. false if there were any failures. If this
2984 * method returns false, some of the removals will probably have succeeded, and others
2985 * failed, but you have no way of knowing which.
2987 function remove_course_contents($courseid, $showfeedback=true) {
2989 global $CFG;
2991 $result = true;
2993 if (! $course = get_record('course', 'id', $courseid)) {
2994 error('Course ID was incorrect (can\'t find it)');
2997 $strdeleted = get_string('deleted');
2999 /// First delete every instance of every module
3001 if ($allmods = get_records('modules') ) {
3002 foreach ($allmods as $mod) {
3003 $modname = $mod->name;
3004 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3005 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3006 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3007 $count=0;
3008 if (file_exists($modfile)) {
3009 include_once($modfile);
3010 if (function_exists($moddelete)) {
3011 if ($instances = get_records($modname, 'course', $course->id)) {
3012 foreach ($instances as $instance) {
3013 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
3014 delete_context(CONTEXT_MODULE, $cm->id);
3016 if ($moddelete($instance->id)) {
3017 $count++;
3019 } else {
3020 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
3021 $result = false;
3025 } else {
3026 notify('Function '. $moddelete() .'doesn\'t exist!');
3027 $result = false;
3030 if (function_exists($moddeletecourse)) {
3031 $moddeletecourse($course, $showfeedback);
3034 if ($showfeedback) {
3035 notify($strdeleted .' '. $count .' x '. $modname);
3038 } else {
3039 error('No modules are installed!');
3042 /// Give local code a chance to delete its references to this course.
3043 require_once('locallib.php');
3044 notify_local_delete_course($courseid, $showfeedback);
3046 /// Delete course blocks
3048 if ($blocks = get_records_sql("SELECT *
3049 FROM {$CFG->prefix}block_instance
3050 WHERE pagetype = '".PAGE_COURSE_VIEW."'
3051 AND pageid = $course->id")) {
3052 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
3053 if ($showfeedback) {
3054 notify($strdeleted .' block_instance');
3057 require_once($CFG->libdir.'/blocklib.php');
3058 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3060 // Block instances are rarely created. Since the block instance is gone from the above delete
3061 // statement, calling delete_context() will generate a warning as get_context_instance could
3062 // no longer create the context as the block is already gone.
3063 if (record_exists('context', 'contextlevel', CONTEXT_BLOCK, 'instanceid', $block->id)) {
3064 delete_context(CONTEXT_BLOCK, $block->id);
3067 // fix for MDL-7164
3068 // Get the block object and call instance_delete()
3069 if (!$record = blocks_get_record($block->blockid)) {
3070 $result = false;
3071 continue;
3073 if (!$obj = block_instance($record->name, $block)) {
3074 $result = false;
3075 continue;
3077 // Return value ignored, in core mods this does not do anything, but just in case
3078 // third party blocks might have stuff to clean up
3079 // we execute this anyway
3080 $obj->instance_delete();
3082 } else {
3083 $result = false;
3087 /// Delete any groups, removing members and grouping/course links first.
3088 //TODO: If groups or groupings are to be shared between courses, think again!
3089 if ($groupids = groups_get_groups($course->id)) {
3090 foreach ($groupids as $groupid) {
3091 if (groups_remove_all_members($groupid)) {
3092 if ($showfeedback) {
3093 notify($strdeleted .' groups_members');
3095 } else {
3096 $result = false;
3098 /// Delete any associated context for this group ??
3099 delete_context(CONTEXT_GROUP, $groupid);
3101 if (groups_delete_group($groupid)) {
3102 if ($showfeedback) {
3103 notify($strdeleted .' groups');
3105 } else {
3106 $result = false;
3110 /// Delete any groupings.
3111 $result = groups_delete_all_groupings($course->id);
3112 if ($result && $showfeedback) {
3113 notify($strdeleted .' groupings');
3116 /// Delete all related records in other tables that may have a courseid
3117 /// This array stores the tables that need to be cleared, as
3118 /// table_name => column_name that contains the course id.
3120 $tablestoclear = array(
3121 'event' => 'courseid', // Delete events
3122 'log' => 'course', // Delete logs
3123 'course_sections' => 'course', // Delete any course stuff
3124 'course_modules' => 'course',
3125 'grade_category' => 'courseid', // Delete gradebook stuff
3126 'grade_exceptions' => 'courseid',
3127 'grade_item' => 'courseid',
3128 'grade_letter' => 'courseid',
3129 'grade_preferences' => 'courseid',
3130 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3131 'backup_log' => 'courseid'
3133 foreach ($tablestoclear as $table => $col) {
3134 if (delete_records($table, $col, $course->id)) {
3135 if ($showfeedback) {
3136 notify($strdeleted . ' ' . $table);
3138 } else {
3139 $result = false;
3144 /// Clean up metacourse stuff
3146 if ($course->metacourse) {
3147 delete_records("course_meta","parent_course",$course->id);
3148 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3149 if ($showfeedback) {
3150 notify("$strdeleted course_meta");
3152 } else {
3153 if ($parents = get_records("course_meta","child_course",$course->id)) {
3154 foreach ($parents as $parent) {
3155 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3157 if ($showfeedback) {
3158 notify("$strdeleted course_meta");
3163 /// Delete questions and question categories
3164 include_once($CFG->libdir.'/questionlib.php');
3165 question_delete_course($course, $showfeedback);
3167 /// Delete all roles and overiddes in the course context (but keep the course context)
3168 if ($courseid != SITEID) {
3169 delete_context(CONTEXT_COURSE, $course->id);
3172 // fix for MDL-9016
3173 // clear the cache because the course context is deleted, and
3174 // we don't want to write assignment, overrides and context_rel table
3175 // with this old context id!
3176 get_context_instance('clearcache');
3177 return $result;
3182 * This function will empty a course of USER data as much as
3183 /// possible. It will retain the activities and the structure
3184 /// of the course.
3186 * @uses $USER
3187 * @uses $SESSION
3188 * @uses $CFG
3189 * @param object $data an object containing all the boolean settings and courseid
3190 * @param bool $showfeedback if false then do it all silently
3191 * @return bool
3192 * @todo Finish documenting this function
3194 function reset_course_userdata($data, $showfeedback=true) {
3196 global $CFG, $USER, $SESSION;
3198 $result = true;
3200 $strdeleted = get_string('deleted');
3202 // Look in every instance of every module for data to delete
3204 if ($allmods = get_records('modules') ) {
3205 foreach ($allmods as $mod) {
3206 $modname = $mod->name;
3207 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3208 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3209 if (file_exists($modfile)) {
3210 @include_once($modfile);
3211 if (function_exists($moddeleteuserdata)) {
3212 $moddeleteuserdata($data, $showfeedback);
3216 } else {
3217 error('No modules are installed!');
3220 // Delete other stuff
3221 $coursecontext = get_context_instance(CONTEXT_COURSE, $data->courseid);
3223 if (!empty($data->reset_students) or !empty($data->reset_teachers)) {
3224 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3225 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3226 $students = array_diff($participants, $teachers);
3228 if (!empty($data->reset_students)) {
3229 foreach ($students as $studentid) {
3230 role_unassign(0, $studentid, 0, $coursecontext->id);
3232 if ($showfeedback) {
3233 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3236 /// Delete group members (but keep the groups) TODO:check.
3237 if ($groupids = groups_get_groups($data->courseid)) {
3238 foreach ($groupids as $groupid) {
3239 if (groups_remove_all_group_members($groupid)) {
3240 if ($showfeedback) {
3241 notify($strdeleted .' groups_members', 'notifysuccess');
3243 } else {
3244 $result = false;
3250 if (!empty($data->reset_teachers)) {
3251 foreach ($teachers as $teacherid) {
3252 role_unassign(0, $teacherid, 0, $coursecontext->id);
3254 if ($showfeedback) {
3255 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3260 if (!empty($data->reset_groups)) {
3261 if ($groupids = groups_get_groups($data->courseid)) {
3262 foreach ($groupids as $groupid) {
3263 if (groups_delete_group($groupid)) {
3264 if ($showfeedback) {
3265 notify($strdeleted .' groups', 'notifysuccess');
3267 } else {
3268 $result = false;
3274 if (!empty($data->reset_events)) {
3275 if (delete_records('event', 'courseid', $data->courseid)) {
3276 if ($showfeedback) {
3277 notify($strdeleted .' event', 'notifysuccess');
3279 } else {
3280 $result = false;
3284 if (!empty($data->reset_logs)) {
3285 if (delete_records('log', 'course', $data->courseid)) {
3286 if ($showfeedback) {
3287 notify($strdeleted .' log', 'notifysuccess');
3289 } else {
3290 $result = false;
3294 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
3295 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
3296 delete_records('role_capabilities', 'contextid', $context->id);
3298 return $result;
3302 require_once($CFG->dirroot.'/group/lib.php');
3303 /*TODO: functions moved to /group/lib/legacylib.php
3305 ismember
3306 add_user_to_group
3307 mygroupid
3308 groupmode
3309 set_current_group
3310 ... */
3313 function generate_email_processing_address($modid,$modargs) {
3314 global $CFG;
3316 if (empty($CFG->siteidentifier)) { // Unique site identification code
3317 set_config('siteidentifier', random_string(32));
3320 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3321 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
3325 function moodle_process_email($modargs,$body) {
3326 // the first char should be an unencoded letter. We'll take this as an action
3327 switch ($modargs{0}) {
3328 case 'B': { // bounce
3329 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3330 if ($user = get_record_select("user","id=$userid","id,email")) {
3331 // check the half md5 of their email
3332 $md5check = substr(md5($user->email),0,16);
3333 if ($md5check == substr($modargs, -16)) {
3334 set_bounce_count($user);
3336 // else maybe they've already changed it?
3339 break;
3340 // maybe more later?
3344 /// CORRESPONDENCE ////////////////////////////////////////////////
3347 * Send an email to a specified user
3349 * @uses $CFG
3350 * @uses $FULLME
3351 * @uses SITEID
3352 * @param user $user A {@link $USER} object
3353 * @param user $from A {@link $USER} object
3354 * @param string $subject plain text subject line of the email
3355 * @param string $messagetext plain text version of the message
3356 * @param string $messagehtml complete html version of the message (optional)
3357 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3358 * @param string $attachname the name of the file (extension indicates MIME)
3359 * @param bool $usetrueaddress determines whether $from email address should
3360 * be sent out. Will be overruled by user profile setting for maildisplay
3361 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3362 * was blocked by user and "false" if there was another sort of error.
3364 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3366 global $CFG, $FULLME;
3368 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
3370 /// We are going to use textlib services here
3371 $textlib = textlib_get_instance();
3373 if (empty($user)) {
3374 return false;
3377 // skip mail to suspended users
3378 if (isset($user->auth) && $user->auth=='nologin') {
3379 return true;
3382 if (!empty($user->emailstop)) {
3383 return 'emailstop';
3386 if (over_bounce_threshold($user)) {
3387 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3388 return false;
3391 $mail = new phpmailer;
3393 $mail->Version = 'Moodle '. $CFG->version; // mailer version
3394 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
3396 $mail->CharSet = 'UTF-8';
3398 if ($CFG->smtphosts == 'qmail') {
3399 $mail->IsQmail(); // use Qmail system
3401 } else if (empty($CFG->smtphosts)) {
3402 $mail->IsMail(); // use PHP mail() = sendmail
3404 } else {
3405 $mail->IsSMTP(); // use SMTP directly
3406 if (!empty($CFG->debugsmtp)) {
3407 echo '<pre>' . "\n";
3408 $mail->SMTPDebug = true;
3410 $mail->Host = $CFG->smtphosts; // specify main and backup servers
3412 if ($CFG->smtpuser) { // Use SMTP authentication
3413 $mail->SMTPAuth = true;
3414 $mail->Username = $CFG->smtpuser;
3415 $mail->Password = $CFG->smtppass;
3419 $adminuser = get_admin();
3421 // make up an email address for handling bounces
3422 if (!empty($CFG->handlebounces)) {
3423 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
3424 $mail->Sender = generate_email_processing_address(0,$modargs);
3426 else {
3427 $mail->Sender = $adminuser->email;
3430 if (is_string($from)) { // So we can pass whatever we want if there is need
3431 $mail->From = $CFG->noreplyaddress;
3432 $mail->FromName = $from;
3433 } else if ($usetrueaddress and $from->maildisplay) {
3434 $mail->From = $from->email;
3435 $mail->FromName = fullname($from);
3436 } else {
3437 $mail->From = $CFG->noreplyaddress;
3438 $mail->FromName = fullname($from);
3439 if (empty($replyto)) {
3440 $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
3444 if (!empty($replyto)) {
3445 $mail->AddReplyTo($replyto,$replytoname);
3448 $mail->Subject = substr(stripslashes($subject), 0, 900);
3450 $mail->AddAddress($user->email, fullname($user) );
3452 $mail->WordWrap = 79; // set word wrap
3454 if (!empty($from->customheaders)) { // Add custom headers
3455 if (is_array($from->customheaders)) {
3456 foreach ($from->customheaders as $customheader) {
3457 $mail->AddCustomHeader($customheader);
3459 } else {
3460 $mail->AddCustomHeader($from->customheaders);
3464 if (!empty($from->priority)) {
3465 $mail->Priority = $from->priority;
3468 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
3469 $mail->IsHTML(true);
3470 $mail->Encoding = 'quoted-printable'; // Encoding to use
3471 $mail->Body = $messagehtml;
3472 $mail->AltBody = "\n$messagetext\n";
3473 } else {
3474 $mail->IsHTML(false);
3475 $mail->Body = "\n$messagetext\n";
3478 if ($attachment && $attachname) {
3479 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3480 $mail->AddAddress($adminuser->email, fullname($adminuser) );
3481 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3482 } else {
3483 require_once($CFG->libdir.'/filelib.php');
3484 $mimetype = mimeinfo('type', $attachname);
3485 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
3491 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3492 /// encoding to the specified one
3493 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
3494 /// Set it to site mail charset
3495 $charset = $CFG->sitemailcharset;
3496 /// Overwrite it with the user mail charset
3497 if (!empty($CFG->allowusermailcharset)) {
3498 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
3499 $charset = $useremailcharset;
3502 /// If it has changed, convert all the necessary strings
3503 $charsets = get_list_of_charsets();
3504 unset($charsets['UTF-8']);
3505 if (in_array($charset, $charsets)) {
3506 /// Save the new mail charset
3507 $mail->CharSet = $charset;
3508 /// And convert some strings
3509 $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
3510 foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names
3511 $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet);
3513 $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject
3514 foreach ($mail->to as $key => $to) {
3515 $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet); //To Names
3517 $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body
3518 $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject
3522 if ($mail->Send()) {
3523 set_send_count($user);
3524 $mail->IsSMTP(); // use SMTP directly
3525 if (!empty($CFG->debugsmtp)) {
3526 echo '</pre>';
3528 return true;
3529 } else {
3530 mtrace('ERROR: '. $mail->ErrorInfo);
3531 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
3532 if (!empty($CFG->debugsmtp)) {
3533 echo '</pre>';
3535 return false;
3540 * Sets specified user's password and send the new password to the user via email.
3542 * @uses $CFG
3543 * @param user $user A {@link $USER} object
3544 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3545 * was blocked by user and "false" if there was another sort of error.
3547 function setnew_password_and_mail($user) {
3549 global $CFG;
3551 $site = get_site();
3552 $from = get_admin();
3554 $newpassword = generate_password();
3556 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
3557 trigger_error('Could not set user password!');
3558 return false;
3561 $a = new object();
3562 $a->firstname = $user->firstname;
3563 $a->sitename = format_string($site->fullname);
3564 $a->username = $user->username;
3565 $a->newpassword = $newpassword;
3566 $a->link = $CFG->wwwroot .'/login/';
3567 $a->signoff = fullname($from, true).' ('. $from->email .')';
3569 $message = get_string('newusernewpasswordtext', '', $a);
3571 $subject = format_string($site->fullname) .': '. get_string('newusernewpasswordsubj');
3573 return email_to_user($user, $from, $subject, $message);
3578 * Resets specified user's password and send the new password to the user via email.
3580 * @uses $CFG
3581 * @param user $user A {@link $USER} object
3582 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3583 * was blocked by user and "false" if there was another sort of error.
3585 function reset_password_and_mail($user) {
3587 global $CFG;
3589 $site = get_site();
3590 $from = get_admin();
3592 $userauth = get_auth_plugin($user->auth);
3593 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
3594 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3595 return false;
3598 $newpassword = generate_password();
3600 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3601 error("Could not set user password!");
3604 $a = new object();
3605 $a->firstname = $user->firstname;
3606 $a->sitename = format_string($site->fullname);
3607 $a->username = $user->username;
3608 $a->newpassword = $newpassword;
3609 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
3610 $a->signoff = fullname($from, true).' ('. $from->email .')';
3612 $message = get_string('newpasswordtext', '', $a);
3614 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
3616 return email_to_user($user, $from, $subject, $message);
3621 * Send email to specified user with confirmation text and activation link.
3623 * @uses $CFG
3624 * @param user $user A {@link $USER} object
3625 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3626 * was blocked by user and "false" if there was another sort of error.
3628 function send_confirmation_email($user) {
3630 global $CFG;
3632 $site = get_site();
3633 $from = get_admin();
3635 $data = new object();
3636 $data->firstname = fullname($user);
3637 $data->sitename = format_string($site->fullname);
3638 $data->admin = fullname($from) .' ('. $from->email .')';
3640 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
3642 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. urlencode($user->username);
3643 $message = get_string('emailconfirmation', '', $data);
3644 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3646 $user->mailformat = 1; // Always send HTML version as well
3648 return email_to_user($user, $from, $subject, $message, $messagehtml);
3653 * send_password_change_confirmation_email.
3655 * @uses $CFG
3656 * @param user $user A {@link $USER} object
3657 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3658 * was blocked by user and "false" if there was another sort of error.
3660 function send_password_change_confirmation_email($user) {
3662 global $CFG;
3664 $site = get_site();
3665 $from = get_admin();
3667 $data = new object();
3668 $data->firstname = $user->firstname;
3669 $data->sitename = format_string($site->fullname);
3670 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
3671 $data->admin = fullname($from).' ('. $from->email .')';
3673 $message = get_string('emailpasswordconfirmation', '', $data);
3674 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
3676 return email_to_user($user, $from, $subject, $message);
3681 * send_password_change_info.
3683 * @uses $CFG
3684 * @param user $user A {@link $USER} object
3685 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3686 * was blocked by user and "false" if there was another sort of error.
3688 function send_password_change_info($user) {
3690 global $CFG;
3692 $site = get_site();
3693 $from = get_admin();
3694 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
3696 $data = new object();
3697 $data->firstname = $user->firstname;
3698 $data->sitename = format_string($site->fullname);
3699 $data->admin = fullname($from).' ('. $from->email .')';
3701 $userauth = get_auth_plugin($user->auth);
3703 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
3704 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
3705 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3706 return email_to_user($user, $from, $subject, $message);
3709 if ($userauth->can_change_password() and $userauth->change_password_url()) {
3710 // we have some external url for password changing
3711 $data->link .= $userauth->change_password_url();
3713 } else {
3714 //no way to change password, sorry
3715 $data->link = '';
3718 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
3719 $message = get_string('emailpasswordchangeinfo', '', $data);
3720 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3721 } else {
3722 $message = get_string('emailpasswordchangeinfofail', '', $data);
3723 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3726 return email_to_user($user, $from, $subject, $message);
3731 * Check that an email is allowed. It returns an error message if there
3732 * was a problem.
3734 * @uses $CFG
3735 * @param string $email Content of email
3736 * @return string|false
3738 function email_is_not_allowed($email) {
3740 global $CFG;
3742 if (!empty($CFG->allowemailaddresses)) {
3743 $allowed = explode(' ', $CFG->allowemailaddresses);
3744 foreach ($allowed as $allowedpattern) {
3745 $allowedpattern = trim($allowedpattern);
3746 if (!$allowedpattern) {
3747 continue;
3749 if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
3750 return false;
3753 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
3755 } else if (!empty($CFG->denyemailaddresses)) {
3756 $denied = explode(' ', $CFG->denyemailaddresses);
3757 foreach ($denied as $deniedpattern) {
3758 $deniedpattern = trim($deniedpattern);
3759 if (!$deniedpattern) {
3760 continue;
3762 if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
3763 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
3768 return false;
3771 function email_welcome_message_to_user($course, $user=NULL) {
3772 global $CFG, $USER;
3774 if (empty($user)) {
3775 if (!isloggedin()) {
3776 return false;
3778 $user = $USER;
3781 if (!empty($course->welcomemessage)) {
3782 $subject = get_string('welcometocourse', '', format_string($course->fullname));
3784 $a->coursename = $course->fullname;
3785 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3786 //$message = get_string("welcometocoursetext", "", $a);
3787 $message = $course->welcomemessage;
3789 if (! $teacher = get_teacher($course->id)) {
3790 $teacher = get_admin();
3792 email_to_user($user, $teacher, $subject, $message);
3796 /// FILE HANDLING /////////////////////////////////////////////
3800 * Makes an upload directory for a particular module.
3802 * @uses $CFG
3803 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
3804 * @return string|false Returns full path to directory if successful, false if not
3806 function make_mod_upload_directory($courseid) {
3807 global $CFG;
3809 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
3810 return false;
3813 $strreadme = get_string('readme');
3815 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
3816 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3817 } else {
3818 copy($CFG->dirroot .'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3820 return $moddata;
3824 * Returns current name of file on disk if it exists.
3826 * @param string $newfile File to be verified
3827 * @return string Current name of file on disk if true
3829 function valid_uploaded_file($newfile) {
3830 if (empty($newfile)) {
3831 return '';
3833 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
3834 return $newfile['tmp_name'];
3835 } else {
3836 return '';
3841 * Returns the maximum size for uploading files.
3843 * There are seven possible upload limits:
3844 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3845 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3846 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3847 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3848 * 5. by the Moodle admin in $CFG->maxbytes
3849 * 6. by the teacher in the current course $course->maxbytes
3850 * 7. by the teacher for the current module, eg $assignment->maxbytes
3852 * These last two are passed to this function as arguments (in bytes).
3853 * Anything defined as 0 is ignored.
3854 * The smallest of all the non-zero numbers is returned.
3856 * @param int $sizebytes ?
3857 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3858 * @param int $modulebytes Current module ->maxbytes (in bytes)
3859 * @return int The maximum size for uploading files.
3860 * @todo Finish documenting this function
3862 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3864 if (! $filesize = ini_get('upload_max_filesize')) {
3865 $filesize = '5M';
3867 $minimumsize = get_real_size($filesize);
3869 if ($postsize = ini_get('post_max_size')) {
3870 $postsize = get_real_size($postsize);
3871 if ($postsize < $minimumsize) {
3872 $minimumsize = $postsize;
3876 if ($sitebytes and $sitebytes < $minimumsize) {
3877 $minimumsize = $sitebytes;
3880 if ($coursebytes and $coursebytes < $minimumsize) {
3881 $minimumsize = $coursebytes;
3884 if ($modulebytes and $modulebytes < $minimumsize) {
3885 $minimumsize = $modulebytes;
3888 return $minimumsize;
3892 * Related to {@link get_max_upload_file_size()} - this function returns an
3893 * array of possible sizes in an array, translated to the
3894 * local language.
3896 * @uses SORT_NUMERIC
3897 * @param int $sizebytes ?
3898 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3899 * @param int $modulebytes Current module ->maxbytes (in bytes)
3900 * @return int
3901 * @todo Finish documenting this function
3903 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3904 global $CFG;
3906 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
3907 return array();
3910 $filesize[$maxsize] = display_size($maxsize);
3912 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
3913 5242880, 10485760, 20971520, 52428800, 104857600);
3915 // Allow maxbytes to be selected if it falls outside the above boundaries
3916 if( isset($CFG->maxbytes) && !in_array($CFG->maxbytes, $sizelist) ){
3917 $sizelist[] = $CFG->maxbytes;
3920 foreach ($sizelist as $sizebytes) {
3921 if ($sizebytes < $maxsize) {
3922 $filesize[$sizebytes] = display_size($sizebytes);
3926 krsort($filesize, SORT_NUMERIC);
3928 return $filesize;
3932 * If there has been an error uploading a file, print the appropriate error message
3933 * Numerical constants used as constant definitions not added until PHP version 4.2.0
3935 * $filearray is a 1-dimensional sub-array of the $_FILES array
3936 * eg $filearray = $_FILES['userfile1']
3937 * If left empty then the first element of the $_FILES array will be used
3939 * @uses $_FILES
3940 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
3941 * @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.
3942 * @return bool|string
3944 function print_file_upload_error($filearray = '', $returnerror = false) {
3946 if ($filearray == '' or !isset($filearray['error'])) {
3948 if (empty($_FILES)) return false;
3950 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
3951 $filearray = array_shift($files); /// use first element of array
3954 switch ($filearray['error']) {
3956 case 0: // UPLOAD_ERR_OK
3957 if ($filearray['size'] > 0) {
3958 $errmessage = get_string('uploadproblem', $filearray['name']);
3959 } else {
3960 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
3962 break;
3964 case 1: // UPLOAD_ERR_INI_SIZE
3965 $errmessage = get_string('uploadserverlimit');
3966 break;
3968 case 2: // UPLOAD_ERR_FORM_SIZE
3969 $errmessage = get_string('uploadformlimit');
3970 break;
3972 case 3: // UPLOAD_ERR_PARTIAL
3973 $errmessage = get_string('uploadpartialfile');
3974 break;
3976 case 4: // UPLOAD_ERR_NO_FILE
3977 $errmessage = get_string('uploadnofilefound');
3978 break;
3980 default:
3981 $errmessage = get_string('uploadproblem', $filearray['name']);
3984 if ($returnerror) {
3985 return $errmessage;
3986 } else {
3987 notify($errmessage);
3988 return true;
3994 * handy function to loop through an array of files and resolve any filename conflicts
3995 * both in the array of filenames and for what is already on disk.
3996 * not really compatible with the similar function in uploadlib.php
3997 * but this could be used for files/index.php for moving files around.
4000 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4001 foreach ($files as $k => $f) {
4002 if (check_potential_filename($destination,$f,$files)) {
4003 $bits = explode('.', $f);
4004 for ($i = 1; true; $i++) {
4005 $try = sprintf($format, $bits[0], $i, $bits[1]);
4006 if (!check_potential_filename($destination,$try,$files)) {
4007 $files[$k] = $try;
4008 break;
4013 return $files;
4017 * @used by resolve_filename_collisions
4019 function check_potential_filename($destination,$filename,$files) {
4020 if (file_exists($destination.'/'.$filename)) {
4021 return true;
4023 if (count(array_keys($files,$filename)) > 1) {
4024 return true;
4026 return false;
4031 * Returns an array with all the filenames in
4032 * all subdirectories, relative to the given rootdir.
4033 * If excludefile is defined, then that file/directory is ignored
4034 * If getdirs is true, then (sub)directories are included in the output
4035 * If getfiles is true, then files are included in the output
4036 * (at least one of these must be true!)
4038 * @param string $rootdir ?
4039 * @param string $excludefile If defined then the specified file/directory is ignored
4040 * @param bool $descend ?
4041 * @param bool $getdirs If true then (sub)directories are included in the output
4042 * @param bool $getfiles If true then files are included in the output
4043 * @return array An array with all the filenames in
4044 * all subdirectories, relative to the given rootdir
4045 * @todo Finish documenting this function. Add examples of $excludefile usage.
4047 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4049 $dirs = array();
4051 if (!$getdirs and !$getfiles) { // Nothing to show
4052 return $dirs;
4055 if (!is_dir($rootdir)) { // Must be a directory
4056 return $dirs;
4059 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4060 return $dirs;
4063 if (!is_array($excludefiles)) {
4064 $excludefiles = array($excludefiles);
4067 while (false !== ($file = readdir($dir))) {
4068 $firstchar = substr($file, 0, 1);
4069 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4070 continue;
4072 $fullfile = $rootdir .'/'. $file;
4073 if (filetype($fullfile) == 'dir') {
4074 if ($getdirs) {
4075 $dirs[] = $file;
4077 if ($descend) {
4078 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4079 foreach ($subdirs as $subdir) {
4080 $dirs[] = $file .'/'. $subdir;
4083 } else if ($getfiles) {
4084 $dirs[] = $file;
4087 closedir($dir);
4089 asort($dirs);
4091 return $dirs;
4096 * Adds up all the files in a directory and works out the size.
4098 * @param string $rootdir ?
4099 * @param string $excludefile ?
4100 * @return array
4101 * @todo Finish documenting this function
4103 function get_directory_size($rootdir, $excludefile='') {
4105 global $CFG;
4107 // do it this way if we can, it's much faster
4108 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
4109 $command = trim($CFG->pathtodu).' -sk --apparent-size '.escapeshellarg($rootdir);
4110 $output = null;
4111 $return = null;
4112 exec($command,$output,$return);
4113 if (is_array($output)) {
4114 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4118 if (!is_dir($rootdir)) { // Must be a directory
4119 return 0;
4122 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
4123 return 0;
4126 $size = 0;
4128 while (false !== ($file = readdir($dir))) {
4129 $firstchar = substr($file, 0, 1);
4130 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4131 continue;
4133 $fullfile = $rootdir .'/'. $file;
4134 if (filetype($fullfile) == 'dir') {
4135 $size += get_directory_size($fullfile, $excludefile);
4136 } else {
4137 $size += filesize($fullfile);
4140 closedir($dir);
4142 return $size;
4146 * Converts bytes into display form
4148 * @param string $size ?
4149 * @return string
4150 * @staticvar string $gb Localized string for size in gigabytes
4151 * @staticvar string $mb Localized string for size in megabytes
4152 * @staticvar string $kb Localized string for size in kilobytes
4153 * @staticvar string $b Localized string for size in bytes
4154 * @todo Finish documenting this function. Verify return type.
4156 function display_size($size) {
4158 static $gb, $mb, $kb, $b;
4160 if (empty($gb)) {
4161 $gb = get_string('sizegb');
4162 $mb = get_string('sizemb');
4163 $kb = get_string('sizekb');
4164 $b = get_string('sizeb');
4167 if ($size >= 1073741824) {
4168 $size = round($size / 1073741824 * 10) / 10 . $gb;
4169 } else if ($size >= 1048576) {
4170 $size = round($size / 1048576 * 10) / 10 . $mb;
4171 } else if ($size >= 1024) {
4172 $size = round($size / 1024 * 10) / 10 . $kb;
4173 } else {
4174 $size = $size .' '. $b;
4176 return $size;
4180 * Cleans a given filename by removing suspicious or troublesome characters
4181 * Only these are allowed: alphanumeric _ - .
4182 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4184 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4185 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4187 * @param string $string file name
4188 * @return string cleaned file name
4190 function clean_filename($string) {
4191 global $CFG;
4192 if (empty($CFG->unicodecleanfilename)) {
4193 $textlib = textlib_get_instance();
4194 $string = $textlib->specialtoascii($string);
4195 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4196 } else {
4197 //clean only ascii range
4198 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4200 $string = preg_replace("/_+/", '_', $string);
4201 $string = preg_replace("/\.\.+/", '.', $string);
4202 return $string;
4206 /// STRING TRANSLATION ////////////////////////////////////////
4209 * Returns the code for the current language
4211 * @uses $CFG
4212 * @param $USER
4213 * @param $SESSION
4214 * @return string
4216 function current_language() {
4217 global $CFG, $USER, $SESSION, $COURSE;
4219 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
4220 $return = $COURSE->lang;
4222 } else if (!empty($SESSION->lang)) { // Session language can override other settings
4223 $return = $SESSION->lang;
4225 } else if (!empty($USER->lang)) {
4226 $return = $USER->lang;
4228 } else {
4229 $return = $CFG->lang;
4232 if ($return == 'en') {
4233 $return = 'en_utf8';
4236 return $return;
4240 * Prints out a translated string.
4242 * Prints out a translated string using the return value from the {@link get_string()} function.
4244 * Example usage of this function when the string is in the moodle.php file:<br/>
4245 * <code>
4246 * echo '<strong>';
4247 * print_string('wordforstudent');
4248 * echo '</strong>';
4249 * </code>
4251 * Example usage of this function when the string is not in the moodle.php file:<br/>
4252 * <code>
4253 * echo '<h1>';
4254 * print_string('typecourse', 'calendar');
4255 * echo '</h1>';
4256 * </code>
4258 * @param string $identifier The key identifier for the localized string
4259 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4260 * @param mixed $a An object, string or number that can be used
4261 * within translation strings
4263 function print_string($identifier, $module='', $a=NULL) {
4264 echo get_string($identifier, $module, $a);
4268 * fix up the optional data in get_string()/print_string() etc
4269 * ensure possible sprintf() format characters are escaped correctly
4270 * needs to handle arbitrary strings and objects
4271 * @param mixed $a An object, string or number that can be used
4272 * @return mixed the supplied parameter 'cleaned'
4274 function clean_getstring_data( $a ) {
4275 if (is_string($a)) {
4276 return str_replace( '%','%%',$a );
4278 elseif (is_object($a)) {
4279 $a_vars = get_object_vars( $a );
4280 $new_a_vars = array();
4281 foreach ($a_vars as $fname => $a_var) {
4282 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4284 return (object)$new_a_vars;
4286 else {
4287 return $a;
4291 /**
4292 * @return array places to look for lang strings based on the prefix to the
4293 * module name. For example qtype_ in question/type. Used by get_string and
4294 * help.php.
4296 function places_to_search_for_lang_strings() {
4297 global $CFG;
4299 return array(
4300 '__exceptions' => array('moodle', 'langconfig'),
4301 'assignment_' => array('mod/assignment/type'),
4302 'auth_' => array('auth'),
4303 'block_' => array('blocks'),
4304 'datafield_' => array('mod/data/field'),
4305 'datapreset_' => array('mod/data/preset'),
4306 'enrol_' => array('enrol'),
4307 'format_' => array('course/format'),
4308 'qtype_' => array('question/type'),
4309 'report_' => array($CFG->admin.'/report', 'course/report', 'mod/quiz/report'),
4310 'resource_' => array('mod/resource/type'),
4311 '' => array('mod')
4316 * Returns a localized string.
4318 * Returns the translated string specified by $identifier as
4319 * for $module. Uses the same format files as STphp.
4320 * $a is an object, string or number that can be used
4321 * within translation strings
4323 * eg "hello \$a->firstname \$a->lastname"
4324 * or "hello \$a"
4326 * If you would like to directly echo the localized string use
4327 * the function {@link print_string()}
4329 * Example usage of this function involves finding the string you would
4330 * like a local equivalent of and using its identifier and module information
4331 * to retrive it.<br/>
4332 * If you open moodle/lang/en/moodle.php and look near line 1031
4333 * you will find a string to prompt a user for their word for student
4334 * <code>
4335 * $string['wordforstudent'] = 'Your word for Student';
4336 * </code>
4337 * So if you want to display the string 'Your word for student'
4338 * in any language that supports it on your site
4339 * you just need to use the identifier 'wordforstudent'
4340 * <code>
4341 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4343 * </code>
4344 * If the string you want is in another file you'd take a slightly
4345 * different approach. Looking in moodle/lang/en/calendar.php you find
4346 * around line 75:
4347 * <code>
4348 * $string['typecourse'] = 'Course event';
4349 * </code>
4350 * If you want to display the string "Course event" in any language
4351 * supported you would use the identifier 'typecourse' and the module 'calendar'
4352 * (because it is in the file calendar.php):
4353 * <code>
4354 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4355 * </code>
4357 * As a last resort, should the identifier fail to map to a string
4358 * the returned string will be [[ $identifier ]]
4360 * @uses $CFG
4361 * @param string $identifier The key identifier for the localized string
4362 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4363 * @param mixed $a An object, string or number that can be used
4364 * within translation strings
4365 * @param array $extralocations An array of strings with other locations to look for string files
4366 * @return string The localized string.
4368 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4370 global $CFG;
4372 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4373 $langconfigstrs = array('alphabet', 'backupnameformat', 'firstdayofweek', 'locale',
4374 'localewin', 'localewincharset', 'oldcharset',
4375 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4376 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4377 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4378 'thischarset', 'thisdirection', 'thislanguage');
4380 $filetocheck = 'langconfig.php';
4381 $defaultlang = 'en_utf8';
4382 if (in_array($identifier, $langconfigstrs)) {
4383 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4386 $lang = current_language();
4388 if ($module == '') {
4389 $module = 'moodle';
4392 // if $a happens to have % in it, double it so sprintf() doesn't break
4393 if ($a) {
4394 $a = clean_getstring_data( $a );
4397 /// Define the two or three major locations of language strings for this module
4398 $locations = array();
4400 if (!empty($extralocations)) { // Calling code has a good idea where to look
4401 if (is_array($extralocations)) {
4402 $locations += $extralocations;
4403 } else if (is_string($extralocations)) {
4404 $locations[] = $extralocations;
4405 } else {
4406 debugging('Bad lang path provided');
4410 if (isset($CFG->running_installer)) {
4411 $module = 'installer';
4412 $filetocheck = 'installer.php';
4413 $locations += array( $CFG->dirroot.'/install/lang/', $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
4414 $defaultlang = 'en_utf8';
4415 } else {
4416 $locations += array( $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
4419 /// Add extra places to look for strings for particular plugin types.
4420 $rules = places_to_search_for_lang_strings();
4421 $exceptions = $rules['__exceptions'];
4422 unset($rules['__exceptions']);
4424 if (!in_array($module, $exceptions)) {
4425 $dividerpos = strpos($module, '_');
4426 if ($dividerpos === false) {
4427 $type = '';
4428 $plugin = $module;
4429 } else {
4430 $type = substr($module, 0, $dividerpos + 1);
4431 $plugin = substr($module, $dividerpos + 1);
4433 if (!empty($rules[$type])) {
4434 foreach ($rules[$type] as $location) {
4435 $locations[] = $CFG->dirroot . "/$location/$plugin/lang/";
4440 /// First check all the normal locations for the string in the current language
4441 $resultstring = '';
4442 foreach ($locations as $location) {
4443 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4444 if (file_exists($locallangfile)) {
4445 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4446 eval($result);
4447 return $resultstring;
4450 //if local directory not found, or particular string does not exist in local direcotry
4451 $langfile = $location.$lang.'/'.$module.'.php';
4452 if (file_exists($langfile)) {
4453 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4454 eval($result);
4455 return $resultstring;
4460 /// If the preferred language was English (utf8) we can abort now
4461 /// saving some checks beacuse it's the only "root" lang
4462 if ($lang == 'en_utf8') {
4463 return '[['. $identifier .']]';
4466 /// Is a parent language defined? If so, try to find this string in a parent language file
4468 foreach ($locations as $location) {
4469 $langfile = $location.$lang.'/'.$filetocheck;
4470 if (file_exists($langfile)) {
4471 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4472 eval($result);
4473 if (!empty($parentlang)) { // found it!
4475 //first, see if there's a local file for parent
4476 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4477 if (file_exists($locallangfile)) {
4478 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4479 eval($result);
4480 return $resultstring;
4484 //if local directory not found, or particular string does not exist in local direcotry
4485 $langfile = $location.$parentlang.'/'.$module.'.php';
4486 if (file_exists($langfile)) {
4487 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4488 eval($result);
4489 return $resultstring;
4497 /// Our only remaining option is to try English
4499 foreach ($locations as $location) {
4500 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4501 if (file_exists($locallangfile)) {
4502 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4503 eval($result);
4504 return $resultstring;
4508 //if local_en not found, or string not found in local_en
4509 $langfile = $location.$defaultlang.'/'.$module.'.php';
4511 if (file_exists($langfile)) {
4512 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4513 eval($result);
4514 return $resultstring;
4519 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4520 /// if it hasn't been queried before.
4521 if ($defaultlang == 'en') {
4522 $defaultlang = 'en_utf8';
4523 foreach ($locations as $location) {
4524 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4525 if (file_exists($locallangfile)) {
4526 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4527 eval($result);
4528 return $resultstring;
4532 //if local_en not found, or string not found in local_en
4533 $langfile = $location.$defaultlang.'/'.$module.'.php';
4535 if (file_exists($langfile)) {
4536 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4537 eval($result);
4538 return $resultstring;
4544 return '[['.$identifier.']]'; // Last resort
4548 * This function is only used from {@link get_string()}.
4550 * @internal Only used from get_string, not meant to be public API
4551 * @param string $identifier ?
4552 * @param string $langfile ?
4553 * @param string $destination ?
4554 * @return string|false ?
4555 * @staticvar array $strings Localized strings
4556 * @access private
4557 * @todo Finish documenting this function.
4559 function get_string_from_file($identifier, $langfile, $destination) {
4561 static $strings; // Keep the strings cached in memory.
4563 if (empty($strings[$langfile])) {
4564 $string = array();
4565 include ($langfile);
4566 $strings[$langfile] = $string;
4567 } else {
4568 $string = &$strings[$langfile];
4571 if (!isset ($string[$identifier])) {
4572 return false;
4575 return $destination .'= sprintf("'. $string[$identifier] .'");';
4579 * Converts an array of strings to their localized value.
4581 * @param array $array An array of strings
4582 * @param string $module The language module that these strings can be found in.
4583 * @return string
4585 function get_strings($array, $module='') {
4587 $string = NULL;
4588 foreach ($array as $item) {
4589 $string->$item = get_string($item, $module);
4591 return $string;
4595 * Returns a list of language codes and their full names
4596 * hides the _local files from everyone.
4597 * @param bool refreshcache force refreshing of lang cache
4598 * @param bool returnall ignore langlist, return all languages available
4599 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4601 function get_list_of_languages($refreshcache=false, $returnall=false) {
4603 global $CFG;
4605 $languages = array();
4607 $filetocheck = 'langconfig.php';
4609 if (!$refreshcache && !$returnall && !empty($CFG->langcache) && file_exists($CFG->dataroot .'/cache/languages')) {
4610 /// read available langs from cache
4612 $lines = file($CFG->dataroot .'/cache/languages');
4613 foreach ($lines as $line) {
4614 $line = trim($line);
4615 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4616 $languages[$matches[1]] = $matches[2];
4619 unset($lines); unset($line); unset($matches);
4620 return $languages;
4623 if (!$returnall && !empty($CFG->langlist)) {
4624 /// return only languages allowed in langlist admin setting
4626 $langlist = explode(',', $CFG->langlist);
4627 // fix short lang names first - non existing langs are skipped anyway...
4628 foreach ($langlist as $lang) {
4629 if (strpos($lang, '_utf8') === false) {
4630 $langlist[] = $lang.'_utf8';
4633 // find existing langs from langlist
4634 foreach ($langlist as $lang) {
4635 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4636 if (strstr($lang, '_local')!==false) {
4637 continue;
4639 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4640 $shortlang = substr($lang, 0, -5);
4641 } else {
4642 $shortlang = $lang;
4644 /// Search under dirroot/lang
4645 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4646 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4647 if (!empty($string['thislanguage'])) {
4648 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4650 unset($string);
4652 /// And moodledata/lang
4653 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4654 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4655 if (!empty($string['thislanguage'])) {
4656 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4658 unset($string);
4662 } else {
4663 /// return all languages available in system
4664 /// Fetch langs from moodle/lang directory
4665 $langdirs = get_list_of_plugins('lang');
4666 /// Fetch langs from moodledata/lang directory
4667 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot);
4668 /// Merge both lists of langs
4669 $langdirs = array_merge($langdirs, $langdirs2);
4670 /// Sort all
4671 asort($langdirs);
4672 /// Get some info from each lang (first from moodledata, then from moodle)
4673 foreach ($langdirs as $lang) {
4674 if (strstr($lang, '_local')!==false) {
4675 continue;
4677 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4678 $shortlang = substr($lang, 0, -5);
4679 } else {
4680 $shortlang = $lang;
4682 /// Search under moodledata/lang
4683 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4684 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4685 if (!empty($string['thislanguage'])) {
4686 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4688 unset($string);
4690 /// And dirroot/lang
4691 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4692 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4693 if (!empty($string['thislanguage'])) {
4694 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4696 unset($string);
4701 if ($refreshcache && !empty($CFG->langcache)) {
4702 if ($returnall) {
4703 // we have a list of all langs only, just delete old cache
4704 @unlink($CFG->dataroot.'/cache/languages');
4706 } else {
4707 // store the list of allowed languages
4708 if ($file = fopen($CFG->dataroot .'/cache/languages', 'w')) {
4709 foreach ($languages as $key => $value) {
4710 fwrite($file, "$key $value\n");
4712 fclose($file);
4717 return $languages;
4721 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4722 * (cheking that such charset is supported by the texlib library!)
4724 * @return array And associative array with contents in the form of charset => charset
4726 function get_list_of_charsets() {
4728 $charsets = array(
4729 'EUC-JP' => 'EUC-JP',
4730 'ISO-2022-JP'=> 'ISO-2022-JP',
4731 'ISO-8859-1' => 'ISO-8859-1',
4732 'SHIFT-JIS' => 'SHIFT-JIS',
4733 'GB2312' => 'GB2312',
4734 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4735 'UTF-8' => 'UTF-8');
4737 asort($charsets);
4739 return $charsets;
4743 * Returns a list of country names in the current language
4745 * @uses $CFG
4746 * @uses $USER
4747 * @return array
4749 function get_list_of_countries() {
4750 global $CFG, $USER;
4752 $lang = current_language();
4754 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php') &&
4755 !file_exists($CFG->dataroot.'/lang/'. $lang .'/countries.php')) {
4756 if ($parentlang = get_string('parentlanguage')) {
4757 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/countries.php') ||
4758 file_exists($CFG->dataroot.'/lang/'. $parentlang .'/countries.php')) {
4759 $lang = $parentlang;
4760 } else {
4761 $lang = 'en_utf8'; // countries.php must exist in this pack
4763 } else {
4764 $lang = 'en_utf8'; // countries.php must exist in this pack
4768 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/countries.php')) {
4769 include($CFG->dataroot .'/lang/'. $lang .'/countries.php');
4770 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
4771 include($CFG->dirroot .'/lang/'. $lang .'/countries.php');
4774 if (!empty($string)) {
4775 asort($string);
4778 return $string;
4782 * Returns a list of valid and compatible themes
4784 * @uses $CFG
4785 * @return array
4787 function get_list_of_themes() {
4789 global $CFG;
4791 $themes = array();
4793 if (!empty($CFG->themelist)) { // use admin's list of themes
4794 $themelist = explode(',', $CFG->themelist);
4795 } else {
4796 $themelist = get_list_of_plugins("theme");
4799 foreach ($themelist as $key => $theme) {
4800 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
4801 continue;
4803 $THEME = new object(); // Note this is not the global one!! :-)
4804 include("$CFG->themedir/$theme/config.php");
4805 if (!isset($THEME->sheets)) { // Not a valid 1.5 theme
4806 continue;
4808 $themes[$theme] = $theme;
4810 asort($themes);
4812 return $themes;
4817 * Returns a list of picture names in the current or specified language
4819 * @uses $CFG
4820 * @return array
4822 function get_list_of_pixnames($lang = '') {
4823 global $CFG;
4825 if (empty($lang)) {
4826 $lang = current_language();
4829 $string = array();
4831 $path = $CFG->dirroot .'/lang/en_utf8/pix.php'; // always exists
4833 if (file_exists($CFG->dataroot .'/lang/'. $lang .'_local/pix.php')) {
4834 $path = $CFG->dataroot .'/lang/'. $lang .'_local/pix.php';
4836 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
4837 $path = $CFG->dirroot .'/lang/'. $lang .'/pix.php';
4839 } else if (file_exists($CFG->dataroot .'/lang/'. $lang .'/pix.php')) {
4840 $path = $CFG->dataroot .'/lang/'. $lang .'/pix.php';
4842 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
4843 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
4846 include($path);
4848 return $string;
4852 * Returns a list of timezones in the current language
4854 * @uses $CFG
4855 * @return array
4857 function get_list_of_timezones() {
4858 global $CFG;
4860 $timezones = array();
4862 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix.'timezone GROUP BY name')) {
4863 foreach($rawtimezones as $timezone) {
4864 if (!empty($timezone->name)) {
4865 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
4866 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
4867 $timezones[$timezone->name] = $timezone->name;
4873 asort($timezones);
4875 for ($i = -13; $i <= 13; $i += .5) {
4876 $tzstring = 'GMT';
4877 if ($i < 0) {
4878 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
4879 } else if ($i > 0) {
4880 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
4881 } else {
4882 $timezones[sprintf("%.1f", $i)] = $tzstring;
4886 return $timezones;
4890 * Returns a list of currencies in the current language
4892 * @uses $CFG
4893 * @uses $USER
4894 * @return array
4896 function get_list_of_currencies() {
4897 global $CFG, $USER;
4899 $lang = current_language();
4901 if (!file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
4902 if ($parentlang = get_string('parentlanguage')) {
4903 if (file_exists($CFG->dataroot .'/lang/'. $parentlang .'/currencies.php')) {
4904 $lang = $parentlang;
4905 } else {
4906 $lang = 'en_utf8'; // currencies.php must exist in this pack
4908 } else {
4909 $lang = 'en_utf8'; // currencies.php must exist in this pack
4913 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
4914 include_once($CFG->dataroot .'/lang/'. $lang .'/currencies.php');
4915 } else { //if en_utf8 is not installed in dataroot
4916 include_once($CFG->dirroot .'/lang/'. $lang .'/currencies.php');
4919 if (!empty($string)) {
4920 asort($string);
4923 return $string;
4929 * Can include a given document file (depends on second
4930 * parameter) or just return info about it.
4932 * @uses $CFG
4933 * @param string $file ?
4934 * @param bool $include ?
4935 * @return ?
4936 * @todo Finish documenting this function
4938 function document_file($file, $include=true) {
4939 global $CFG;
4941 $file = clean_filename($file);
4943 if (empty($file)) {
4944 return false;
4947 $langs = array(current_language(), get_string('parentlanguage'), 'en');
4949 foreach ($langs as $lang) {
4950 $info = new object();
4951 $info->filepath = $CFG->dirroot .'/lang/'. $lang .'/docs/'. $file;
4952 $info->urlpath = $CFG->wwwroot .'/lang/'. $lang .'/docs/'. $file;
4954 if (file_exists($info->filepath)) {
4955 if ($include) {
4956 include($info->filepath);
4958 return $info;
4962 return false;
4965 /// ENCRYPTION ////////////////////////////////////////////////
4968 * rc4encrypt
4970 * @param string $data ?
4971 * @return string
4972 * @todo Finish documenting this function
4974 function rc4encrypt($data) {
4975 $password = 'nfgjeingjk';
4976 return endecrypt($password, $data, '');
4980 * rc4decrypt
4982 * @param string $data ?
4983 * @return string
4984 * @todo Finish documenting this function
4986 function rc4decrypt($data) {
4987 $password = 'nfgjeingjk';
4988 return endecrypt($password, $data, 'de');
4992 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
4994 * @param string $pwd ?
4995 * @param string $data ?
4996 * @param string $case ?
4997 * @return string
4998 * @todo Finish documenting this function
5000 function endecrypt ($pwd, $data, $case) {
5002 if ($case == 'de') {
5003 $data = urldecode($data);
5006 $key[] = '';
5007 $box[] = '';
5008 $temp_swap = '';
5009 $pwd_length = 0;
5011 $pwd_length = strlen($pwd);
5013 for ($i = 0; $i <= 255; $i++) {
5014 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
5015 $box[$i] = $i;
5018 $x = 0;
5020 for ($i = 0; $i <= 255; $i++) {
5021 $x = ($x + $box[$i] + $key[$i]) % 256;
5022 $temp_swap = $box[$i];
5023 $box[$i] = $box[$x];
5024 $box[$x] = $temp_swap;
5027 $temp = '';
5028 $k = '';
5030 $cipherby = '';
5031 $cipher = '';
5033 $a = 0;
5034 $j = 0;
5036 for ($i = 0; $i < strlen($data); $i++) {
5037 $a = ($a + 1) % 256;
5038 $j = ($j + $box[$a]) % 256;
5039 $temp = $box[$a];
5040 $box[$a] = $box[$j];
5041 $box[$j] = $temp;
5042 $k = $box[(($box[$a] + $box[$j]) % 256)];
5043 $cipherby = ord(substr($data, $i, 1)) ^ $k;
5044 $cipher .= chr($cipherby);
5047 if ($case == 'de') {
5048 $cipher = urldecode(urlencode($cipher));
5049 } else {
5050 $cipher = urlencode($cipher);
5053 return $cipher;
5057 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5061 * Call this function to add an event to the calendar table
5062 * and to call any calendar plugins
5064 * @uses $CFG
5065 * @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:
5066 * <ul>
5067 * <li><b>$event->name</b> - Name for the event
5068 * <li><b>$event->description</b> - Description of the event (defaults to '')
5069 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5070 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5071 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5072 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5073 * <li><b>$event->modulename</b> - Name of the module that creates this event
5074 * <li><b>$event->instance</b> - Instance of the module that owns this event
5075 * <li><b>$event->eventtype</b> - The type info together with the module info could
5076 * be used by calendar plugins to decide how to display event
5077 * <li><b>$event->timestart</b>- Timestamp for start of event
5078 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5079 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5080 * </ul>
5081 * @return int The id number of the resulting record
5083 function add_event($event) {
5085 global $CFG;
5087 $event->timemodified = time();
5089 if (!$event->id = insert_record('event', $event)) {
5090 return false;
5093 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
5094 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5095 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5096 $calendar_add_event = $CFG->calendar.'_add_event';
5097 if (function_exists($calendar_add_event)) {
5098 $calendar_add_event($event);
5103 return $event->id;
5107 * Call this function to update an event in the calendar table
5108 * the event will be identified by the id field of the $event object.
5110 * @uses $CFG
5111 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5112 * @return bool
5114 function update_event($event) {
5116 global $CFG;
5118 $event->timemodified = time();
5120 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5121 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5122 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5123 $calendar_update_event = $CFG->calendar.'_update_event';
5124 if (function_exists($calendar_update_event)) {
5125 $calendar_update_event($event);
5129 return update_record('event', $event);
5133 * Call this function to delete the event with id $id from calendar table.
5135 * @uses $CFG
5136 * @param int $id The id of an event from the 'calendar' table.
5137 * @return array An associative array with the results from the SQL call.
5138 * @todo Verify return type
5140 function delete_event($id) {
5142 global $CFG;
5144 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
5145 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5146 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5147 $calendar_delete_event = $CFG->calendar.'_delete_event';
5148 if (function_exists($calendar_delete_event)) {
5149 $calendar_delete_event($id);
5153 return delete_records('event', 'id', $id);
5157 * Call this function to hide an event in the calendar table
5158 * the event will be identified by the id field of the $event object.
5160 * @uses $CFG
5161 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5162 * @return array An associative array with the results from the SQL call.
5163 * @todo Verify return type
5165 function hide_event($event) {
5166 global $CFG;
5168 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5169 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5170 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5171 $calendar_hide_event = $CFG->calendar.'_hide_event';
5172 if (function_exists($calendar_hide_event)) {
5173 $calendar_hide_event($event);
5177 return set_field('event', 'visible', 0, 'id', $event->id);
5181 * Call this function to unhide an event in the calendar table
5182 * the event will be identified by the id field of the $event object.
5184 * @uses $CFG
5185 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5186 * @return array An associative array with the results from the SQL call.
5187 * @todo Verify return type
5189 function show_event($event) {
5190 global $CFG;
5192 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5193 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5194 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5195 $calendar_show_event = $CFG->calendar.'_show_event';
5196 if (function_exists($calendar_show_event)) {
5197 $calendar_show_event($event);
5201 return set_field('event', 'visible', 1, 'id', $event->id);
5205 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5208 * Lists plugin directories within some directory
5210 * @uses $CFG
5211 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5212 * @param string $exclude dir name to exclude from the list (defaults to none)
5213 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5214 * @return array of plugins found under the requested parameters
5216 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5218 global $CFG;
5220 $plugins = array();
5222 if (empty($basedir)) {
5224 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5225 switch ($plugin) {
5226 case "theme":
5227 $basedir = $CFG->themedir;
5228 break;
5230 default:
5231 $basedir = $CFG->dirroot .'/'. $plugin;
5234 } else {
5235 $basedir = $basedir .'/'. $plugin;
5238 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5239 $dirhandle = opendir($basedir);
5240 while (false !== ($dir = readdir($dirhandle))) {
5241 $firstchar = substr($dir, 0, 1);
5242 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5243 continue;
5245 if (filetype($basedir .'/'. $dir) != 'dir') {
5246 continue;
5248 $plugins[] = $dir;
5250 closedir($dirhandle);
5252 if ($plugins) {
5253 asort($plugins);
5255 return $plugins;
5259 * Returns true if the current version of PHP is greater that the specified one.
5261 * @param string $version The version of php being tested.
5262 * @return bool
5264 function check_php_version($version='4.1.0') {
5265 return (version_compare(phpversion(), $version) >= 0);
5270 * Checks to see if is a browser matches the specified
5271 * brand and is equal or better version.
5273 * @uses $_SERVER
5274 * @param string $brand The browser identifier being tested
5275 * @param int $version The version of the browser
5276 * @return bool true if the given version is below that of the detected browser
5278 function check_browser_version($brand='MSIE', $version=5.5) {
5279 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5280 return false;
5283 $agent = $_SERVER['HTTP_USER_AGENT'];
5285 switch ($brand) {
5287 case 'Camino': /// Mozilla Firefox browsers
5289 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5290 if (version_compare($match[1], $version) >= 0) {
5291 return true;
5294 break;
5297 case 'Firefox': /// Mozilla Firefox browsers
5299 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5300 if (version_compare($match[1], $version) >= 0) {
5301 return true;
5304 break;
5307 case 'Gecko': /// Gecko based browsers
5309 if (substr_count($agent, 'Camino')) {
5310 // MacOS X Camino support
5311 $version = 20041110;
5314 // the proper string - Gecko/CCYYMMDD Vendor/Version
5315 // Faster version and work-a-round No IDN problem.
5316 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5317 if ($match[1] > $version) {
5318 return true;
5321 break;
5324 case 'MSIE': /// Internet Explorer
5326 if (strpos($agent, 'Opera')) { // Reject Opera
5327 return false;
5329 $string = explode(';', $agent);
5330 if (!isset($string[1])) {
5331 return false;
5333 $string = explode(' ', trim($string[1]));
5334 if (!isset($string[0]) and !isset($string[1])) {
5335 return false;
5337 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5338 return true;
5340 break;
5342 case 'Opera': /// Opera
5344 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5345 if (version_compare($match[1], $version) >= 0) {
5346 return true;
5349 break;
5351 case 'Safari': /// Safari
5352 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5353 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5354 return false;
5355 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5356 return false;
5357 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5358 return false;
5361 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5362 if (version_compare($match[1], $version) >= 0) {
5363 return true;
5367 break;
5371 return false;
5375 * This function makes the return value of ini_get consistent if you are
5376 * setting server directives through the .htaccess file in apache.
5377 * Current behavior for value set from php.ini On = 1, Off = [blank]
5378 * Current behavior for value set from .htaccess On = On, Off = Off
5379 * Contributed by jdell @ unr.edu
5381 * @param string $ini_get_arg ?
5382 * @return bool
5383 * @todo Finish documenting this function
5385 function ini_get_bool($ini_get_arg) {
5386 $temp = ini_get($ini_get_arg);
5388 if ($temp == '1' or strtolower($temp) == 'on') {
5389 return true;
5391 return false;
5395 * Compatibility stub to provide backward compatibility
5397 * Determines if the HTML editor is enabled.
5398 * @deprecated Use {@link can_use_html_editor()} instead.
5400 function can_use_richtext_editor() {
5401 return can_use_html_editor();
5405 * Determines if the HTML editor is enabled.
5407 * This depends on site and user
5408 * settings, as well as the current browser being used.
5410 * @return string|false Returns false if editor is not being used, otherwise
5411 * returns 'MSIE' or 'Gecko'.
5413 function can_use_html_editor() {
5414 global $USER, $CFG;
5416 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
5417 if (check_browser_version('MSIE', 5.5)) {
5418 return 'MSIE';
5419 } else if (check_browser_version('Gecko', 20030516)) {
5420 return 'Gecko';
5423 return false;
5427 * Hack to find out the GD version by parsing phpinfo output
5429 * @return int GD version (1, 2, or 0)
5431 function check_gd_version() {
5432 $gdversion = 0;
5434 if (function_exists('gd_info')){
5435 $gd_info = gd_info();
5436 if (substr_count($gd_info['GD Version'], '2.')) {
5437 $gdversion = 2;
5438 } else if (substr_count($gd_info['GD Version'], '1.')) {
5439 $gdversion = 1;
5442 } else {
5443 ob_start();
5444 phpinfo(8);
5445 $phpinfo = ob_get_contents();
5446 ob_end_clean();
5448 $phpinfo = explode("\n", $phpinfo);
5451 foreach ($phpinfo as $text) {
5452 $parts = explode('</td>', $text);
5453 foreach ($parts as $key => $val) {
5454 $parts[$key] = trim(strip_tags($val));
5456 if ($parts[0] == 'GD Version') {
5457 if (substr_count($parts[1], '2.0')) {
5458 $parts[1] = '2.0';
5460 $gdversion = intval($parts[1]);
5465 return $gdversion; // 1, 2 or 0
5469 * Determine if moodle installation requires update
5471 * Checks version numbers of main code and all modules to see
5472 * if there are any mismatches
5474 * @uses $CFG
5475 * @return bool
5477 function moodle_needs_upgrading() {
5478 global $CFG;
5480 $version = null;
5481 include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
5482 if ($CFG->version) {
5483 if ($version > $CFG->version) {
5484 return true;
5486 if ($mods = get_list_of_plugins('mod')) {
5487 foreach ($mods as $mod) {
5488 $fullmod = $CFG->dirroot .'/mod/'. $mod;
5489 $module = new object();
5490 if (!is_readable($fullmod .'/version.php')) {
5491 notify('Module "'. $mod .'" is not readable - check permissions');
5492 continue;
5494 include_once($fullmod .'/version.php'); # defines $module with version etc
5495 if ($currmodule = get_record('modules', 'name', $mod)) {
5496 if ($module->version > $currmodule->version) {
5497 return true;
5502 } else {
5503 return true;
5505 return false;
5509 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5512 * Notify admin users or admin user of any failed logins (since last notification).
5514 * @uses $CFG
5515 * @uses $db
5516 * @uses HOURSECS
5518 function notify_login_failures() {
5519 global $CFG, $db;
5521 switch ($CFG->notifyloginfailures) {
5522 case 'mainadmin' :
5523 $recip = array(get_admin());
5524 break;
5525 case 'alladmins':
5526 $recip = get_admins();
5527 break;
5530 if (empty($CFG->lastnotifyfailure)) {
5531 $CFG->lastnotifyfailure=0;
5534 // we need to deal with the threshold stuff first.
5535 if (empty($CFG->notifyloginthreshold)) {
5536 $CFG->notifyloginthreshold = 10; // default to something sensible.
5539 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5540 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold);
5542 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5543 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold);
5545 if ($notifyipsrs) {
5546 $ipstr = '';
5547 while ($row = rs_fetch_next_record($notifyipsrs)) {
5548 $ipstr .= "'". $row->ip ."',";
5550 rs_close($notifyipsrs);
5551 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5553 if ($notifyusersrs) {
5554 $userstr = '';
5555 while ($row = rs_fetch_next_record($notifyusersrs)) {
5556 $userstr .= "'". $row->info ."',";
5558 rs_close($notifyusersrs);
5559 $userstr = substr($userstr,0,strlen($userstr)-1);
5562 if (strlen($userstr) > 0 || strlen($ipstr) > 0) {
5563 $count = 0;
5564 $logs = get_logs('time > '. $CFG->lastnotifyfailure .' AND module=\'login\' AND action=\'error\' '
5565 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ? ' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5566 : ((strlen($ipstr) != 0) ? ' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5568 // 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
5569 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS) > $CFG->lastnotifyfailure)
5570 and is_array($logs) and count($logs) > 0) {
5572 $message = '';
5573 $site = get_site();
5574 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
5575 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot)
5576 .(($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n";
5577 foreach ($logs as $log) {
5578 $log->time = userdate($log->time);
5579 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5581 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
5582 foreach ($recip as $admin) {
5583 mtrace('Emailing '. $admin->username .' about '. count($logs) .' failed login attempts');
5584 email_to_user($admin,get_admin(),$subject,$message);
5586 $conf = new object();
5587 $conf->name = 'lastnotifyfailure';
5588 $conf->value = time();
5589 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5590 $conf->id = $current->id;
5591 if (! update_record('config', $conf)) {
5592 mtrace('Could not update last notify time');
5595 } else if (! insert_record('config', $conf)) {
5596 mtrace('Could not set last notify time');
5603 * moodle_setlocale
5605 * @uses $CFG
5606 * @param string $locale ?
5607 * @todo Finish documenting this function
5609 function moodle_setlocale($locale='') {
5611 global $CFG;
5613 static $currentlocale = ''; // last locale caching
5615 $oldlocale = $currentlocale;
5617 /// Fetch the correct locale based on ostype
5618 if($CFG->ostype == 'WINDOWS') {
5619 $stringtofetch = 'localewin';
5620 } else {
5621 $stringtofetch = 'locale';
5624 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5625 if (!empty($locale)) {
5626 $currentlocale = $locale;
5627 } else if (!empty($CFG->locale)) { // override locale for all language packs
5628 $currentlocale = $CFG->locale;
5629 } else {
5630 $currentlocale = get_string($stringtofetch);
5633 /// do nothing if locale already set up
5634 if ($oldlocale == $currentlocale) {
5635 return;
5638 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5639 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5640 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5642 /// Get current values
5643 $monetary= setlocale (LC_MONETARY, 0);
5644 $numeric = setlocale (LC_NUMERIC, 0);
5645 $ctype = setlocale (LC_CTYPE, 0);
5646 if ($CFG->ostype != 'WINDOWS') {
5647 $messages= setlocale (LC_MESSAGES, 0);
5649 /// Set locale to all
5650 setlocale (LC_ALL, $currentlocale);
5651 /// Set old values
5652 setlocale (LC_MONETARY, $monetary);
5653 setlocale (LC_NUMERIC, $numeric);
5654 if ($CFG->ostype != 'WINDOWS') {
5655 setlocale (LC_MESSAGES, $messages);
5657 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5658 setlocale (LC_CTYPE, $ctype);
5663 * Converts string to lowercase using most compatible function available.
5665 * @param string $string The string to convert to all lowercase characters.
5666 * @param string $encoding The encoding on the string.
5667 * @return string
5668 * @todo Add examples of calling this function with/without encoding types
5669 * @deprecated Use textlib->strtolower($text) instead.
5671 function moodle_strtolower ($string, $encoding='') {
5673 //If not specified use utf8
5674 if (empty($encoding)) {
5675 $encoding = 'UTF-8';
5677 //Use text services
5678 $textlib = textlib_get_instance();
5680 return $textlib->strtolower($string, $encoding);
5684 * Count words in a string.
5686 * Words are defined as things between whitespace.
5688 * @param string $string The text to be searched for words.
5689 * @return int The count of words in the specified string
5691 function count_words($string) {
5692 $string = strip_tags($string);
5693 return count(preg_split("/\w\b/", $string)) - 1;
5696 /** Count letters in a string.
5698 * Letters are defined as chars not in tags and different from whitespace.
5700 * @param string $string The text to be searched for letters.
5701 * @return int The count of letters in the specified text.
5703 function count_letters($string) {
5704 /// Loading the textlib singleton instance. We are going to need it.
5705 $textlib = textlib_get_instance();
5707 $string = strip_tags($string); // Tags are out now
5708 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5710 return $textlib->strlen($string);
5714 * Generate and return a random string of the specified length.
5716 * @param int $length The length of the string to be created.
5717 * @return string
5719 function random_string ($length=15) {
5720 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5721 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5722 $pool .= '0123456789';
5723 $poollen = strlen($pool);
5724 mt_srand ((double) microtime() * 1000000);
5725 $string = '';
5726 for ($i = 0; $i < $length; $i++) {
5727 $string .= substr($pool, (mt_rand()%($poollen)), 1);
5729 return $string;
5733 * Given some text (which may contain HTML) and an ideal length,
5734 * this function truncates the text neatly on a word boundary if possible
5736 function shorten_text($text, $ideal=30) {
5738 global $CFG;
5741 $i = 0;
5742 $tag = false;
5743 $length = strlen($text);
5744 $count = 0;
5745 $stopzone = false;
5746 $truncate = 0;
5748 if ($length <= $ideal) {
5749 return $text;
5752 for ($i=0; $i<$length; $i++) {
5753 $char = $text[$i];
5755 switch ($char) {
5756 case "<":
5757 $tag = true;
5758 break;
5759 case ">":
5760 $tag = false;
5761 break;
5762 default:
5763 if (!$tag) {
5764 if ($stopzone) {
5765 if ($char == '.' or $char == ' ') {
5766 $truncate = $i+1;
5767 break 2;
5768 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5769 $truncate = $i; // can be truncated at any UTF-8
5770 break 2; // character boundary.
5773 $count++;
5775 break;
5777 if (!$stopzone) {
5778 if ($count > $ideal) {
5779 $stopzone = true;
5784 if (!$truncate) {
5785 $truncate = $i;
5788 $ellipse = ($truncate < $length) ? '...' : '';
5790 return substr($text, 0, $truncate).$ellipse;
5795 * Given dates in seconds, how many weeks is the date from startdate
5796 * The first week is 1, the second 2 etc ...
5798 * @uses WEEKSECS
5799 * @param ? $startdate ?
5800 * @param ? $thedate ?
5801 * @return string
5802 * @todo Finish documenting this function
5804 function getweek ($startdate, $thedate) {
5805 if ($thedate < $startdate) { // error
5806 return 0;
5809 return floor(($thedate - $startdate) / WEEKSECS) + 1;
5813 * returns a randomly generated password of length $maxlen. inspired by
5814 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
5816 * @param int $maxlength The maximum size of the password being generated.
5817 * @return string
5819 function generate_password($maxlen=10) {
5820 global $CFG;
5822 $fillers = '1234567890!$-+';
5823 $wordlist = file($CFG->wordlist);
5825 srand((double) microtime() * 1000000);
5826 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5827 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5828 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
5830 return substr($word1 . $filler1 . $word2, 0, $maxlen);
5834 * Given a float, prints it nicely
5836 * @param float $num The float to print
5837 * @param int $places The number of decimal places to print.
5838 * @return string
5840 function format_float($num, $places=1) {
5841 return sprintf("%.$places"."f", $num);
5845 * Given a simple array, this shuffles it up just like shuffle()
5846 * Unlike PHP's shuffle() ihis function works on any machine.
5848 * @param array $array The array to be rearranged
5849 * @return array
5851 function swapshuffle($array) {
5853 srand ((double) microtime() * 10000000);
5854 $last = count($array) - 1;
5855 for ($i=0;$i<=$last;$i++) {
5856 $from = rand(0,$last);
5857 $curr = $array[$i];
5858 $array[$i] = $array[$from];
5859 $array[$from] = $curr;
5861 return $array;
5865 * Like {@link swapshuffle()}, but works on associative arrays
5867 * @param array $array The associative array to be rearranged
5868 * @return array
5870 function swapshuffle_assoc($array) {
5873 $newkeys = swapshuffle(array_keys($array));
5874 foreach ($newkeys as $newkey) {
5875 $newarray[$newkey] = $array[$newkey];
5877 return $newarray;
5881 * Given an arbitrary array, and a number of draws,
5882 * this function returns an array with that amount
5883 * of items. The indexes are retained.
5885 * @param array $array ?
5886 * @param ? $draws ?
5887 * @return ?
5888 * @todo Finish documenting this function
5890 function draw_rand_array($array, $draws) {
5891 srand ((double) microtime() * 10000000);
5893 $return = array();
5895 $last = count($array);
5897 if ($draws > $last) {
5898 $draws = $last;
5901 while ($draws > 0) {
5902 $last--;
5904 $keys = array_keys($array);
5905 $rand = rand(0, $last);
5907 $return[$keys[$rand]] = $array[$keys[$rand]];
5908 unset($array[$keys[$rand]]);
5910 $draws--;
5913 return $return;
5917 * microtime_diff
5919 * @param string $a ?
5920 * @param string $b ?
5921 * @return string
5922 * @todo Finish documenting this function
5924 function microtime_diff($a, $b) {
5925 list($a_dec, $a_sec) = explode(' ', $a);
5926 list($b_dec, $b_sec) = explode(' ', $b);
5927 return $b_sec - $a_sec + $b_dec - $a_dec;
5931 * Given a list (eg a,b,c,d,e) this function returns
5932 * an array of 1->a, 2->b, 3->c etc
5934 * @param array $list ?
5935 * @param string $separator ?
5936 * @todo Finish documenting this function
5938 function make_menu_from_list($list, $separator=',') {
5940 $array = array_reverse(explode($separator, $list), true);
5941 foreach ($array as $key => $item) {
5942 $outarray[$key+1] = trim($item);
5944 return $outarray;
5948 * Creates an array that represents all the current grades that
5949 * can be chosen using the given grading type. Negative numbers
5950 * are scales, zero is no grade, and positive numbers are maximum
5951 * grades.
5953 * @param int $gradingtype ?
5954 * return int
5955 * @todo Finish documenting this function
5957 function make_grades_menu($gradingtype) {
5958 $grades = array();
5959 if ($gradingtype < 0) {
5960 if ($scale = get_record('scale', 'id', - $gradingtype)) {
5961 return make_menu_from_list($scale->scale);
5963 } else if ($gradingtype > 0) {
5964 for ($i=$gradingtype; $i>=0; $i--) {
5965 $grades[$i] = $i .' / '. $gradingtype;
5967 return $grades;
5969 return $grades;
5973 * This function returns the nummber of activities
5974 * using scaleid in a courseid
5976 * @param int $courseid ?
5977 * @param int $scaleid ?
5978 * @return int
5979 * @todo Finish documenting this function
5981 function course_scale_used($courseid, $scaleid) {
5983 global $CFG;
5985 $return = 0;
5987 if (!empty($scaleid)) {
5988 if ($cms = get_course_mods($courseid)) {
5989 foreach ($cms as $cm) {
5990 //Check cm->name/lib.php exists
5991 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
5992 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
5993 $function_name = $cm->modname.'_scale_used';
5994 if (function_exists($function_name)) {
5995 if ($function_name($cm->instance,$scaleid)) {
5996 $return++;
6003 return $return;
6007 * This function returns the nummber of activities
6008 * using scaleid in the entire site
6010 * @param int $scaleid ?
6011 * @return int
6012 * @todo Finish documenting this function. Is return type correct?
6014 function site_scale_used($scaleid,&$courses) {
6016 global $CFG;
6018 $return = 0;
6020 if (!is_array($courses) || count($courses) == 0) {
6021 $courses = get_courses("all",false,"c.id,c.shortname");
6024 if (!empty($scaleid)) {
6025 if (is_array($courses) && count($courses) > 0) {
6026 foreach ($courses as $course) {
6027 $return += course_scale_used($course->id,$scaleid);
6031 return $return;
6035 * make_unique_id_code
6037 * @param string $extra ?
6038 * @return string
6039 * @todo Finish documenting this function
6041 function make_unique_id_code($extra='') {
6043 $hostname = 'unknownhost';
6044 if (!empty($_SERVER['HTTP_HOST'])) {
6045 $hostname = $_SERVER['HTTP_HOST'];
6046 } else if (!empty($_ENV['HTTP_HOST'])) {
6047 $hostname = $_ENV['HTTP_HOST'];
6048 } else if (!empty($_SERVER['SERVER_NAME'])) {
6049 $hostname = $_SERVER['SERVER_NAME'];
6050 } else if (!empty($_ENV['SERVER_NAME'])) {
6051 $hostname = $_ENV['SERVER_NAME'];
6054 $date = gmdate("ymdHis");
6056 $random = random_string(6);
6058 if ($extra) {
6059 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6060 } else {
6061 return $hostname .'+'. $date .'+'. $random;
6067 * Function to check the passed address is within the passed subnet
6069 * The parameter is a comma separated string of subnet definitions.
6070 * Subnet strings can be in one of three formats:
6071 * 1: xxx.xxx.xxx.xxx/xx
6072 * 2: xxx.xxx
6073 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
6074 * Code for type 1 modified from user posted comments by mediator at
6075 * {@link http://au.php.net/manual/en/function.ip2long.php}
6077 * @param string $addr The address you are checking
6078 * @param string $subnetstr The string of subnet addresses
6079 * @return bool
6081 function address_in_subnet($addr, $subnetstr) {
6083 $subnets = explode(',', $subnetstr);
6084 $found = false;
6085 $addr = trim($addr);
6087 foreach ($subnets as $subnet) {
6088 $subnet = trim($subnet);
6089 if (strpos($subnet, '/') !== false) { /// type 1
6090 list($ip, $mask) = explode('/', $subnet);
6091 $mask = 0xffffffff << (32 - $mask);
6092 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
6093 } else if (strpos($subnet, '-') !== false) {/// type 3
6094 $subnetparts = explode('.', $subnet);
6095 $addrparts = explode('.', $addr);
6096 $subnetrange = explode('-', array_pop($subnetparts));
6097 if (count($subnetrange) == 2) {
6098 $lastaddrpart = array_pop($addrparts);
6099 $found = ($subnetparts == $addrparts &&
6100 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
6102 } else { /// type 2
6103 $found = (strpos($addr, $subnet) === 0);
6106 if ($found) {
6107 break;
6110 return $found;
6114 * This function sets the $HTTPSPAGEREQUIRED global
6115 * (used in some parts of moodle to change some links)
6116 * and calculate the proper wwwroot to be used
6118 * By using this function properly, we can ensure 100% https-ized pages
6119 * at our entire discretion (login, forgot_password, change_password)
6121 function httpsrequired() {
6123 global $CFG, $HTTPSPAGEREQUIRED;
6125 if (!empty($CFG->loginhttps)) {
6126 $HTTPSPAGEREQUIRED = true;
6127 $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
6128 $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
6130 // change theme URLs to https
6131 theme_setup();
6133 } else {
6134 $CFG->httpswwwroot = $CFG->wwwroot;
6135 $CFG->httpsthemewww = $CFG->themewww;
6140 * For outputting debugging info
6142 * @uses STDOUT
6143 * @param string $string ?
6144 * @param string $eol ?
6145 * @todo Finish documenting this function
6147 function mtrace($string, $eol="\n", $sleep=0) {
6149 if (defined('STDOUT')) {
6150 fwrite(STDOUT, $string.$eol);
6151 } else {
6152 echo $string . $eol;
6155 flush();
6157 //delay to keep message on user's screen in case of subsequent redirect
6158 if ($sleep) {
6159 sleep($sleep);
6163 //Replace 1 or more slashes or backslashes to 1 slash
6164 function cleardoubleslashes ($path) {
6165 return preg_replace('/(\/|\\\){1,}/','/',$path);
6168 function zip_files ($originalfiles, $destination) {
6169 //Zip an array of files/dirs to a destination zip file
6170 //Both parameters must be FULL paths to the files/dirs
6172 global $CFG;
6174 //Extract everything from destination
6175 $path_parts = pathinfo(cleardoubleslashes($destination));
6176 $destpath = $path_parts["dirname"]; //The path of the zip file
6177 $destfilename = $path_parts["basename"]; //The name of the zip file
6178 $extension = $path_parts["extension"]; //The extension of the file
6180 //If no file, error
6181 if (empty($destfilename)) {
6182 return false;
6185 //If no extension, add it
6186 if (empty($extension)) {
6187 $extension = 'zip';
6188 $destfilename = $destfilename.'.'.$extension;
6191 //Check destination path exists
6192 if (!is_dir($destpath)) {
6193 return false;
6196 //Check destination path is writable. TODO!!
6198 //Clean destination filename
6199 $destfilename = clean_filename($destfilename);
6201 //Now check and prepare every file
6202 $files = array();
6203 $origpath = NULL;
6205 foreach ($originalfiles as $file) { //Iterate over each file
6206 //Check for every file
6207 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6208 //Calculate the base path for all files if it isn't set
6209 if ($origpath === NULL) {
6210 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6212 //See if the file is readable
6213 if (!is_readable($tempfile)) { //Is readable
6214 continue;
6216 //See if the file/dir is in the same directory than the rest
6217 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6218 continue;
6220 //Add the file to the array
6221 $files[] = $tempfile;
6224 //Everything is ready:
6225 // -$origpath is the path where ALL the files to be compressed reside (dir).
6226 // -$destpath is the destination path where the zip file will go (dir).
6227 // -$files is an array of files/dirs to compress (fullpath)
6228 // -$destfilename is the name of the zip file (without path)
6230 //print_object($files); //Debug
6232 if (empty($CFG->zip)) { // Use built-in php-based zip function
6234 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6235 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6236 $zipfiles = array();
6237 $start = strlen($origpath)+1;
6238 foreach($files as $file) {
6239 $tf = array();
6240 $tf[PCLZIP_ATT_FILE_NAME] = $file;
6241 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME] = substr($file, $start);
6242 $zipfiles[] = $tf;
6244 //create the archive
6245 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6246 if (($list = $archive->create($zipfiles) == 0)) {
6247 notice($archive->errorInfo(true));
6248 return false;
6251 } else { // Use external zip program
6253 $filestozip = "";
6254 foreach ($files as $filetozip) {
6255 $filestozip .= escapeshellarg(basename($filetozip));
6256 $filestozip .= " ";
6258 //Construct the command
6259 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6260 $command = 'cd '.escapeshellarg($origpath).$separator.
6261 escapeshellarg($CFG->zip).' -r '.
6262 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6263 //All converted to backslashes in WIN
6264 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6265 $command = str_replace('/','\\',$command);
6267 Exec($command);
6269 return true;
6272 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6273 //Unzip one zip file to a destination dir
6274 //Both parameters must be FULL paths
6275 //If destination isn't specified, it will be the
6276 //SAME directory where the zip file resides.
6278 global $CFG;
6280 //Extract everything from zipfile
6281 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6282 $zippath = $path_parts["dirname"]; //The path of the zip file
6283 $zipfilename = $path_parts["basename"]; //The name of the zip file
6284 $extension = $path_parts["extension"]; //The extension of the file
6286 //If no file, error
6287 if (empty($zipfilename)) {
6288 return false;
6291 //If no extension, error
6292 if (empty($extension)) {
6293 return false;
6296 //Clear $zipfile
6297 $zipfile = cleardoubleslashes($zipfile);
6299 //Check zipfile exists
6300 if (!file_exists($zipfile)) {
6301 return false;
6304 //If no destination, passed let's go with the same directory
6305 if (empty($destination)) {
6306 $destination = $zippath;
6309 //Clear $destination
6310 $destpath = rtrim(cleardoubleslashes($destination), "/");
6312 //Check destination path exists
6313 if (!is_dir($destpath)) {
6314 return false;
6317 //Check destination path is writable. TODO!!
6319 //Everything is ready:
6320 // -$zippath is the path where the zip file resides (dir)
6321 // -$zipfilename is the name of the zip file (without path)
6322 // -$destpath is the destination path where the zip file will uncompressed (dir)
6324 $list = null;
6326 if (empty($CFG->unzip)) { // Use built-in php-based unzip function
6328 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6329 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6330 if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
6331 PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename',
6332 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $destpath)) {
6333 notice($archive->errorInfo(true));
6334 return false;
6337 } else { // Use external unzip program
6339 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6340 $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
6342 $command = 'cd '.escapeshellarg($zippath).$separator.
6343 escapeshellarg($CFG->unzip).' -o '.
6344 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6345 escapeshellarg($destpath).$redirection;
6346 //All converted to backslashes in WIN
6347 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6348 $command = str_replace('/','\\',$command);
6350 Exec($command,$list);
6353 //Display some info about the unzip execution
6354 if ($showstatus) {
6355 unzip_show_status($list,$destpath);
6358 return true;
6361 function unzip_cleanfilename ($p_event, &$p_header) {
6362 //This function is used as callback in unzip_file() function
6363 //to clean illegal characters for given platform and to prevent directory traversal.
6364 //Produces the same result as info-zip unzip.
6365 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6366 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6367 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6368 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6369 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6370 } else {
6371 //Add filtering for other systems here
6372 // BSD: none (tested)
6373 // Linux: ??
6374 // MacosX: ??
6376 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6377 return 1;
6380 function unzip_show_status ($list,$removepath) {
6381 //This function shows the results of the unzip execution
6382 //depending of the value of the $CFG->zip, results will be
6383 //text or an array of files.
6385 global $CFG;
6387 if (empty($CFG->unzip)) { // Use built-in php-based zip function
6388 $strname = get_string("name");
6389 $strsize = get_string("size");
6390 $strmodified = get_string("modified");
6391 $strstatus = get_string("status");
6392 echo "<table width=\"640\">";
6393 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6394 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6395 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6396 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6397 foreach ($list as $item) {
6398 echo "<tr>";
6399 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6400 print_cell("left", s($item['filename']));
6401 if (! $item['folder']) {
6402 print_cell("right", display_size($item['size']));
6403 } else {
6404 echo "<td>&nbsp;</td>";
6406 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6407 print_cell("right", $filedate);
6408 print_cell("right", $item['status']);
6409 echo "</tr>";
6411 echo "</table>";
6413 } else { // Use external zip program
6414 print_simple_box_start("center");
6415 echo "<pre>";
6416 foreach ($list as $item) {
6417 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6419 echo "</pre>";
6420 print_simple_box_end();
6425 * Returns most reliable client address
6427 * @return string The remote IP address
6429 function getremoteaddr() {
6430 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6431 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6433 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6434 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6436 if (!empty($_SERVER['REMOTE_ADDR'])) {
6437 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6439 return '';
6443 * Cleans a remote address ready to put into the log table
6445 function cleanremoteaddr($addr) {
6446 $originaladdr = $addr;
6447 $matches = array();
6448 // first get all things that look like IP addresses.
6449 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER)) {
6450 return '';
6452 $goodmatches = array();
6453 $lanmatches = array();
6454 foreach ($matches as $match) {
6455 // print_r($match);
6456 // check to make sure it's not an internal address.
6457 // the following are reserved for private lans...
6458 // 10.0.0.0 - 10.255.255.255
6459 // 172.16.0.0 - 172.31.255.255
6460 // 192.168.0.0 - 192.168.255.255
6461 // 169.254.0.0 -169.254.255.255
6462 $bits = explode('.',$match[0]);
6463 if (count($bits) != 4) {
6464 // weird, preg match shouldn't give us it.
6465 continue;
6467 if (($bits[0] == 10)
6468 || ($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6469 || ($bits[0] == 192 && $bits[1] == 168)
6470 || ($bits[0] == 169 && $bits[1] == 254)) {
6471 $lanmatches[] = $match[0];
6472 continue;
6474 // finally, it's ok
6475 $goodmatches[] = $match[0];
6477 if (!count($goodmatches)) {
6478 // perhaps we have a lan match, it's probably better to return that.
6479 if (!count($lanmatches)) {
6480 return '';
6481 } else {
6482 return array_pop($lanmatches);
6485 if (count($goodmatches) == 1) {
6486 return $goodmatches[0];
6488 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6489 // we need to return something, so
6490 return array_pop($goodmatches);
6494 * file_put_contents is only supported by php 5.0 and higher
6495 * so if it is not predefined, define it here
6497 * @param $file full path of the file to write
6498 * @param $contents contents to be sent
6499 * @return number of bytes written (false on error)
6501 if(!function_exists('file_put_contents')) {
6502 function file_put_contents($file, $contents) {
6503 $result = false;
6504 if ($f = fopen($file, 'w')) {
6505 $result = fwrite($f, $contents);
6506 fclose($f);
6508 return $result;
6513 * The clone keyword is only supported from PHP 5 onwards.
6514 * The behaviour of $obj2 = $obj1 differs fundamentally
6515 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6516 * created, in PHP 5 $obj1 is referenced. To create a copy
6517 * in PHP 5 the clone keyword was introduced. This function
6518 * simulates this behaviour for PHP < 5.0.0.
6519 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6521 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6522 * Found a better implementation (more checks and possibilities) from PEAR:
6523 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6525 * @param object $obj
6526 * @return object
6528 if(!check_php_version('5.0.0')) {
6529 // the eval is needed to prevent PHP 5 from getting a parse error!
6530 eval('
6531 function clone($obj) {
6532 /// Sanity check
6533 if (!is_object($obj)) {
6534 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6535 return;
6538 /// Use serialize/unserialize trick to deep copy the object
6539 $obj = unserialize(serialize($obj));
6541 /// If there is a __clone method call it on the "new" class
6542 if (method_exists($obj, \'__clone\')) {
6543 $obj->__clone();
6546 return $obj;
6549 // Supply the PHP5 function scandir() to older versions.
6550 function scandir($directory) {
6551 $files = array();
6552 if ($dh = opendir($directory)) {
6553 while (($file = readdir($dh)) !== false) {
6554 $files[] = $file;
6556 closedir($dh);
6558 return $files;
6561 // Supply the PHP5 function array_combine() to older versions.
6562 function array_combine($keys, $values) {
6563 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6564 return false;
6566 reset($values);
6567 $result = array();
6568 foreach ($keys as $key) {
6569 $result[$key] = current($values);
6570 next($values);
6572 return $result;
6578 * This function will make a complete copy of anything it's given,
6579 * regardless of whether it's an object or not.
6580 * @param mixed $thing
6581 * @return mixed
6583 function fullclone($thing) {
6584 return unserialize(serialize($thing));
6589 * This function expects to called during shutdown
6590 * should be set via register_shutdown_function()
6591 * in lib/setup.php .
6593 * Right now we do it only if we are under apache, to
6594 * make sure apache children that hog too much mem are
6595 * killed.
6598 function moodle_request_shutdown() {
6600 global $CFG;
6602 // initially, we are only ever called under apache
6603 // but check just in case
6604 if (function_exists('apache_child_terminate')
6605 && function_exists('memory_get_usage')
6606 && ini_get_bool('child_terminate')) {
6607 if (empty($CFG->apachemaxmem)) {
6608 $CFG->apachemaxmem = 25000000; // default 25MiB
6610 if (memory_get_usage() > (int)$CFG->apachemaxmem) {
6611 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
6612 @apache_child_terminate();
6618 * If new messages are waiting for the current user, then return
6619 * Javascript code to create a popup window
6621 * @return string Javascript code
6623 function message_popup_window() {
6624 global $USER;
6626 $popuplimit = 30; // Minimum seconds between popups
6628 if (!defined('MESSAGE_WINDOW')) {
6629 if (isset($USER->id)) {
6630 if (!isset($USER->message_lastpopup)) {
6631 $USER->message_lastpopup = 0;
6633 if ((time() - $USER->message_lastpopup) > $popuplimit) { /// It's been long enough
6634 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6635 if (count_records_select('message', 'useridto = \''.$USER->id.'\' AND timecreated > \''.$USER->message_lastpopup.'\'')) {
6636 $USER->message_lastpopup = time();
6637 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6638 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6645 return '';
6648 // Used to make sure that $min <= $value <= $max
6649 function bounded_number($min, $value, $max) {
6650 if($value < $min) {
6651 return $min;
6653 if($value > $max) {
6654 return $max;
6656 return $value;
6659 function array_is_nested($array) {
6660 foreach ($array as $value) {
6661 if (is_array($value)) {
6662 return true;
6665 return false;
6669 *** get_performance_info() pairs up with init_performance_info()
6670 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6671 *** values ready for use, and each of the individual stats provided
6672 *** separately as well.
6675 function get_performance_info() {
6676 global $CFG, $PERF, $rcache;
6678 $info = array();
6679 $info['html'] = ''; // holds userfriendly HTML representation
6680 $info['txt'] = me() . ' '; // holds log-friendly representation
6682 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
6684 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6685 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6687 if (function_exists('memory_get_usage')) {
6688 $info['memory_total'] = memory_get_usage();
6689 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
6690 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6691 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6694 $inc = get_included_files();
6695 //error_log(print_r($inc,1));
6696 $info['includecount'] = count($inc);
6697 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6698 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6700 if (!empty($PERF->dbqueries)) {
6701 $info['dbqueries'] = $PERF->dbqueries;
6702 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6703 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6706 if (!empty($PERF->logwrites)) {
6707 $info['logwrites'] = $PERF->logwrites;
6708 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6709 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6712 if (!empty($PERF->profiling) && $PERF->profiling) {
6713 require_once($CFG->dirroot .'/lib/profilerlib.php');
6714 $info['html'] .= '<span class="profilinginfo">'.Profiler::get_profiling(array('-R')).'</span>';
6717 if (function_exists('posix_times')) {
6718 $ptimes = posix_times();
6719 if (is_array($ptimes)) {
6720 foreach ($ptimes as $key => $val) {
6721 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
6723 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6724 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6728 // Grab the load average for the last minute
6729 // /proc will only work under some linux configurations
6730 // while uptime is there under MacOSX/Darwin and other unices
6731 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
6732 list($server_load) = explode(' ', $loadavg[0]);
6733 unset($loadavg);
6734 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
6735 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
6736 $server_load = $matches[1];
6737 } else {
6738 trigger_error('Could not parse uptime output!');
6741 if (!empty($server_load)) {
6742 $info['serverload'] = $server_load;
6743 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
6744 $info['txt'] .= "serverload: {$info['serverload']} ";
6747 if (isset($rcache->hits) && isset($rcache->misses)) {
6748 $info['rcachehits'] = $rcache->hits;
6749 $info['rcachemisses'] = $rcache->misses;
6750 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
6751 "{$rcache->hits}/{$rcache->misses}</span> ";
6752 $info['txt'] .= 'rcache: '.
6753 "{$rcache->hits}/{$rcache->misses} ";
6755 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
6756 return $info;
6759 function apd_get_profiling() {
6760 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
6763 function remove_dir($dir, $content_only=false) {
6764 // if content_only=true then delete all but
6765 // the directory itself
6767 $handle = opendir($dir);
6768 while (false!==($item = readdir($handle))) {
6769 if($item != '.' && $item != '..') {
6770 if(is_dir($dir.'/'.$item)) {
6771 remove_dir($dir.'/'.$item);
6772 }else{
6773 unlink($dir.'/'.$item);
6777 closedir($handle);
6778 if ($content_only) {
6779 return true;
6781 return rmdir($dir);
6785 * Function to check if a directory exists and optionally create it.
6787 * @param string absolute directory path
6788 * @param boolean create directory if does not exist
6789 * @param boolean create directory recursively
6791 * @return boolean true if directory exists or created
6793 function check_dir_exists($dir, $create=false, $recursive=false) {
6795 global $CFG;
6797 $status = true;
6799 if(!is_dir($dir)) {
6800 if (!$create) {
6801 $status = false;
6802 } else {
6803 umask(0000);
6804 if ($recursive) {
6805 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
6806 $dir = str_replace('\\', '/', $dir); //windows compatibility
6807 $dirs = explode('/', $dir);
6808 $dir = array_shift($dirs).'/'; //skip root or drive letter
6809 foreach ($dirs as $part) {
6810 if ($part == '') {
6811 continue;
6813 $dir .= $part.'/';
6814 if (!is_dir($dir)) {
6815 if (!mkdir($dir, $CFG->directorypermissions)) {
6816 $status = false;
6817 break;
6821 } else {
6822 $status = mkdir($dir, $CFG->directorypermissions);
6826 return $status;
6829 function report_session_error() {
6830 global $CFG, $FULLME;
6832 if (empty($CFG->lang)) {
6833 $CFG->lang = "en";
6835 // Set up default theme and locale
6836 theme_setup();
6837 moodle_setlocale();
6839 //clear session cookies
6840 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
6841 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
6842 //increment database error counters
6843 if (isset($CFG->session_error_counter)) {
6844 set_config('session_error_counter', 1 + $CFG->session_error_counter);
6845 } else {
6846 set_config('session_error_counter', 1);
6848 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
6853 * Detect if an object or a class contains a given property
6854 * will take an actual object or the name of a class
6855 * @param mix $obj Name of class or real object to test
6856 * @param string $property name of property to find
6857 * @return bool true if property exists
6859 function object_property_exists( $obj, $property ) {
6860 if (is_string( $obj )) {
6861 $properties = get_class_vars( $obj );
6863 else {
6864 $properties = get_object_vars( $obj );
6866 return array_key_exists( $property, $properties );
6871 * Detect a custom script replacement in the data directory that will
6872 * replace an existing moodle script
6873 * @param string $urlpath path to the original script
6874 * @return string full path name if a custom script exists
6875 * @return bool false if no custom script exists
6877 function custom_script_path($urlpath='') {
6878 global $CFG;
6880 // set default $urlpath, if necessary
6881 if (empty($urlpath)) {
6882 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
6885 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
6886 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot) === false )) {
6887 return false;
6890 // replace wwwroot with the path to the customscripts folder and clean path
6891 $scriptpath = $CFG->customscripts . clean_param(substr($urlpath, strlen($CFG->wwwroot)), PARAM_PATH);
6893 // remove the query string, if any
6894 if (($strpos = strpos($scriptpath, '?')) !== false) {
6895 $scriptpath = substr($scriptpath, 0, $strpos);
6898 // remove trailing slashes, if any
6899 $scriptpath = rtrim($scriptpath, '/\\');
6901 // append index.php, if necessary
6902 if (is_dir($scriptpath)) {
6903 $scriptpath .= '/index.php';
6906 // check the custom script exists
6907 if (file_exists($scriptpath)) {
6908 return $scriptpath;
6909 } else {
6910 return false;
6915 * Wrapper function to load necessary editor scripts
6916 * to $CFG->editorsrc array. Params can be coursei id
6917 * or associative array('courseid' => value, 'name' => 'editorname').
6918 * @uses $CFG
6919 * @param mixed $args Courseid or associative array.
6921 function loadeditor($args) {
6922 global $CFG;
6923 include($CFG->libdir .'/editorlib.php');
6924 return editorObject::loadeditor($args);
6928 * Returns whether or not the user object is a remote MNET user. This function
6929 * is in moodlelib because it does not rely on loading any of the MNET code.
6931 * @param object $user A valid user object
6932 * @return bool True if the user is from a remote Moodle.
6934 function is_mnet_remote_user($user) {
6935 global $CFG;
6937 if (!isset($CFG->mnet_localhost_id)) {
6938 include_once $CFG->dirroot . '/mnet/lib.php';
6939 $env = new mnet_environment();
6940 $env->init();
6941 unset($env);
6944 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
6948 * Checks if a given plugin is in the list of enabled enrolment plugins.
6950 * @param string $auth Enrolment plugin.
6951 * @return boolean Whether the plugin is enabled.
6953 function is_enabled_enrol($enrol='') {
6954 global $CFG;
6956 // use the global default if not specified
6957 if ($enrol == '') {
6958 $enrol = $CFG->enrol;
6960 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
6964 * This function will search for browser prefereed languages, setting Moodle
6965 * to use the best one available if $SESSION->lang is undefined
6967 function setup_lang_from_browser() {
6969 global $CFG, $SESSION, $USER;
6971 if (!empty($SESSION->lang) or !empty($USER->lang)) {
6972 // Lang is defined in session or user profile, nothing to do
6973 return;
6976 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
6977 return;
6980 /// Extract and clean langs from headers
6981 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
6982 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
6983 $rawlangs = explode(',', $rawlangs); // Convert to array
6984 $langs = array();
6986 $order = 1.0;
6987 foreach ($rawlangs as $lang) {
6988 if (strpos($lang, ';') === false) {
6989 $langs[(string)$order] = $lang;
6990 $order = $order-0.01;
6991 } else {
6992 $parts = explode(';', $lang);
6993 $pos = strpos($parts[1], '=');
6994 $langs[substr($parts[1], $pos+1)] = $parts[0];
6997 krsort($langs, SORT_NUMERIC);
6999 $langlist = get_list_of_languages();
7001 /// Look for such langs under standard locations
7002 foreach ($langs as $lang) {
7003 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR)); // clean it properly for include
7004 if (!array_key_exists($lang, $langlist)) {
7005 continue; // language not allowed, try next one
7007 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
7008 $SESSION->lang = $lang; /// Lang exists, set it in session
7009 break; /// We have finished. Go out
7012 return;
7016 ////////////////////////////////////////////////////////////////////////////////
7018 * This function will build the navigation string to be used by print_header
7019 * and others
7020 * @uses $CFG
7021 * @uses $THEME
7022 * @param $extrabreadcrumbs - array of associative arrays, keys: name, link, type
7023 * @return $navigation as an object so it can be differentiated from old style
7024 * navigation strings.
7026 function build_navigation($extrabreadcrumbs) {
7027 global $CFG, $COURSE;
7029 $navigation = '';
7031 //Site name
7032 if ($site = get_site()) {
7033 $breadcrumbs[] = array('name' => format_string($site->shortname), 'link' => "$CFG->wwwroot/", 'type' => 'home');
7037 if ($COURSE) {
7038 if ($COURSE->id != SITEID) {
7039 //Course
7040 $breadcrumbs[] = array('name' => format_string($COURSE->shortname), 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",'type' => 'course');
7044 //Merge in extra bread crumbs
7045 $breadcrumbs = array_merge($breadcrumbs, $extrabreadcrumbs);
7047 //Construct an unordered list from $breadcrumbs
7048 //Accessibility: heading hidden from visual browsers by default.
7049 $navigation = '<h2 class="accesshide">'.get_string('youarehere','access')."</h2> <ul>\n";
7050 $countcrumb = count($breadcrumbs);
7052 for($i=0;$i<$countcrumb;$i++) {
7054 // Check the link type to see if this link should appear in the trail
7055 if ($breadcrumbs[$i]['type'] == 'activity' && $i+1 < $countcrumb && ($CFG->hideactivitytypecrumb == 2 || ($CFG->hideactivitytypecrumb == 1 && !has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))))) {
7056 continue;
7058 $navigation .= '<li class="first">';
7059 if ($i > 0) {
7060 $navigation .= get_separator();
7062 if ($breadcrumbs[$i]['link'] && $i+1 < $countcrumb) {
7063 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$breadcrumbs[$i]['link']}\">";
7065 $navigation .= "{$breadcrumbs[$i]['name']}";
7066 if ($breadcrumbs[$i]['link'] && $i+1 < $countcrumb) {
7067 $navigation .= "</a>";
7070 $navigation .= "</li>";
7073 $navigation .= "</ul>";
7075 return(array('newnav' => true, 'breadcrumbs' => $navigation));
7078 function is_newnav($navigation) {
7079 if (is_array($navigation) && $navigation['newnav']) {
7080 return(true);
7081 } else {
7082 return(false);
7087 * Checks whether the given variable name is defined as a variable within the given object.
7088 * @note This will NOT work with stdClass objects, which have no class variables.
7089 * @param string $var The variable name
7090 * @param object $object The object to check
7091 * @return boolean
7093 function in_object_vars($var, $object)
7095 $class_vars = get_class_vars(get_class($object));
7096 $class_vars = array_keys($class_vars);
7097 return in_array($var, $class_vars);
7100 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: