MDL-10689:
[moodle-linuxchix.git] / lib / moodlelib.php
bloba5c1b06580a51bccd26a6f7d18c3e3d11d1e6e7f
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))) {
1711 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1712 print_maintenance_message();
1713 exit;
1717 /// groupmembersonly access control
1718 if (!empty($CFG->enablegroupings) and $cm and $cm->groupmembersonly and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
1719 if (isguestuser() or !groups_has_membership($cm)) {
1720 error(get_string('groupmembersonlyerror', 'group'), $CFG->wwwroot.'/course/view.php?id='.$cm->course);
1724 if ($COURSE->id == SITEID) {
1725 /// We can eliminate hidden site activities straight away
1726 if (!empty($cm) && !$cm->visible and !has_capability('moodle/course:viewhiddenactivities',
1727 get_context_instance(CONTEXT_SYSTEM))) {
1728 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
1730 return;
1732 } else {
1733 /// Check if the user can be in a particular course
1734 if (!$context = get_context_instance(CONTEXT_COURSE, $COURSE->id)) {
1735 print_error('nocontext');
1738 if (empty($USER->switchrole[$context->id]) &&
1739 !($COURSE->visible && course_parent_visible($COURSE)) &&
1740 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $COURSE->id)) ){
1741 print_header_simple();
1742 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1745 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1747 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $context)) {
1748 if ($COURSE->guest == 1) {
1749 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1750 has_capability('clearcache'); // Must clear cache
1751 $guestcaps = get_role_context_caps($CFG->guestroleid, $context);
1752 $USER->capabilities = merge_role_caps($USER->capabilities, $guestcaps);
1756 /// If the user is a guest then treat them according to the course policy about guests
1758 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1759 switch ($COURSE->guest) { /// Check course policy about guest access
1761 case 1: /// Guests always allowed
1762 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1763 print_header_simple();
1764 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1766 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1767 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1768 get_string('activityiscurrentlyhidden'));
1771 return; // User is allowed to see this course
1773 break;
1775 case 2: /// Guests allowed with key
1776 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
1777 return true;
1779 // otherwise drop through to logic below (--> enrol.php)
1780 break;
1782 default: /// Guests not allowed
1783 $strloggedinasguest = get_string('loggedinasguest');
1784 print_header_simple('', '',
1785 build_navigation(array(array('name' => $strloggedinasguest, 'link' => null, 'type' => 'misc'))));
1786 if (empty($USER->switchrole[$context->id])) { // Normal guest
1787 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1788 } else {
1789 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
1790 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
1791 print_footer($COURSE);
1792 exit;
1794 break;
1797 /// For non-guests, check if they have course view access
1799 } else if (has_capability('moodle/course:view', $context)) {
1800 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
1801 if (!has_capability('moodle/course:view', $context, $USER->realuser)) {
1802 print_header_simple();
1803 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
1807 /// Make sure they can read this activity too, if specified
1809 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
1810 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1812 return; // User is allowed to see this course
1817 /// Currently not enrolled in the course, so see if they want to enrol
1818 $SESSION->wantsurl = $FULLME;
1819 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
1820 die;
1827 * This function just makes sure a user is logged out.
1829 * @uses $CFG
1830 * @uses $USER
1832 function require_logout() {
1834 global $USER, $CFG, $SESSION;
1836 if (isloggedin()) {
1837 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1839 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1840 foreach($authsequence as $authname) {
1841 $authplugin = get_auth_plugin($authname);
1842 $authplugin->prelogout_hook();
1846 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1847 // This method is just to try to avoid silly warnings from PHP 4.3.0
1848 session_unregister("USER");
1849 session_unregister("SESSION");
1852 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
1853 $file = $line = null;
1854 if (headers_sent($file, $line)) {
1855 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
1856 error_log('Headers were already sent in file: '.$file.' on line '.$line);
1857 } else {
1858 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
1861 unset($_SESSION['USER']);
1862 unset($_SESSION['SESSION']);
1864 unset($SESSION);
1865 unset($USER);
1870 * This is a weaker version of {@link require_login()} which only requires login
1871 * when called from within a course rather than the site page, unless
1872 * the forcelogin option is turned on.
1874 * @uses $CFG
1875 * @param mixed $courseorid The course object or id in question
1876 * @param bool $autologinguest Allow autologin guests if that is wanted
1877 * @param object $cm Course activity module if known
1879 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1880 global $CFG;
1881 if (!empty($CFG->forcelogin)) {
1882 // login required for both SITE and courses
1883 require_login($courseorid, $autologinguest, $cm);
1885 } else if (!empty($cm) and !$cm->visible) {
1886 // always login for hidden activities
1887 require_login($courseorid, $autologinguest, $cm);
1889 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
1890 or (!is_object($courseorid) and $courseorid == SITEID)) {
1891 //login for SITE not required
1892 return;
1894 } else {
1895 // course login always required
1896 require_login($courseorid, $autologinguest, $cm);
1901 * Modify the user table by setting the currently logged in user's
1902 * last login to now.
1904 * @uses $USER
1905 * @return bool
1907 function update_user_login_times() {
1908 global $USER;
1910 $user = new object();
1911 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
1912 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1914 $user->id = $USER->id;
1916 return update_record('user', $user);
1920 * Determines if a user has completed setting up their account.
1922 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
1923 * @return bool
1925 function user_not_fully_set_up($user) {
1926 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1929 function over_bounce_threshold($user) {
1931 global $CFG;
1933 if (empty($CFG->handlebounces)) {
1934 return false;
1936 // set sensible defaults
1937 if (empty($CFG->minbounces)) {
1938 $CFG->minbounces = 10;
1940 if (empty($CFG->bounceratio)) {
1941 $CFG->bounceratio = .20;
1943 $bouncecount = 0;
1944 $sendcount = 0;
1945 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1946 $bouncecount = $bounce->value;
1948 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1949 $sendcount = $send->value;
1951 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
1955 * @param $user - object containing an id
1956 * @param $reset - will reset the count to 0
1958 function set_send_count($user,$reset=false) {
1959 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1960 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1961 update_record('user_preferences',$pref);
1963 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1964 // make a new one
1965 $pref->name = 'email_send_count';
1966 $pref->value = 1;
1967 $pref->userid = $user->id;
1968 insert_record('user_preferences',$pref, false);
1973 * @param $user - object containing an id
1974 * @param $reset - will reset the count to 0
1976 function set_bounce_count($user,$reset=false) {
1977 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1978 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1979 update_record('user_preferences',$pref);
1981 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1982 // make a new one
1983 $pref->name = 'email_bounce_count';
1984 $pref->value = 1;
1985 $pref->userid = $user->id;
1986 insert_record('user_preferences',$pref, false);
1991 * Keeps track of login attempts
1993 * @uses $SESSION
1995 function update_login_count() {
1997 global $SESSION;
1999 $max_logins = 10;
2001 if (empty($SESSION->logincount)) {
2002 $SESSION->logincount = 1;
2003 } else {
2004 $SESSION->logincount++;
2007 if ($SESSION->logincount > $max_logins) {
2008 unset($SESSION->wantsurl);
2009 error(get_string('errortoomanylogins'));
2014 * Resets login attempts
2016 * @uses $SESSION
2018 function reset_login_count() {
2019 global $SESSION;
2021 $SESSION->logincount = 0;
2024 function sync_metacourses() {
2026 global $CFG;
2028 if (!$courses = get_records('course', 'metacourse', 1)) {
2029 return;
2032 foreach ($courses as $course) {
2033 sync_metacourse($course);
2038 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2040 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2042 function sync_metacourse($course) {
2043 global $CFG;
2045 // Check the course is valid.
2046 if (!is_object($course)) {
2047 if (!$course = get_record('course', 'id', $course)) {
2048 return false; // invalid course id
2052 // Check that we actually have a metacourse.
2053 if (empty($course->metacourse)) {
2054 return false;
2057 // Get a list of roles that should not be synced.
2058 if (!empty($CFG->nonmetacoursesyncroleids)) {
2059 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2060 } else {
2061 $roleexclusions = '';
2064 // Get the context of the metacourse.
2065 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2067 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2068 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2069 $managers = array_keys($users);
2070 } else {
2071 $managers = array();
2074 // Get assignments of a user to a role that exist in a child course, but
2075 // not in the meta coure. That is, get a list of the assignments that need to be made.
2076 if (!$assignments = get_records_sql("
2077 SELECT
2078 ra.id, ra.roleid, ra.userid
2079 FROM
2080 {$CFG->prefix}role_assignments ra,
2081 {$CFG->prefix}context con,
2082 {$CFG->prefix}course_meta cm
2083 WHERE
2084 ra.contextid = con.id AND
2085 con.contextlevel = " . CONTEXT_COURSE . " AND
2086 con.instanceid = cm.child_course AND
2087 cm.parent_course = {$course->id} AND
2088 $roleexclusions
2089 NOT EXISTS (
2090 SELECT 1 FROM
2091 {$CFG->prefix}role_assignments ra2
2092 WHERE
2093 ra2.userid = ra.userid AND
2094 ra2.roleid = ra.roleid AND
2095 ra2.contextid = {$context->id}
2097 ")) {
2098 $assignments = array();
2101 // Get assignments of a user to a role that exist in the meta course, but
2102 // not in any child courses. That is, get a list of the unassignments that need to be made.
2103 if (!$unassignments = get_records_sql("
2104 SELECT
2105 ra.id, ra.roleid, ra.userid
2106 FROM
2107 {$CFG->prefix}role_assignments ra
2108 WHERE
2109 ra.contextid = {$context->id} AND
2110 $roleexclusions
2111 NOT EXISTS (
2112 SELECT 1 FROM
2113 {$CFG->prefix}role_assignments ra2,
2114 {$CFG->prefix}context con2,
2115 {$CFG->prefix}course_meta cm
2116 WHERE
2117 ra2.userid = ra.userid AND
2118 ra2.roleid = ra.roleid AND
2119 ra2.contextid = con2.id AND
2120 con2.contextlevel = " . CONTEXT_COURSE . " AND
2121 con2.instanceid = cm.child_course AND
2122 cm.parent_course = {$course->id}
2124 ")) {
2125 $unassignments = array();
2128 $success = true;
2130 // Make the unassignments, if they are not managers.
2131 foreach ($unassignments as $unassignment) {
2132 if (!in_array($unassignment->userid, $managers)) {
2133 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
2137 // Make the assignments.
2138 foreach ($assignments as $assignment) {
2139 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
2142 return $success;
2144 // TODO: finish timeend and timestart
2145 // maybe we could rely on cron job to do the cleaning from time to time
2149 * Adds a record to the metacourse table and calls sync_metacoures
2151 function add_to_metacourse ($metacourseid, $courseid) {
2153 if (!$metacourse = get_record("course","id",$metacourseid)) {
2154 return false;
2157 if (!$course = get_record("course","id",$courseid)) {
2158 return false;
2161 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2162 $rec = new object();
2163 $rec->parent_course = $metacourseid;
2164 $rec->child_course = $courseid;
2165 if (!insert_record('course_meta',$rec)) {
2166 return false;
2168 return sync_metacourse($metacourseid);
2170 return true;
2175 * Removes the record from the metacourse table and calls sync_metacourse
2177 function remove_from_metacourse($metacourseid, $courseid) {
2179 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2180 return sync_metacourse($metacourseid);
2182 return false;
2187 * Determines if a user is currently logged in
2189 * @uses $USER
2190 * @return bool
2192 function isloggedin() {
2193 global $USER;
2195 return (!empty($USER->id));
2199 * Determines if a user is logged in as real guest user with username 'guest'.
2200 * This function is similar to original isguest() in 1.6 and earlier.
2201 * Current isguest() is deprecated - do not use it anymore.
2203 * @param $user mixed user object or id, $USER if not specified
2204 * @return bool true if user is the real guest user, false if not logged in or other user
2206 function isguestuser($user=NULL) {
2207 global $USER;
2208 if ($user === NULL) {
2209 $user = $USER;
2210 } else if (is_numeric($user)) {
2211 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2214 if (empty($user->id)) {
2215 return false; // not logged in, can not be guest
2218 return ($user->username == 'guest');
2222 * Determines if the currently logged in user is in editing mode
2224 * @uses $USER
2225 * @param int $courseid The id of the course being tested
2226 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
2227 * @return bool
2229 function isediting($courseid, $user=NULL) {
2230 global $USER;
2231 if (!$user) {
2232 $user = $USER;
2234 if (empty($user->editing)) {
2235 return false;
2238 $capcheck = false;
2239 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
2241 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
2242 has_capability('moodle/site:manageblocks', $coursecontext)) {
2243 $capcheck = true;
2244 } else {
2245 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
2246 if ($children = get_child_contexts($coursecontext)) {
2247 foreach ($children as $child) {
2248 $childcontext = get_record('context', 'id', $child);
2249 if (has_capability('moodle/course:manageactivities', $childcontext) ||
2250 has_capability('moodle/site:manageblocks', $childcontext)) {
2251 $capcheck = true;
2252 break;
2258 return ($user->editing && $capcheck);
2259 //return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2263 * Determines if the logged in user is currently moving an activity
2265 * @uses $USER
2266 * @param int $courseid The id of the course being tested
2267 * @return bool
2269 function ismoving($courseid) {
2270 global $USER;
2272 if (!empty($USER->activitycopy)) {
2273 return ($USER->activitycopycourse == $courseid);
2275 return false;
2279 * Given an object containing firstname and lastname
2280 * values, this function returns a string with the
2281 * full name of the person.
2282 * The result may depend on system settings
2283 * or language. 'override' will force both names
2284 * to be used even if system settings specify one.
2286 * @uses $CFG
2287 * @uses $SESSION
2288 * @param object $user A {@link $USER} object to get full name of
2289 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2291 function fullname($user, $override=false) {
2293 global $CFG, $SESSION;
2295 if (!isset($user->firstname) and !isset($user->lastname)) {
2296 return '';
2299 if (!$override) {
2300 if (!empty($CFG->forcefirstname)) {
2301 $user->firstname = $CFG->forcefirstname;
2303 if (!empty($CFG->forcelastname)) {
2304 $user->lastname = $CFG->forcelastname;
2308 if (!empty($SESSION->fullnamedisplay)) {
2309 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2312 if ($CFG->fullnamedisplay == 'firstname lastname') {
2313 return $user->firstname .' '. $user->lastname;
2315 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
2316 return $user->lastname .' '. $user->firstname;
2318 } else if ($CFG->fullnamedisplay == 'firstname') {
2319 if ($override) {
2320 return get_string('fullnamedisplay', '', $user);
2321 } else {
2322 return $user->firstname;
2326 return get_string('fullnamedisplay', '', $user);
2330 * Sets a moodle cookie with an encrypted string
2332 * @uses $CFG
2333 * @uses DAYSECS
2334 * @uses HOURSECS
2335 * @param string $thing The string to encrypt and place in a cookie
2337 function set_moodle_cookie($thing) {
2338 global $CFG;
2340 if ($thing == 'guest') { // Ignore guest account
2341 return;
2344 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2346 $days = 60;
2347 $seconds = DAYSECS*$days;
2349 setCookie($cookiename, '', time() - HOURSECS, '/');
2350 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
2354 * Gets a moodle cookie with an encrypted string
2356 * @uses $CFG
2357 * @return string
2359 function get_moodle_cookie() {
2360 global $CFG;
2362 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2364 if (empty($_COOKIE[$cookiename])) {
2365 return '';
2366 } else {
2367 $thing = rc4decrypt($_COOKIE[$cookiename]);
2368 return ($thing == 'guest') ? '': $thing; // Ignore guest account
2373 * Returns whether a given authentication plugin exists.
2375 * @uses $CFG
2376 * @param string $auth Form of authentication to check for. Defaults to the
2377 * global setting in {@link $CFG}.
2378 * @return boolean Whether the plugin is available.
2380 function exists_auth_plugin($auth) {
2381 global $CFG;
2383 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2384 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2386 return false;
2390 * Checks if a given plugin is in the list of enabled authentication plugins.
2392 * @param string $auth Authentication plugin.
2393 * @return boolean Whether the plugin is enabled.
2395 function is_enabled_auth($auth) {
2396 if (empty($auth)) {
2397 return false;
2400 $enabled = get_enabled_auth_plugins();
2402 return in_array($auth, $enabled);
2406 * Returns an authentication plugin instance.
2408 * @uses $CFG
2409 * @param string $auth name of authentication plugin
2410 * @return object An instance of the required authentication plugin.
2412 function get_auth_plugin($auth) {
2413 global $CFG;
2415 // check the plugin exists first
2416 if (! exists_auth_plugin($auth)) {
2417 error("Authentication plugin '$auth' not found.");
2420 // return auth plugin instance
2421 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2422 $class = "auth_plugin_$auth";
2423 return new $class;
2427 * Returns array of active auth plugins.
2429 * @param bool $fix fix $CFG->auth if needed
2430 * @return array
2432 function get_enabled_auth_plugins($fix=false) {
2433 global $CFG;
2435 $default = array('manual', 'nologin');
2437 if (empty($CFG->auth)) {
2438 $auths = array();
2439 } else {
2440 $auths = explode(',', $CFG->auth);
2443 if ($fix) {
2444 $auths = array_unique($auths);
2445 foreach($auths as $k=>$authname) {
2446 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2447 unset($auths[$k]);
2450 $newconfig = implode(',', $auths);
2451 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2452 set_config('auth', $newconfig);
2456 return (array_merge($default, $auths));
2460 * Returns true if an internal authentication method is being used.
2461 * if method not specified then, global default is assumed
2463 * @uses $CFG
2464 * @param string $auth Form of authentication required
2465 * @return bool
2467 function is_internal_auth($auth) {
2468 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2469 return $authplugin->is_internal();
2473 * Returns an array of user fields
2475 * @uses $CFG
2476 * @uses $db
2477 * @return array User field/column names
2479 function get_user_fieldnames() {
2481 global $CFG, $db;
2483 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2484 unset($fieldarray['ID']);
2486 return $fieldarray;
2490 * Creates the default "guest" user. Used both from
2491 * admin/index.php and login/index.php
2492 * @return mixed user object created or boolean false if the creation has failed
2494 function create_guest_record() {
2496 global $CFG;
2498 $guest->auth = 'manual';
2499 $guest->username = 'guest';
2500 $guest->password = hash_internal_user_password('guest');
2501 $guest->firstname = addslashes(get_string('guestuser'));
2502 $guest->lastname = ' ';
2503 $guest->email = 'root@localhost';
2504 $guest->description = addslashes(get_string('guestuserinfo'));
2505 $guest->mnethostid = $CFG->mnet_localhost_id;
2506 $guest->confirmed = 1;
2507 $guest->lang = $CFG->lang;
2508 $guest->timemodified= time();
2510 if (! $guest->id = insert_record("user", $guest)) {
2511 return false;
2514 return $guest;
2518 * Creates a bare-bones user record
2520 * @uses $CFG
2521 * @param string $username New user's username to add to record
2522 * @param string $password New user's password to add to record
2523 * @param string $auth Form of authentication required
2524 * @return object A {@link $USER} object
2525 * @todo Outline auth types and provide code example
2527 function create_user_record($username, $password, $auth='manual') {
2528 global $CFG;
2530 //just in case check text case
2531 $username = trim(moodle_strtolower($username));
2533 $authplugin = get_auth_plugin($auth);
2535 if ($newinfo = $authplugin->get_userinfo($username)) {
2536 $newinfo = truncate_userinfo($newinfo);
2537 foreach ($newinfo as $key => $value){
2538 $newuser->$key = addslashes($value);
2542 if (!empty($newuser->email)) {
2543 if (email_is_not_allowed($newuser->email)) {
2544 unset($newuser->email);
2548 $newuser->auth = $auth;
2549 $newuser->username = $username;
2551 // fix for MDL-8480
2552 // user CFG lang for user if $newuser->lang is empty
2553 // or $user->lang is not an installed language
2554 $sitelangs = array_keys(get_list_of_languages());
2555 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2556 $newuser -> lang = $CFG->lang;
2558 $newuser->confirmed = 1;
2559 $newuser->lastip = getremoteaddr();
2560 $newuser->timemodified = time();
2561 $newuser->mnethostid = $CFG->mnet_localhost_id;
2563 if (insert_record('user', $newuser)) {
2564 $user = get_complete_user_data('username', $newuser->username);
2565 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
2566 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2568 update_internal_user_password($user, $password);
2569 return $user;
2571 return false;
2575 * Will update a local user record from an external source
2577 * @uses $CFG
2578 * @param string $username New user's username to add to record
2579 * @return user A {@link $USER} object
2581 function update_user_record($username, $authplugin) {
2582 $username = trim(moodle_strtolower($username)); /// just in case check text case
2584 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2585 $userauth = get_auth_plugin($oldinfo->auth);
2587 if ($newinfo = $userauth->get_userinfo($username)) {
2588 $newinfo = truncate_userinfo($newinfo);
2589 foreach ($newinfo as $key => $value){
2590 $confkey = 'field_updatelocal_' . $key;
2591 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2592 $value = addslashes(stripslashes($value)); // Just in case
2593 set_field('user', $key, $value, 'username', $username)
2594 or error_log("Error updating $key for $username");
2599 return get_complete_user_data('username', $username);
2602 function truncate_userinfo($info) {
2603 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2604 /// which may have large fields
2606 // define the limits
2607 $limit = array(
2608 'username' => 100,
2609 'idnumber' => 64,
2610 'firstname' => 100,
2611 'lastname' => 100,
2612 'email' => 100,
2613 'icq' => 15,
2614 'phone1' => 20,
2615 'phone2' => 20,
2616 'institution' => 40,
2617 'department' => 30,
2618 'address' => 70,
2619 'city' => 20,
2620 'country' => 2,
2621 'url' => 255,
2624 // apply where needed
2625 foreach (array_keys($info) as $key) {
2626 if (!empty($limit[$key])) {
2627 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2631 return $info;
2635 * Retrieve the guest user object
2637 * @uses $CFG
2638 * @return user A {@link $USER} object
2640 function guest_user() {
2641 global $CFG;
2643 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
2644 $newuser->confirmed = 1;
2645 $newuser->lang = $CFG->lang;
2646 $newuser->lastip = getremoteaddr();
2649 return $newuser;
2653 * Given a username and password, this function looks them
2654 * up using the currently selected authentication mechanism,
2655 * and if the authentication is successful, it returns a
2656 * valid $user object from the 'user' table.
2658 * Uses auth_ functions from the currently active auth module
2660 * @uses $CFG
2661 * @param string $username User's username (with system magic quotes)
2662 * @param string $password User's password (with system magic quotes)
2663 * @return user|flase A {@link $USER} object or false if error
2665 function authenticate_user_login($username, $password) {
2667 global $CFG;
2669 $authsenabled = get_enabled_auth_plugins();
2671 if ($user = get_complete_user_data('username', $username)) {
2672 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
2673 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2674 add_to_log(0, 'login', 'error', 'index.php', $username);
2675 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2676 return false;
2678 if (!empty($user->deleted)) {
2679 add_to_log(0, 'login', 'error', 'index.php', $username);
2680 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2681 return false;
2683 $auths = array($auth);
2685 } else {
2686 $auths = $authsenabled;
2687 $user = new object();
2688 $user->id = 0; // User does not exist
2691 foreach ($auths as $auth) {
2692 $authplugin = get_auth_plugin($auth);
2694 // on auth fail fall through to the next plugin
2695 if (!$authplugin->user_login($username, $password)) {
2696 continue;
2699 // successful authentication
2700 if ($user->id) { // User already exists in database
2701 if (empty($user->auth)) { // For some reason auth isn't set yet
2702 set_field('user', 'auth', $auth, 'username', $username);
2703 $user->auth = $auth;
2706 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2708 if (!$authplugin->is_internal()) { // update user record from external DB
2709 $user = update_user_record($username, get_auth_plugin($user->auth));
2711 } else {
2712 // if user not found, create him
2713 $user = create_user_record($username, $password, $auth);
2716 $authplugin->sync_roles($user);
2718 foreach ($authsenabled as $hau) {
2719 $hauth = get_auth_plugin($hau);
2720 $hauth->user_authenticated_hook($user, $username, $password);
2723 /// Log in to a second system if necessary
2724 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2725 if (!empty($CFG->sso)) {
2726 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2727 if (function_exists('sso_user_login')) {
2728 if (!sso_user_login($username, $password)) { // Perform the signon process
2729 notify('Second sign-on failed');
2734 return $user;
2738 // failed if all the plugins have failed
2739 add_to_log(0, 'login', 'error', 'index.php', $username);
2740 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2741 return false;
2745 * Compare password against hash stored in internal user table.
2746 * If necessary it also updates the stored hash to new format.
2748 * @param object user
2749 * @param string plain text password
2750 * @return bool is password valid?
2752 function validate_internal_user_password(&$user, $password) {
2753 global $CFG;
2755 if (!isset($CFG->passwordsaltmain)) {
2756 $CFG->passwordsaltmain = '';
2759 $validated = false;
2761 // get password original encoding in case it was not updated to unicode yet
2762 $textlib = textlib_get_instance();
2763 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2765 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2766 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
2767 $validated = true;
2768 } else {
2769 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
2770 $alt = 'passwordsaltalt'.$i;
2771 if (!empty($CFG->$alt)) {
2772 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2773 $validated = true;
2774 break;
2780 if ($validated) {
2781 // force update of password hash using latest main password salt and encoding if needed
2782 update_internal_user_password($user, $password);
2785 return $validated;
2789 * Calculate hashed value from password using current hash mechanism.
2791 * @param string password
2792 * @return string password hash
2794 function hash_internal_user_password($password) {
2795 global $CFG;
2797 if (isset($CFG->passwordsaltmain)) {
2798 return md5($password.$CFG->passwordsaltmain);
2799 } else {
2800 return md5($password);
2805 * Update pssword hash in user object.
2807 * @param object user
2808 * @param string plain text password
2809 * @param bool store changes also in db, default true
2810 * @return true if hash changed
2812 function update_internal_user_password(&$user, $password) {
2813 global $CFG;
2815 $authplugin = get_auth_plugin($user->auth);
2816 if (!empty($authplugin->config->preventpassindb)) {
2817 $hashedpassword = 'not cached';
2818 } else {
2819 $hashedpassword = hash_internal_user_password($password);
2822 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
2826 * Get a complete user record, which includes all the info
2827 * in the user record
2828 * Intended for setting as $USER session variable
2830 * @uses $CFG
2831 * @uses SITEID
2832 * @param string $field The user field to be checked for a given value.
2833 * @param string $value The value to match for $field.
2834 * @return user A {@link $USER} object.
2836 function get_complete_user_data($field, $value, $mnethostid=null) {
2838 global $CFG;
2840 if (!$field || !$value) {
2841 return false;
2844 /// Build the WHERE clause for an SQL query
2846 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2848 if (is_null($mnethostid)) {
2849 // if null, we restrict to local users
2850 // ** testing for local user can be done with
2851 // mnethostid = $CFG->mnet_localhost_id
2852 // or with
2853 // auth != 'mnet'
2854 // but the first one is FAST with our indexes
2855 $mnethostid = $CFG->mnet_localhost_id;
2857 $mnethostid = (int)$mnethostid;
2858 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2860 /// Get all the basic user data
2862 if (! $user = get_record_select('user', $constraints)) {
2863 return false;
2866 /// Get various settings and preferences
2868 if ($displays = get_records('course_display', 'userid', $user->id)) {
2869 foreach ($displays as $display) {
2870 $user->display[$display->course] = $display->display;
2874 $user->preference = get_user_preferences(null, null, $user->id);
2876 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
2877 foreach ($lastaccesses as $lastaccess) {
2878 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
2882 $sql = "SELECT g.id, g.courseid
2883 FROM {$CFG->prefix}groups g, {$CFG->prefix}groups_members gm
2884 WHERE gm.groupid=g.id AND gm.userid={$user->id}";
2886 // this is a special hack to speedup calendar display
2887 $user->groupmember = array();
2888 if ($groups = get_records_sql($sql)) {
2889 foreach ($groups as $group) {
2890 if (!array_key_exists($group->courseid, $user->groupmember)) {
2891 $user->groupmember[$group->courseid] = array();
2893 $user->groupmember[$group->courseid][$group->id] = $group->id;
2897 /// Rewrite some variables if necessary
2898 if (!empty($user->description)) {
2899 $user->description = true; // No need to cart all of it around
2901 if ($user->username == 'guest') {
2902 $user->lang = $CFG->lang; // Guest language always same as site
2903 $user->firstname = get_string('guestuser'); // Name always in current language
2904 $user->lastname = ' ';
2907 $user->sesskey = random_string(10);
2908 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
2910 return $user;
2914 * @uses $CFG
2915 * @param string $password the password to be checked agains the password policy
2916 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
2917 * @return bool true if the password is valid according to the policy. false otherwise.
2919 function check_password_policy($password, &$errmsg) {
2920 global $CFG;
2922 if (empty($CFG->passwordpolicy)) {
2923 return true;
2926 $textlib = new textlib();
2927 $errmsg = '';
2928 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
2929 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
2931 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
2932 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
2934 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
2935 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
2937 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
2938 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
2940 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
2941 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
2943 } else if ($password == 'admin' or $password == 'password') {
2944 $errmsg = get_string('unsafepassword');
2947 if ($errmsg == '') {
2948 return true;
2949 } else {
2950 return false;
2956 * When logging in, this function is run to set certain preferences
2957 * for the current SESSION
2959 function set_login_session_preferences() {
2960 global $SESSION, $CFG;
2962 $SESSION->justloggedin = true;
2964 unset($SESSION->lang);
2966 // Restore the calendar filters, if saved
2967 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2968 include_once($CFG->dirroot.'/calendar/lib.php');
2969 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
2975 * Delete a course, including all related data from the database,
2976 * and any associated files from the moodledata folder.
2978 * @param int $courseid The id of the course to delete.
2979 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2980 * @return bool true if all the removals succeeded. false if there were any failures. If this
2981 * method returns false, some of the removals will probably have succeeded, and others
2982 * failed, but you have no way of knowing which.
2984 function delete_course($courseid, $showfeedback = true) {
2985 global $CFG;
2986 require_once($CFG->libdir.'/gradelib.php');
2987 $result = true;
2989 if (!remove_course_contents($courseid, $showfeedback)) {
2990 if ($showfeedback) {
2991 notify("An error occurred while deleting some of the course contents.");
2993 $result = false;
2996 remove_course_grades($courseid, $showfeedback);
2998 if (!delete_records("course", "id", $courseid)) {
2999 if ($showfeedback) {
3000 notify("An error occurred while deleting the main course record.");
3002 $result = false;
3005 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE, 'instanceid', $courseid)) {
3006 if ($showfeedback) {
3007 notify("An error occurred while deleting the main context record.");
3009 $result = false;
3012 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
3013 if ($showfeedback) {
3014 notify("An error occurred while deleting the course files.");
3016 $result = false;
3019 return $result;
3023 * Clear a course out completely, deleting all content
3024 * but don't delete the course itself
3026 * @uses $CFG
3027 * @param int $courseid The id of the course that is being deleted
3028 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3029 * @return bool true if all the removals succeeded. false if there were any failures. If this
3030 * method returns false, some of the removals will probably have succeeded, and others
3031 * failed, but you have no way of knowing which.
3033 function remove_course_contents($courseid, $showfeedback=true) {
3035 global $CFG;
3036 include_once($CFG->libdir.'/questionlib.php');
3038 $result = true;
3040 if (! $course = get_record('course', 'id', $courseid)) {
3041 error('Course ID was incorrect (can\'t find it)');
3044 $strdeleted = get_string('deleted');
3046 /// First delete every instance of every module
3048 if ($allmods = get_records('modules') ) {
3049 foreach ($allmods as $mod) {
3050 $modname = $mod->name;
3051 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3052 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3053 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3054 $count=0;
3055 if (file_exists($modfile)) {
3056 include_once($modfile);
3057 if (function_exists($moddelete)) {
3058 if ($instances = get_records($modname, 'course', $course->id)) {
3059 foreach ($instances as $instance) {
3060 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
3061 /// Delete activity context questions and question categories
3062 question_delete_activity($cm, $showfeedback);
3063 delete_context(CONTEXT_MODULE, $cm->id);
3065 if ($moddelete($instance->id)) {
3066 $count++;
3068 } else {
3069 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
3070 $result = false;
3074 } else {
3075 notify('Function '. $moddelete() .'doesn\'t exist!');
3076 $result = false;
3079 if (function_exists($moddeletecourse)) {
3080 $moddeletecourse($course, $showfeedback);
3083 if ($showfeedback) {
3084 notify($strdeleted .' '. $count .' x '. $modname);
3087 } else {
3088 error('No modules are installed!');
3091 /// Give local code a chance to delete its references to this course.
3092 require_once('locallib.php');
3093 notify_local_delete_course($courseid, $showfeedback);
3095 /// Delete course blocks
3097 if ($blocks = get_records_sql("SELECT *
3098 FROM {$CFG->prefix}block_instance
3099 WHERE pagetype = '".PAGE_COURSE_VIEW."'
3100 AND pageid = $course->id")) {
3101 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
3102 if ($showfeedback) {
3103 notify($strdeleted .' block_instance');
3106 require_once($CFG->libdir.'/blocklib.php');
3107 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3109 // Block instances are rarely created. Since the block instance is gone from the above delete
3110 // statement, calling delete_context() will generate a warning as get_context_instance could
3111 // no longer create the context as the block is already gone.
3112 if (record_exists('context', 'contextlevel', CONTEXT_BLOCK, 'instanceid', $block->id)) {
3113 delete_context(CONTEXT_BLOCK, $block->id);
3116 // fix for MDL-7164
3117 // Get the block object and call instance_delete()
3118 if (!$record = blocks_get_record($block->blockid)) {
3119 $result = false;
3120 continue;
3122 if (!$obj = block_instance($record->name, $block)) {
3123 $result = false;
3124 continue;
3126 // Return value ignored, in core mods this does not do anything, but just in case
3127 // third party blocks might have stuff to clean up
3128 // we execute this anyway
3129 $obj->instance_delete();
3131 } else {
3132 $result = false;
3136 /// Delete any groups, removing members and grouping/course links first.
3137 require_once($CFG->dirroot.'/group/lib.php');
3138 groups_delete_groupings($courseid, true);
3139 groups_delete_groups($courseid, true);
3141 /// Delete all related records in other tables that may have a courseid
3142 /// This array stores the tables that need to be cleared, as
3143 /// table_name => column_name that contains the course id.
3145 $tablestoclear = array(
3146 'event' => 'courseid', // Delete events
3147 'log' => 'course', // Delete logs
3148 'course_sections' => 'course', // Delete any course stuff
3149 'course_modules' => 'course',
3150 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3151 'backup_log' => 'courseid'
3153 foreach ($tablestoclear as $table => $col) {
3154 if (delete_records($table, $col, $course->id)) {
3155 if ($showfeedback) {
3156 notify($strdeleted . ' ' . $table);
3158 } else {
3159 $result = false;
3164 /// Clean up metacourse stuff
3166 if ($course->metacourse) {
3167 delete_records("course_meta","parent_course",$course->id);
3168 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3169 if ($showfeedback) {
3170 notify("$strdeleted course_meta");
3172 } else {
3173 if ($parents = get_records("course_meta","child_course",$course->id)) {
3174 foreach ($parents as $parent) {
3175 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3177 if ($showfeedback) {
3178 notify("$strdeleted course_meta");
3183 /// Delete questions and question categories
3184 question_delete_course($course, $showfeedback);
3186 /// Delete all roles and overiddes in the course context (but keep the course context)
3187 if ($courseid != SITEID) {
3188 delete_context(CONTEXT_COURSE, $course->id);
3191 // fix for MDL-9016
3192 // clear the cache because the course context is deleted, and
3193 // we don't want to write assignment, overrides and context_rel table
3194 // with this old context id!
3195 get_context_instance('clearcache');
3196 return $result;
3201 * This function will empty a course of USER data as much as
3202 /// possible. It will retain the activities and the structure
3203 /// of the course.
3205 * @uses $USER
3206 * @uses $SESSION
3207 * @uses $CFG
3208 * @param object $data an object containing all the boolean settings and courseid
3209 * @param bool $showfeedback if false then do it all silently
3210 * @return bool
3211 * @todo Finish documenting this function
3213 function reset_course_userdata($data, $showfeedback=true) {
3215 global $CFG, $USER, $SESSION;
3216 require_once($CFG->dirroot.'/group/lib.php');
3218 $result = true;
3220 $strdeleted = get_string('deleted');
3222 // Look in every instance of every module for data to delete
3224 if ($allmods = get_records('modules') ) {
3225 foreach ($allmods as $mod) {
3226 $modname = $mod->name;
3227 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3228 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3229 if (file_exists($modfile)) {
3230 @include_once($modfile);
3231 if (function_exists($moddeleteuserdata)) {
3232 $moddeleteuserdata($data, $showfeedback);
3236 } else {
3237 error('No modules are installed!');
3240 // Delete other stuff
3241 $coursecontext = get_context_instance(CONTEXT_COURSE, $data->courseid);
3243 if (!empty($data->reset_students) or !empty($data->reset_teachers)) {
3244 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3245 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3246 $students = array_diff($participants, $teachers);
3248 if (!empty($data->reset_students)) {
3249 foreach ($students as $studentid) {
3250 role_unassign(0, $studentid, 0, $coursecontext->id);
3252 if ($showfeedback) {
3253 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3256 /// Delete group members (but keep the groups)
3257 $result = groups_delete_group_members($data->courseid, $showfeedback) && $result;
3260 if (!empty($data->reset_teachers)) {
3261 foreach ($teachers as $teacherid) {
3262 role_unassign(0, $teacherid, 0, $coursecontext->id);
3264 if ($showfeedback) {
3265 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3270 if (!empty($data->reset_groups)) {
3271 $result = groups_delete_groupings($data->courseid, $showfeedback) && $result;
3272 $result = groups_delete_groups($data->courseid, $showfeedback) && $result;
3275 if (!empty($data->reset_events)) {
3276 if (delete_records('event', 'courseid', $data->courseid)) {
3277 if ($showfeedback) {
3278 notify($strdeleted .' event', 'notifysuccess');
3280 } else {
3281 $result = false;
3285 if (!empty($data->reset_logs)) {
3286 if (delete_records('log', 'course', $data->courseid)) {
3287 if ($showfeedback) {
3288 notify($strdeleted .' log', 'notifysuccess');
3290 } else {
3291 $result = false;
3295 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
3296 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
3297 delete_records('role_capabilities', 'contextid', $context->id);
3299 return $result;
3302 function generate_email_processing_address($modid,$modargs) {
3303 global $CFG;
3305 if (empty($CFG->siteidentifier)) { // Unique site identification code
3306 set_config('siteidentifier', random_string(32));
3309 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3310 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
3314 function moodle_process_email($modargs,$body) {
3315 // the first char should be an unencoded letter. We'll take this as an action
3316 switch ($modargs{0}) {
3317 case 'B': { // bounce
3318 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3319 if ($user = get_record_select("user","id=$userid","id,email")) {
3320 // check the half md5 of their email
3321 $md5check = substr(md5($user->email),0,16);
3322 if ($md5check == substr($modargs, -16)) {
3323 set_bounce_count($user);
3325 // else maybe they've already changed it?
3328 break;
3329 // maybe more later?
3333 /// CORRESPONDENCE ////////////////////////////////////////////////
3336 * Send an email to a specified user
3338 * @uses $CFG
3339 * @uses $FULLME
3340 * @uses SITEID
3341 * @param user $user A {@link $USER} object
3342 * @param user $from A {@link $USER} object
3343 * @param string $subject plain text subject line of the email
3344 * @param string $messagetext plain text version of the message
3345 * @param string $messagehtml complete html version of the message (optional)
3346 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3347 * @param string $attachname the name of the file (extension indicates MIME)
3348 * @param bool $usetrueaddress determines whether $from email address should
3349 * be sent out. Will be overruled by user profile setting for maildisplay
3350 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3351 * was blocked by user and "false" if there was another sort of error.
3353 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3355 global $CFG, $FULLME;
3357 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
3359 /// We are going to use textlib services here
3360 $textlib = textlib_get_instance();
3362 if (empty($user)) {
3363 return false;
3366 // skip mail to suspended users
3367 if (isset($user->auth) && $user->auth=='nologin') {
3368 return true;
3371 if (!empty($user->emailstop)) {
3372 return 'emailstop';
3375 if (over_bounce_threshold($user)) {
3376 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3377 return false;
3380 $mail = new phpmailer;
3382 $mail->Version = 'Moodle '. $CFG->version; // mailer version
3383 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
3385 $mail->CharSet = 'UTF-8';
3387 if ($CFG->smtphosts == 'qmail') {
3388 $mail->IsQmail(); // use Qmail system
3390 } else if (empty($CFG->smtphosts)) {
3391 $mail->IsMail(); // use PHP mail() = sendmail
3393 } else {
3394 $mail->IsSMTP(); // use SMTP directly
3395 if (!empty($CFG->debugsmtp)) {
3396 echo '<pre>' . "\n";
3397 $mail->SMTPDebug = true;
3399 $mail->Host = $CFG->smtphosts; // specify main and backup servers
3401 if ($CFG->smtpuser) { // Use SMTP authentication
3402 $mail->SMTPAuth = true;
3403 $mail->Username = $CFG->smtpuser;
3404 $mail->Password = $CFG->smtppass;
3408 $supportuser = generate_email_supportuser();
3411 // make up an email address for handling bounces
3412 if (!empty($CFG->handlebounces)) {
3413 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
3414 $mail->Sender = generate_email_processing_address(0,$modargs);
3415 } else {
3416 $mail->Sender = $supportuser->email;
3419 if (is_string($from)) { // So we can pass whatever we want if there is need
3420 $mail->From = $CFG->noreplyaddress;
3421 $mail->FromName = $from;
3422 } else if ($usetrueaddress and $from->maildisplay) {
3423 $mail->From = $from->email;
3424 $mail->FromName = fullname($from);
3425 } else {
3426 $mail->From = $CFG->noreplyaddress;
3427 $mail->FromName = fullname($from);
3428 if (empty($replyto)) {
3429 $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
3433 if (!empty($replyto)) {
3434 $mail->AddReplyTo($replyto,$replytoname);
3437 $mail->Subject = substr(stripslashes($subject), 0, 900);
3439 $mail->AddAddress($user->email, fullname($user) );
3441 $mail->WordWrap = 79; // set word wrap
3443 if (!empty($from->customheaders)) { // Add custom headers
3444 if (is_array($from->customheaders)) {
3445 foreach ($from->customheaders as $customheader) {
3446 $mail->AddCustomHeader($customheader);
3448 } else {
3449 $mail->AddCustomHeader($from->customheaders);
3453 if (!empty($from->priority)) {
3454 $mail->Priority = $from->priority;
3457 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
3458 $mail->IsHTML(true);
3459 $mail->Encoding = 'quoted-printable'; // Encoding to use
3460 $mail->Body = $messagehtml;
3461 $mail->AltBody = "\n$messagetext\n";
3462 } else {
3463 $mail->IsHTML(false);
3464 $mail->Body = "\n$messagetext\n";
3467 if ($attachment && $attachname) {
3468 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3469 $mail->AddAddress($supportuser->email, fullname($supportuser, true) );
3470 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3471 } else {
3472 require_once($CFG->libdir.'/filelib.php');
3473 $mimetype = mimeinfo('type', $attachname);
3474 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
3480 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3481 /// encoding to the specified one
3482 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
3483 /// Set it to site mail charset
3484 $charset = $CFG->sitemailcharset;
3485 /// Overwrite it with the user mail charset
3486 if (!empty($CFG->allowusermailcharset)) {
3487 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
3488 $charset = $useremailcharset;
3491 /// If it has changed, convert all the necessary strings
3492 $charsets = get_list_of_charsets();
3493 unset($charsets['UTF-8']);
3494 if (in_array($charset, $charsets)) {
3495 /// Save the new mail charset
3496 $mail->CharSet = $charset;
3497 /// And convert some strings
3498 $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
3499 foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names
3500 $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet);
3502 $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject
3503 foreach ($mail->to as $key => $to) {
3504 $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet); //To Names
3506 $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body
3507 $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject
3511 if ($mail->Send()) {
3512 set_send_count($user);
3513 $mail->IsSMTP(); // use SMTP directly
3514 if (!empty($CFG->debugsmtp)) {
3515 echo '</pre>';
3517 return true;
3518 } else {
3519 mtrace('ERROR: '. $mail->ErrorInfo);
3520 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
3521 if (!empty($CFG->debugsmtp)) {
3522 echo '</pre>';
3524 return false;
3529 * Generate a signoff for emails based on support settings
3532 function generate_email_signoff() {
3533 global $CFG;
3535 $signoff = "\n";
3536 if (!empty($CFG->supportname)) {
3537 $signoff .= $CFG->supportname."\n";
3539 if (!empty($CFG->supportemail)) {
3540 $signoff .= $CFG->supportemail."\n";
3542 if (!empty($CFG->supportpage)) {
3543 $signoff .= $CFG->supportpage."\n";
3545 return $signoff;
3549 * Generate a fake user for emails based on support settings
3552 function generate_email_supportuser() {
3554 global $CFG;
3556 static $supportuser;
3558 if (!empty($supportuser)) {
3559 return $supportuser;
3562 $supportuser = new object;
3563 $supportuser->email = $CFG->supportemail ? $CFG->supportemail : $CFG->noreplyaddress;
3564 $supportuser->firstname = $CFG->supportname ? $CFG->supportname : get_string('noreplyname');
3565 $supportuser->lastname = '';
3567 return $supportuser;
3572 * Sets specified user's password and send the new password to the user via email.
3574 * @uses $CFG
3575 * @param user $user A {@link $USER} object
3576 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3577 * was blocked by user and "false" if there was another sort of error.
3579 function setnew_password_and_mail($user) {
3581 global $CFG;
3583 $site = get_site();
3585 $supportuser = generate_email_supportuser();
3587 $newpassword = generate_password();
3589 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
3590 trigger_error('Could not set user password!');
3591 return false;
3594 $a = new object();
3595 $a->firstname = fullname($user, true);
3596 $a->sitename = format_string($site->fullname);
3597 $a->username = $user->username;
3598 $a->newpassword = $newpassword;
3599 $a->link = $CFG->wwwroot .'/login/';
3600 $a->signoff = generate_email_signoff();
3602 $message = get_string('newusernewpasswordtext', '', $a);
3604 $subject = format_string($site->fullname) .': '. get_string('newusernewpasswordsubj');
3606 return email_to_user($user, $supportuser, $subject, $message);
3611 * Resets specified user's password and send the new password to the user via email.
3613 * @uses $CFG
3614 * @param user $user A {@link $USER} object
3615 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3616 * was blocked by user and "false" if there was another sort of error.
3618 function reset_password_and_mail($user) {
3620 global $CFG;
3622 $site = get_site();
3623 $supportuser = generate_email_supportuser();
3625 $userauth = get_auth_plugin($user->auth);
3626 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
3627 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3628 return false;
3631 $newpassword = generate_password();
3633 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3634 error("Could not set user password!");
3637 $a = new object();
3638 $a->firstname = $user->firstname;
3639 $a->sitename = format_string($site->fullname);
3640 $a->username = $user->username;
3641 $a->newpassword = $newpassword;
3642 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
3643 $a->signoff = generate_email_signoff();
3645 $message = get_string('newpasswordtext', '', $a);
3647 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
3649 return email_to_user($user, $supportuser, $subject, $message);
3654 * Send email to specified user with confirmation text and activation link.
3656 * @uses $CFG
3657 * @param user $user A {@link $USER} object
3658 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3659 * was blocked by user and "false" if there was another sort of error.
3661 function send_confirmation_email($user) {
3663 global $CFG;
3665 $site = get_site();
3666 $supportuser = generate_email_supportuser();
3668 $data = new object();
3669 $data->firstname = fullname($user);
3670 $data->sitename = format_string($site->fullname);
3671 $data->admin = generate_email_signoff();
3673 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
3675 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. urlencode($user->username);
3676 $message = get_string('emailconfirmation', '', $data);
3677 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3679 $user->mailformat = 1; // Always send HTML version as well
3681 return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
3686 * send_password_change_confirmation_email.
3688 * @uses $CFG
3689 * @param user $user A {@link $USER} object
3690 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3691 * was blocked by user and "false" if there was another sort of error.
3693 function send_password_change_confirmation_email($user) {
3695 global $CFG;
3697 $site = get_site();
3698 $supportuser = generate_email_supportuser();
3700 $data = new object();
3701 $data->firstname = $user->firstname;
3702 $data->sitename = format_string($site->fullname);
3703 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
3704 $data->admin = generate_email_signoff();
3706 $message = get_string('emailpasswordconfirmation', '', $data);
3707 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
3709 return email_to_user($user, $supportuser, $subject, $message);
3714 * send_password_change_info.
3716 * @uses $CFG
3717 * @param user $user A {@link $USER} object
3718 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3719 * was blocked by user and "false" if there was another sort of error.
3721 function send_password_change_info($user) {
3723 global $CFG;
3725 $site = get_site();
3726 $supportuser = generate_email_supportuser();
3727 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
3729 $data = new object();
3730 $data->firstname = $user->firstname;
3731 $data->sitename = format_string($site->fullname);
3732 $data->admin = generate_email_signoff();
3734 $userauth = get_auth_plugin($user->auth);
3736 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
3737 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
3738 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3739 return email_to_user($user, $supportuser, $subject, $message);
3742 if ($userauth->can_change_password() and $userauth->change_password_url()) {
3743 // we have some external url for password changing
3744 $data->link .= $userauth->change_password_url();
3746 } else {
3747 //no way to change password, sorry
3748 $data->link = '';
3751 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
3752 $message = get_string('emailpasswordchangeinfo', '', $data);
3753 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3754 } else {
3755 $message = get_string('emailpasswordchangeinfofail', '', $data);
3756 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3759 return email_to_user($user, $supportuser, $subject, $message);
3764 * Check that an email is allowed. It returns an error message if there
3765 * was a problem.
3767 * @uses $CFG
3768 * @param string $email Content of email
3769 * @return string|false
3771 function email_is_not_allowed($email) {
3773 global $CFG;
3775 if (!empty($CFG->allowemailaddresses)) {
3776 $allowed = explode(' ', $CFG->allowemailaddresses);
3777 foreach ($allowed as $allowedpattern) {
3778 $allowedpattern = trim($allowedpattern);
3779 if (!$allowedpattern) {
3780 continue;
3782 if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
3783 return false;
3786 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
3788 } else if (!empty($CFG->denyemailaddresses)) {
3789 $denied = explode(' ', $CFG->denyemailaddresses);
3790 foreach ($denied as $deniedpattern) {
3791 $deniedpattern = trim($deniedpattern);
3792 if (!$deniedpattern) {
3793 continue;
3795 if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
3796 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
3801 return false;
3804 function email_welcome_message_to_user($course, $user=NULL) {
3805 global $CFG, $USER;
3807 if (empty($user)) {
3808 if (!isloggedin()) {
3809 return false;
3811 $user = $USER;
3814 if (!empty($course->welcomemessage)) {
3815 $subject = get_string('welcometocourse', '', format_string($course->fullname));
3817 $a->coursename = $course->fullname;
3818 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3819 //$message = get_string("welcometocoursetext", "", $a);
3820 $message = $course->welcomemessage;
3822 if (! $teacher = get_teacher($course->id)) {
3823 $teacher = get_admin();
3825 email_to_user($user, $teacher, $subject, $message);
3829 /// FILE HANDLING /////////////////////////////////////////////
3833 * Makes an upload directory for a particular module.
3835 * @uses $CFG
3836 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
3837 * @return string|false Returns full path to directory if successful, false if not
3839 function make_mod_upload_directory($courseid) {
3840 global $CFG;
3842 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
3843 return false;
3846 $strreadme = get_string('readme');
3848 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
3849 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3850 } else {
3851 copy($CFG->dirroot .'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3853 return $moddata;
3857 * Returns current name of file on disk if it exists.
3859 * @param string $newfile File to be verified
3860 * @return string Current name of file on disk if true
3862 function valid_uploaded_file($newfile) {
3863 if (empty($newfile)) {
3864 return '';
3866 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
3867 return $newfile['tmp_name'];
3868 } else {
3869 return '';
3874 * Returns the maximum size for uploading files.
3876 * There are seven possible upload limits:
3877 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3878 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3879 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3880 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3881 * 5. by the Moodle admin in $CFG->maxbytes
3882 * 6. by the teacher in the current course $course->maxbytes
3883 * 7. by the teacher for the current module, eg $assignment->maxbytes
3885 * These last two are passed to this function as arguments (in bytes).
3886 * Anything defined as 0 is ignored.
3887 * The smallest of all the non-zero numbers is returned.
3889 * @param int $sizebytes ?
3890 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3891 * @param int $modulebytes Current module ->maxbytes (in bytes)
3892 * @return int The maximum size for uploading files.
3893 * @todo Finish documenting this function
3895 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3897 if (! $filesize = ini_get('upload_max_filesize')) {
3898 $filesize = '5M';
3900 $minimumsize = get_real_size($filesize);
3902 if ($postsize = ini_get('post_max_size')) {
3903 $postsize = get_real_size($postsize);
3904 if ($postsize < $minimumsize) {
3905 $minimumsize = $postsize;
3909 if ($sitebytes and $sitebytes < $minimumsize) {
3910 $minimumsize = $sitebytes;
3913 if ($coursebytes and $coursebytes < $minimumsize) {
3914 $minimumsize = $coursebytes;
3917 if ($modulebytes and $modulebytes < $minimumsize) {
3918 $minimumsize = $modulebytes;
3921 return $minimumsize;
3925 * Related to {@link get_max_upload_file_size()} - this function returns an
3926 * array of possible sizes in an array, translated to the
3927 * local language.
3929 * @uses SORT_NUMERIC
3930 * @param int $sizebytes ?
3931 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3932 * @param int $modulebytes Current module ->maxbytes (in bytes)
3933 * @return int
3934 * @todo Finish documenting this function
3936 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3937 global $CFG;
3939 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
3940 return array();
3943 $filesize[$maxsize] = display_size($maxsize);
3945 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
3946 5242880, 10485760, 20971520, 52428800, 104857600);
3948 // Allow maxbytes to be selected if it falls outside the above boundaries
3949 if( isset($CFG->maxbytes) && !in_array($CFG->maxbytes, $sizelist) ){
3950 $sizelist[] = $CFG->maxbytes;
3953 foreach ($sizelist as $sizebytes) {
3954 if ($sizebytes < $maxsize) {
3955 $filesize[$sizebytes] = display_size($sizebytes);
3959 krsort($filesize, SORT_NUMERIC);
3961 return $filesize;
3965 * If there has been an error uploading a file, print the appropriate error message
3966 * Numerical constants used as constant definitions not added until PHP version 4.2.0
3968 * $filearray is a 1-dimensional sub-array of the $_FILES array
3969 * eg $filearray = $_FILES['userfile1']
3970 * If left empty then the first element of the $_FILES array will be used
3972 * @uses $_FILES
3973 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
3974 * @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.
3975 * @return bool|string
3977 function print_file_upload_error($filearray = '', $returnerror = false) {
3979 if ($filearray == '' or !isset($filearray['error'])) {
3981 if (empty($_FILES)) return false;
3983 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
3984 $filearray = array_shift($files); /// use first element of array
3987 switch ($filearray['error']) {
3989 case 0: // UPLOAD_ERR_OK
3990 if ($filearray['size'] > 0) {
3991 $errmessage = get_string('uploadproblem', $filearray['name']);
3992 } else {
3993 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
3995 break;
3997 case 1: // UPLOAD_ERR_INI_SIZE
3998 $errmessage = get_string('uploadserverlimit');
3999 break;
4001 case 2: // UPLOAD_ERR_FORM_SIZE
4002 $errmessage = get_string('uploadformlimit');
4003 break;
4005 case 3: // UPLOAD_ERR_PARTIAL
4006 $errmessage = get_string('uploadpartialfile');
4007 break;
4009 case 4: // UPLOAD_ERR_NO_FILE
4010 $errmessage = get_string('uploadnofilefound');
4011 break;
4013 default:
4014 $errmessage = get_string('uploadproblem', $filearray['name']);
4017 if ($returnerror) {
4018 return $errmessage;
4019 } else {
4020 notify($errmessage);
4021 return true;
4027 * handy function to loop through an array of files and resolve any filename conflicts
4028 * both in the array of filenames and for what is already on disk.
4029 * not really compatible with the similar function in uploadlib.php
4030 * but this could be used for files/index.php for moving files around.
4033 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4034 foreach ($files as $k => $f) {
4035 if (check_potential_filename($destination,$f,$files)) {
4036 $bits = explode('.', $f);
4037 for ($i = 1; true; $i++) {
4038 $try = sprintf($format, $bits[0], $i, $bits[1]);
4039 if (!check_potential_filename($destination,$try,$files)) {
4040 $files[$k] = $try;
4041 break;
4046 return $files;
4050 * @used by resolve_filename_collisions
4052 function check_potential_filename($destination,$filename,$files) {
4053 if (file_exists($destination.'/'.$filename)) {
4054 return true;
4056 if (count(array_keys($files,$filename)) > 1) {
4057 return true;
4059 return false;
4064 * Returns an array with all the filenames in
4065 * all subdirectories, relative to the given rootdir.
4066 * If excludefile is defined, then that file/directory is ignored
4067 * If getdirs is true, then (sub)directories are included in the output
4068 * If getfiles is true, then files are included in the output
4069 * (at least one of these must be true!)
4071 * @param string $rootdir ?
4072 * @param string $excludefile If defined then the specified file/directory is ignored
4073 * @param bool $descend ?
4074 * @param bool $getdirs If true then (sub)directories are included in the output
4075 * @param bool $getfiles If true then files are included in the output
4076 * @return array An array with all the filenames in
4077 * all subdirectories, relative to the given rootdir
4078 * @todo Finish documenting this function. Add examples of $excludefile usage.
4080 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4082 $dirs = array();
4084 if (!$getdirs and !$getfiles) { // Nothing to show
4085 return $dirs;
4088 if (!is_dir($rootdir)) { // Must be a directory
4089 return $dirs;
4092 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4093 return $dirs;
4096 if (!is_array($excludefiles)) {
4097 $excludefiles = array($excludefiles);
4100 while (false !== ($file = readdir($dir))) {
4101 $firstchar = substr($file, 0, 1);
4102 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4103 continue;
4105 $fullfile = $rootdir .'/'. $file;
4106 if (filetype($fullfile) == 'dir') {
4107 if ($getdirs) {
4108 $dirs[] = $file;
4110 if ($descend) {
4111 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4112 foreach ($subdirs as $subdir) {
4113 $dirs[] = $file .'/'. $subdir;
4116 } else if ($getfiles) {
4117 $dirs[] = $file;
4120 closedir($dir);
4122 asort($dirs);
4124 return $dirs;
4129 * Adds up all the files in a directory and works out the size.
4131 * @param string $rootdir ?
4132 * @param string $excludefile ?
4133 * @return array
4134 * @todo Finish documenting this function
4136 function get_directory_size($rootdir, $excludefile='') {
4138 global $CFG;
4140 // do it this way if we can, it's much faster
4141 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
4142 $command = trim($CFG->pathtodu).' -sk --apparent-size '.escapeshellarg($rootdir);
4143 $output = null;
4144 $return = null;
4145 exec($command,$output,$return);
4146 if (is_array($output)) {
4147 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4151 if (!is_dir($rootdir)) { // Must be a directory
4152 return 0;
4155 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
4156 return 0;
4159 $size = 0;
4161 while (false !== ($file = readdir($dir))) {
4162 $firstchar = substr($file, 0, 1);
4163 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4164 continue;
4166 $fullfile = $rootdir .'/'. $file;
4167 if (filetype($fullfile) == 'dir') {
4168 $size += get_directory_size($fullfile, $excludefile);
4169 } else {
4170 $size += filesize($fullfile);
4173 closedir($dir);
4175 return $size;
4179 * Converts bytes into display form
4181 * @param string $size ?
4182 * @return string
4183 * @staticvar string $gb Localized string for size in gigabytes
4184 * @staticvar string $mb Localized string for size in megabytes
4185 * @staticvar string $kb Localized string for size in kilobytes
4186 * @staticvar string $b Localized string for size in bytes
4187 * @todo Finish documenting this function. Verify return type.
4189 function display_size($size) {
4191 static $gb, $mb, $kb, $b;
4193 if (empty($gb)) {
4194 $gb = get_string('sizegb');
4195 $mb = get_string('sizemb');
4196 $kb = get_string('sizekb');
4197 $b = get_string('sizeb');
4200 if ($size >= 1073741824) {
4201 $size = round($size / 1073741824 * 10) / 10 . $gb;
4202 } else if ($size >= 1048576) {
4203 $size = round($size / 1048576 * 10) / 10 . $mb;
4204 } else if ($size >= 1024) {
4205 $size = round($size / 1024 * 10) / 10 . $kb;
4206 } else {
4207 $size = $size .' '. $b;
4209 return $size;
4213 * Cleans a given filename by removing suspicious or troublesome characters
4214 * Only these are allowed: alphanumeric _ - .
4215 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4217 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4218 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4220 * @param string $string file name
4221 * @return string cleaned file name
4223 function clean_filename($string) {
4224 global $CFG;
4225 if (empty($CFG->unicodecleanfilename)) {
4226 $textlib = textlib_get_instance();
4227 $string = $textlib->specialtoascii($string);
4228 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4229 } else {
4230 //clean only ascii range
4231 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4233 $string = preg_replace("/_+/", '_', $string);
4234 $string = preg_replace("/\.\.+/", '.', $string);
4235 return $string;
4239 /// STRING TRANSLATION ////////////////////////////////////////
4242 * Returns the code for the current language
4244 * @uses $CFG
4245 * @param $USER
4246 * @param $SESSION
4247 * @return string
4249 function current_language() {
4250 global $CFG, $USER, $SESSION, $COURSE;
4252 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
4253 $return = $COURSE->lang;
4255 } else if (!empty($SESSION->lang)) { // Session language can override other settings
4256 $return = $SESSION->lang;
4258 } else if (!empty($USER->lang)) {
4259 $return = $USER->lang;
4261 } else {
4262 $return = $CFG->lang;
4265 if ($return == 'en') {
4266 $return = 'en_utf8';
4269 return $return;
4273 * Prints out a translated string.
4275 * Prints out a translated string using the return value from the {@link get_string()} function.
4277 * Example usage of this function when the string is in the moodle.php file:<br/>
4278 * <code>
4279 * echo '<strong>';
4280 * print_string('wordforstudent');
4281 * echo '</strong>';
4282 * </code>
4284 * Example usage of this function when the string is not in the moodle.php file:<br/>
4285 * <code>
4286 * echo '<h1>';
4287 * print_string('typecourse', 'calendar');
4288 * echo '</h1>';
4289 * </code>
4291 * @param string $identifier The key identifier for the localized string
4292 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4293 * @param mixed $a An object, string or number that can be used
4294 * within translation strings
4296 function print_string($identifier, $module='', $a=NULL) {
4297 echo get_string($identifier, $module, $a);
4301 * fix up the optional data in get_string()/print_string() etc
4302 * ensure possible sprintf() format characters are escaped correctly
4303 * needs to handle arbitrary strings and objects
4304 * @param mixed $a An object, string or number that can be used
4305 * @return mixed the supplied parameter 'cleaned'
4307 function clean_getstring_data( $a ) {
4308 if (is_string($a)) {
4309 return str_replace( '%','%%',$a );
4311 elseif (is_object($a)) {
4312 $a_vars = get_object_vars( $a );
4313 $new_a_vars = array();
4314 foreach ($a_vars as $fname => $a_var) {
4315 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4317 return (object)$new_a_vars;
4319 else {
4320 return $a;
4325 * @return array places to look for lang strings based on the prefix to the
4326 * module name. For example qtype_ in question/type. Used by get_string and
4327 * help.php.
4329 function places_to_search_for_lang_strings() {
4330 global $CFG;
4332 return array(
4333 '__exceptions' => array('moodle', 'langconfig'),
4334 'assignment_' => array('mod/assignment/type'),
4335 'auth_' => array('auth'),
4336 'block_' => array('blocks'),
4337 'datafield_' => array('mod/data/field'),
4338 'datapreset_' => array('mod/data/preset'),
4339 'enrol_' => array('enrol'),
4340 'format_' => array('course/format'),
4341 'qtype_' => array('question/type'),
4342 'report_' => array($CFG->admin.'/report', 'course/report', 'mod/quiz/report'),
4343 'resource_' => array('mod/resource/type'),
4344 'gradereport_' => array('grade/report'),
4345 'gradeimport_' => array('grade/import'),
4346 'gradeexport_' => array('grade/export'),
4347 '' => array('mod')
4352 * Returns a localized string.
4354 * Returns the translated string specified by $identifier as
4355 * for $module. Uses the same format files as STphp.
4356 * $a is an object, string or number that can be used
4357 * within translation strings
4359 * eg "hello \$a->firstname \$a->lastname"
4360 * or "hello \$a"
4362 * If you would like to directly echo the localized string use
4363 * the function {@link print_string()}
4365 * Example usage of this function involves finding the string you would
4366 * like a local equivalent of and using its identifier and module information
4367 * to retrive it.<br/>
4368 * If you open moodle/lang/en/moodle.php and look near line 1031
4369 * you will find a string to prompt a user for their word for student
4370 * <code>
4371 * $string['wordforstudent'] = 'Your word for Student';
4372 * </code>
4373 * So if you want to display the string 'Your word for student'
4374 * in any language that supports it on your site
4375 * you just need to use the identifier 'wordforstudent'
4376 * <code>
4377 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4379 * </code>
4380 * If the string you want is in another file you'd take a slightly
4381 * different approach. Looking in moodle/lang/en/calendar.php you find
4382 * around line 75:
4383 * <code>
4384 * $string['typecourse'] = 'Course event';
4385 * </code>
4386 * If you want to display the string "Course event" in any language
4387 * supported you would use the identifier 'typecourse' and the module 'calendar'
4388 * (because it is in the file calendar.php):
4389 * <code>
4390 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4391 * </code>
4393 * As a last resort, should the identifier fail to map to a string
4394 * the returned string will be [[ $identifier ]]
4396 * @uses $CFG
4397 * @param string $identifier The key identifier for the localized string
4398 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4399 * @param mixed $a An object, string or number that can be used
4400 * within translation strings
4401 * @param array $extralocations An array of strings with other locations to look for string files
4402 * @return string The localized string.
4404 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4406 global $CFG;
4408 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4409 $langconfigstrs = array('alphabet', 'backupnameformat', 'decsep', 'firstdayofweek', 'listsep', 'locale',
4410 'localewin', 'localewincharset', 'oldcharset',
4411 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4412 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4413 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4414 'thischarset', 'thisdirection', 'thislanguage');
4416 $filetocheck = 'langconfig.php';
4417 $defaultlang = 'en_utf8';
4418 if (in_array($identifier, $langconfigstrs)) {
4419 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4422 $lang = current_language();
4424 if ($module == '') {
4425 $module = 'moodle';
4428 // if $a happens to have % in it, double it so sprintf() doesn't break
4429 if ($a) {
4430 $a = clean_getstring_data( $a );
4433 /// Define the two or three major locations of language strings for this module
4434 $locations = array();
4436 if (!empty($extralocations)) { // Calling code has a good idea where to look
4437 if (is_array($extralocations)) {
4438 $locations += $extralocations;
4439 } else if (is_string($extralocations)) {
4440 $locations[] = $extralocations;
4441 } else {
4442 debugging('Bad lang path provided');
4446 if (isset($CFG->running_installer)) {
4447 $module = 'installer';
4448 $filetocheck = 'installer.php';
4449 $locations += array( $CFG->dirroot.'/install/lang/', $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
4450 $defaultlang = 'en_utf8';
4451 } else {
4452 $locations += array( $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
4455 /// Add extra places to look for strings for particular plugin types.
4456 $rules = places_to_search_for_lang_strings();
4457 $exceptions = $rules['__exceptions'];
4458 unset($rules['__exceptions']);
4460 if (!in_array($module, $exceptions)) {
4461 $dividerpos = strpos($module, '_');
4462 if ($dividerpos === false) {
4463 $type = '';
4464 $plugin = $module;
4465 } else {
4466 $type = substr($module, 0, $dividerpos + 1);
4467 $plugin = substr($module, $dividerpos + 1);
4469 if (!empty($rules[$type])) {
4470 foreach ($rules[$type] as $location) {
4471 $locations[] = $CFG->dirroot . "/$location/$plugin/lang/";
4476 /// First check all the normal locations for the string in the current language
4477 $resultstring = '';
4478 foreach ($locations as $location) {
4479 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4480 if (file_exists($locallangfile)) {
4481 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4482 eval($result);
4483 return $resultstring;
4486 //if local directory not found, or particular string does not exist in local direcotry
4487 $langfile = $location.$lang.'/'.$module.'.php';
4488 if (file_exists($langfile)) {
4489 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4490 eval($result);
4491 return $resultstring;
4496 /// If the preferred language was English (utf8) we can abort now
4497 /// saving some checks beacuse it's the only "root" lang
4498 if ($lang == 'en_utf8') {
4499 return '[['. $identifier .']]';
4502 /// Is a parent language defined? If so, try to find this string in a parent language file
4504 foreach ($locations as $location) {
4505 $langfile = $location.$lang.'/'.$filetocheck;
4506 if (file_exists($langfile)) {
4507 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4508 eval($result);
4509 if (!empty($parentlang)) { // found it!
4511 //first, see if there's a local file for parent
4512 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4513 if (file_exists($locallangfile)) {
4514 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4515 eval($result);
4516 return $resultstring;
4520 //if local directory not found, or particular string does not exist in local direcotry
4521 $langfile = $location.$parentlang.'/'.$module.'.php';
4522 if (file_exists($langfile)) {
4523 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4524 eval($result);
4525 return $resultstring;
4533 /// Our only remaining option is to try English
4535 foreach ($locations as $location) {
4536 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4537 if (file_exists($locallangfile)) {
4538 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4539 eval($result);
4540 return $resultstring;
4544 //if local_en not found, or string not found in local_en
4545 $langfile = $location.$defaultlang.'/'.$module.'.php';
4547 if (file_exists($langfile)) {
4548 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4549 eval($result);
4550 return $resultstring;
4555 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4556 /// if it hasn't been queried before.
4557 if ($defaultlang == 'en') {
4558 $defaultlang = 'en_utf8';
4559 foreach ($locations as $location) {
4560 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4561 if (file_exists($locallangfile)) {
4562 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4563 eval($result);
4564 return $resultstring;
4568 //if local_en not found, or string not found in local_en
4569 $langfile = $location.$defaultlang.'/'.$module.'.php';
4571 if (file_exists($langfile)) {
4572 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4573 eval($result);
4574 return $resultstring;
4580 return '[['.$identifier.']]'; // Last resort
4584 * This function is only used from {@link get_string()}.
4586 * @internal Only used from get_string, not meant to be public API
4587 * @param string $identifier ?
4588 * @param string $langfile ?
4589 * @param string $destination ?
4590 * @return string|false ?
4591 * @staticvar array $strings Localized strings
4592 * @access private
4593 * @todo Finish documenting this function.
4595 function get_string_from_file($identifier, $langfile, $destination) {
4597 static $strings; // Keep the strings cached in memory.
4599 if (empty($strings[$langfile])) {
4600 $string = array();
4601 include ($langfile);
4602 $strings[$langfile] = $string;
4603 } else {
4604 $string = &$strings[$langfile];
4607 if (!isset ($string[$identifier])) {
4608 return false;
4611 return $destination .'= sprintf("'. $string[$identifier] .'");';
4615 * Converts an array of strings to their localized value.
4617 * @param array $array An array of strings
4618 * @param string $module The language module that these strings can be found in.
4619 * @return string
4621 function get_strings($array, $module='') {
4623 $string = NULL;
4624 foreach ($array as $item) {
4625 $string->$item = get_string($item, $module);
4627 return $string;
4631 * Returns a list of language codes and their full names
4632 * hides the _local files from everyone.
4633 * @param bool refreshcache force refreshing of lang cache
4634 * @param bool returnall ignore langlist, return all languages available
4635 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4637 function get_list_of_languages($refreshcache=false, $returnall=false) {
4639 global $CFG;
4641 $languages = array();
4643 $filetocheck = 'langconfig.php';
4645 if (!$refreshcache && !$returnall && !empty($CFG->langcache) && file_exists($CFG->dataroot .'/cache/languages')) {
4646 /// read available langs from cache
4648 $lines = file($CFG->dataroot .'/cache/languages');
4649 foreach ($lines as $line) {
4650 $line = trim($line);
4651 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4652 $languages[$matches[1]] = $matches[2];
4655 unset($lines); unset($line); unset($matches);
4656 return $languages;
4659 if (!$returnall && !empty($CFG->langlist)) {
4660 /// return only languages allowed in langlist admin setting
4662 $langlist = explode(',', $CFG->langlist);
4663 // fix short lang names first - non existing langs are skipped anyway...
4664 foreach ($langlist as $lang) {
4665 if (strpos($lang, '_utf8') === false) {
4666 $langlist[] = $lang.'_utf8';
4669 // find existing langs from langlist
4670 foreach ($langlist as $lang) {
4671 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4672 if (strstr($lang, '_local')!==false) {
4673 continue;
4675 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4676 $shortlang = substr($lang, 0, -5);
4677 } else {
4678 $shortlang = $lang;
4680 /// Search under dirroot/lang
4681 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4682 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4683 if (!empty($string['thislanguage'])) {
4684 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4686 unset($string);
4688 /// And moodledata/lang
4689 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4690 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4691 if (!empty($string['thislanguage'])) {
4692 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4694 unset($string);
4698 } else {
4699 /// return all languages available in system
4700 /// Fetch langs from moodle/lang directory
4701 $langdirs = get_list_of_plugins('lang');
4702 /// Fetch langs from moodledata/lang directory
4703 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot);
4704 /// Merge both lists of langs
4705 $langdirs = array_merge($langdirs, $langdirs2);
4706 /// Sort all
4707 asort($langdirs);
4708 /// Get some info from each lang (first from moodledata, then from moodle)
4709 foreach ($langdirs as $lang) {
4710 if (strstr($lang, '_local')!==false) {
4711 continue;
4713 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4714 $shortlang = substr($lang, 0, -5);
4715 } else {
4716 $shortlang = $lang;
4718 /// Search under moodledata/lang
4719 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4720 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4721 if (!empty($string['thislanguage'])) {
4722 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4724 unset($string);
4726 /// And dirroot/lang
4727 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4728 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4729 if (!empty($string['thislanguage'])) {
4730 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4732 unset($string);
4737 if ($refreshcache && !empty($CFG->langcache)) {
4738 if ($returnall) {
4739 // we have a list of all langs only, just delete old cache
4740 @unlink($CFG->dataroot.'/cache/languages');
4742 } else {
4743 // store the list of allowed languages
4744 if ($file = fopen($CFG->dataroot .'/cache/languages', 'w')) {
4745 foreach ($languages as $key => $value) {
4746 fwrite($file, "$key $value\n");
4748 fclose($file);
4753 return $languages;
4757 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4758 * (cheking that such charset is supported by the texlib library!)
4760 * @return array And associative array with contents in the form of charset => charset
4762 function get_list_of_charsets() {
4764 $charsets = array(
4765 'EUC-JP' => 'EUC-JP',
4766 'ISO-2022-JP'=> 'ISO-2022-JP',
4767 'ISO-8859-1' => 'ISO-8859-1',
4768 'SHIFT-JIS' => 'SHIFT-JIS',
4769 'GB2312' => 'GB2312',
4770 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4771 'UTF-8' => 'UTF-8');
4773 asort($charsets);
4775 return $charsets;
4779 * Returns a list of country names in the current language
4781 * @uses $CFG
4782 * @uses $USER
4783 * @return array
4785 function get_list_of_countries() {
4786 global $CFG, $USER;
4788 $lang = current_language();
4790 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php') &&
4791 !file_exists($CFG->dataroot.'/lang/'. $lang .'/countries.php')) {
4792 if ($parentlang = get_string('parentlanguage')) {
4793 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/countries.php') ||
4794 file_exists($CFG->dataroot.'/lang/'. $parentlang .'/countries.php')) {
4795 $lang = $parentlang;
4796 } else {
4797 $lang = 'en_utf8'; // countries.php must exist in this pack
4799 } else {
4800 $lang = 'en_utf8'; // countries.php must exist in this pack
4804 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/countries.php')) {
4805 include($CFG->dataroot .'/lang/'. $lang .'/countries.php');
4806 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
4807 include($CFG->dirroot .'/lang/'. $lang .'/countries.php');
4810 if (!empty($string)) {
4811 asort($string);
4814 return $string;
4818 * Returns a list of valid and compatible themes
4820 * @uses $CFG
4821 * @return array
4823 function get_list_of_themes() {
4825 global $CFG;
4827 $themes = array();
4829 if (!empty($CFG->themelist)) { // use admin's list of themes
4830 $themelist = explode(',', $CFG->themelist);
4831 } else {
4832 $themelist = get_list_of_plugins("theme");
4835 foreach ($themelist as $key => $theme) {
4836 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
4837 continue;
4839 $THEME = new object(); // Note this is not the global one!! :-)
4840 include("$CFG->themedir/$theme/config.php");
4841 if (!isset($THEME->sheets)) { // Not a valid 1.5 theme
4842 continue;
4844 $themes[$theme] = $theme;
4846 asort($themes);
4848 return $themes;
4853 * Returns a list of picture names in the current or specified language
4855 * @uses $CFG
4856 * @return array
4858 function get_list_of_pixnames($lang = '') {
4859 global $CFG;
4861 if (empty($lang)) {
4862 $lang = current_language();
4865 $string = array();
4867 $path = $CFG->dirroot .'/lang/en_utf8/pix.php'; // always exists
4869 if (file_exists($CFG->dataroot .'/lang/'. $lang .'_local/pix.php')) {
4870 $path = $CFG->dataroot .'/lang/'. $lang .'_local/pix.php';
4872 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
4873 $path = $CFG->dirroot .'/lang/'. $lang .'/pix.php';
4875 } else if (file_exists($CFG->dataroot .'/lang/'. $lang .'/pix.php')) {
4876 $path = $CFG->dataroot .'/lang/'. $lang .'/pix.php';
4878 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
4879 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
4882 include($path);
4884 return $string;
4888 * Returns a list of timezones in the current language
4890 * @uses $CFG
4891 * @return array
4893 function get_list_of_timezones() {
4894 global $CFG;
4896 static $timezones;
4898 if (!empty($timezones)) { // This function has been called recently
4899 return $timezones;
4902 $timezones = array();
4904 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix.'timezone GROUP BY name')) {
4905 foreach($rawtimezones as $timezone) {
4906 if (!empty($timezone->name)) {
4907 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
4908 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
4909 $timezones[$timezone->name] = $timezone->name;
4915 asort($timezones);
4917 for ($i = -13; $i <= 13; $i += .5) {
4918 $tzstring = 'GMT';
4919 if ($i < 0) {
4920 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
4921 } else if ($i > 0) {
4922 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
4923 } else {
4924 $timezones[sprintf("%.1f", $i)] = $tzstring;
4928 return $timezones;
4932 * Returns a list of currencies in the current language
4934 * @uses $CFG
4935 * @uses $USER
4936 * @return array
4938 function get_list_of_currencies() {
4939 global $CFG, $USER;
4941 $lang = current_language();
4943 if (!file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
4944 if ($parentlang = get_string('parentlanguage')) {
4945 if (file_exists($CFG->dataroot .'/lang/'. $parentlang .'/currencies.php')) {
4946 $lang = $parentlang;
4947 } else {
4948 $lang = 'en_utf8'; // currencies.php must exist in this pack
4950 } else {
4951 $lang = 'en_utf8'; // currencies.php must exist in this pack
4955 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
4956 include_once($CFG->dataroot .'/lang/'. $lang .'/currencies.php');
4957 } else { //if en_utf8 is not installed in dataroot
4958 include_once($CFG->dirroot .'/lang/'. $lang .'/currencies.php');
4961 if (!empty($string)) {
4962 asort($string);
4965 return $string;
4971 * Can include a given document file (depends on second
4972 * parameter) or just return info about it.
4974 * @uses $CFG
4975 * @param string $file ?
4976 * @param bool $include ?
4977 * @return ?
4978 * @todo Finish documenting this function
4980 function document_file($file, $include=true) {
4981 global $CFG;
4983 $file = clean_filename($file);
4985 if (empty($file)) {
4986 return false;
4989 $langs = array(current_language(), get_string('parentlanguage'), 'en');
4991 foreach ($langs as $lang) {
4992 $info = new object();
4993 $info->filepath = $CFG->dirroot .'/lang/'. $lang .'/docs/'. $file;
4994 $info->urlpath = $CFG->wwwroot .'/lang/'. $lang .'/docs/'. $file;
4996 if (file_exists($info->filepath)) {
4997 if ($include) {
4998 include($info->filepath);
5000 return $info;
5004 return false;
5007 /// ENCRYPTION ////////////////////////////////////////////////
5010 * rc4encrypt
5012 * @param string $data ?
5013 * @return string
5014 * @todo Finish documenting this function
5016 function rc4encrypt($data) {
5017 $password = 'nfgjeingjk';
5018 return endecrypt($password, $data, '');
5022 * rc4decrypt
5024 * @param string $data ?
5025 * @return string
5026 * @todo Finish documenting this function
5028 function rc4decrypt($data) {
5029 $password = 'nfgjeingjk';
5030 return endecrypt($password, $data, 'de');
5034 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5036 * @param string $pwd ?
5037 * @param string $data ?
5038 * @param string $case ?
5039 * @return string
5040 * @todo Finish documenting this function
5042 function endecrypt ($pwd, $data, $case) {
5044 if ($case == 'de') {
5045 $data = urldecode($data);
5048 $key[] = '';
5049 $box[] = '';
5050 $temp_swap = '';
5051 $pwd_length = 0;
5053 $pwd_length = strlen($pwd);
5055 for ($i = 0; $i <= 255; $i++) {
5056 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
5057 $box[$i] = $i;
5060 $x = 0;
5062 for ($i = 0; $i <= 255; $i++) {
5063 $x = ($x + $box[$i] + $key[$i]) % 256;
5064 $temp_swap = $box[$i];
5065 $box[$i] = $box[$x];
5066 $box[$x] = $temp_swap;
5069 $temp = '';
5070 $k = '';
5072 $cipherby = '';
5073 $cipher = '';
5075 $a = 0;
5076 $j = 0;
5078 for ($i = 0; $i < strlen($data); $i++) {
5079 $a = ($a + 1) % 256;
5080 $j = ($j + $box[$a]) % 256;
5081 $temp = $box[$a];
5082 $box[$a] = $box[$j];
5083 $box[$j] = $temp;
5084 $k = $box[(($box[$a] + $box[$j]) % 256)];
5085 $cipherby = ord(substr($data, $i, 1)) ^ $k;
5086 $cipher .= chr($cipherby);
5089 if ($case == 'de') {
5090 $cipher = urldecode(urlencode($cipher));
5091 } else {
5092 $cipher = urlencode($cipher);
5095 return $cipher;
5099 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5103 * Call this function to add an event to the calendar table
5104 * and to call any calendar plugins
5106 * @uses $CFG
5107 * @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:
5108 * <ul>
5109 * <li><b>$event->name</b> - Name for the event
5110 * <li><b>$event->description</b> - Description of the event (defaults to '')
5111 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5112 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5113 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5114 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5115 * <li><b>$event->modulename</b> - Name of the module that creates this event
5116 * <li><b>$event->instance</b> - Instance of the module that owns this event
5117 * <li><b>$event->eventtype</b> - The type info together with the module info could
5118 * be used by calendar plugins to decide how to display event
5119 * <li><b>$event->timestart</b>- Timestamp for start of event
5120 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5121 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5122 * </ul>
5123 * @return int The id number of the resulting record
5125 function add_event($event) {
5127 global $CFG;
5129 $event->timemodified = time();
5131 if (!$event->id = insert_record('event', $event)) {
5132 return false;
5135 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
5136 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5137 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5138 $calendar_add_event = $CFG->calendar.'_add_event';
5139 if (function_exists($calendar_add_event)) {
5140 $calendar_add_event($event);
5145 return $event->id;
5149 * Call this function to update an event in the calendar table
5150 * the event will be identified by the id field of the $event object.
5152 * @uses $CFG
5153 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5154 * @return bool
5156 function update_event($event) {
5158 global $CFG;
5160 $event->timemodified = time();
5162 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5163 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5164 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5165 $calendar_update_event = $CFG->calendar.'_update_event';
5166 if (function_exists($calendar_update_event)) {
5167 $calendar_update_event($event);
5171 return update_record('event', $event);
5175 * Call this function to delete the event with id $id from calendar table.
5177 * @uses $CFG
5178 * @param int $id The id of an event from the 'calendar' table.
5179 * @return array An associative array with the results from the SQL call.
5180 * @todo Verify return type
5182 function delete_event($id) {
5184 global $CFG;
5186 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
5187 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5188 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5189 $calendar_delete_event = $CFG->calendar.'_delete_event';
5190 if (function_exists($calendar_delete_event)) {
5191 $calendar_delete_event($id);
5195 return delete_records('event', 'id', $id);
5199 * Call this function to hide an event in the calendar table
5200 * the event will be identified by the id field of the $event object.
5202 * @uses $CFG
5203 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5204 * @return array An associative array with the results from the SQL call.
5205 * @todo Verify return type
5207 function hide_event($event) {
5208 global $CFG;
5210 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5211 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5212 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5213 $calendar_hide_event = $CFG->calendar.'_hide_event';
5214 if (function_exists($calendar_hide_event)) {
5215 $calendar_hide_event($event);
5219 return set_field('event', 'visible', 0, 'id', $event->id);
5223 * Call this function to unhide an event in the calendar table
5224 * the event will be identified by the id field of the $event object.
5226 * @uses $CFG
5227 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5228 * @return array An associative array with the results from the SQL call.
5229 * @todo Verify return type
5231 function show_event($event) {
5232 global $CFG;
5234 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5235 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5236 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5237 $calendar_show_event = $CFG->calendar.'_show_event';
5238 if (function_exists($calendar_show_event)) {
5239 $calendar_show_event($event);
5243 return set_field('event', 'visible', 1, 'id', $event->id);
5247 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5250 * Lists plugin directories within some directory
5252 * @uses $CFG
5253 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5254 * @param string $exclude dir name to exclude from the list (defaults to none)
5255 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5256 * @return array of plugins found under the requested parameters
5258 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5260 global $CFG;
5262 $plugins = array();
5264 if (empty($basedir)) {
5266 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5267 switch ($plugin) {
5268 case "theme":
5269 $basedir = $CFG->themedir;
5270 break;
5272 default:
5273 $basedir = $CFG->dirroot .'/'. $plugin;
5276 } else {
5277 $basedir = $basedir .'/'. $plugin;
5280 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5281 $dirhandle = opendir($basedir);
5282 while (false !== ($dir = readdir($dirhandle))) {
5283 $firstchar = substr($dir, 0, 1);
5284 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5285 continue;
5287 if (filetype($basedir .'/'. $dir) != 'dir') {
5288 continue;
5290 $plugins[] = $dir;
5292 closedir($dirhandle);
5294 if ($plugins) {
5295 asort($plugins);
5297 return $plugins;
5301 * Returns true if the current version of PHP is greater that the specified one.
5303 * @param string $version The version of php being tested.
5304 * @return bool
5306 function check_php_version($version='4.1.0') {
5307 return (version_compare(phpversion(), $version) >= 0);
5312 * Checks to see if is a browser matches the specified
5313 * brand and is equal or better version.
5315 * @uses $_SERVER
5316 * @param string $brand The browser identifier being tested
5317 * @param int $version The version of the browser
5318 * @return bool true if the given version is below that of the detected browser
5320 function check_browser_version($brand='MSIE', $version=5.5) {
5321 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5322 return false;
5325 $agent = $_SERVER['HTTP_USER_AGENT'];
5327 switch ($brand) {
5329 case 'Camino': /// Mozilla Firefox browsers
5331 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5332 if (version_compare($match[1], $version) >= 0) {
5333 return true;
5336 break;
5339 case 'Firefox': /// Mozilla Firefox browsers
5341 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5342 if (version_compare($match[1], $version) >= 0) {
5343 return true;
5346 break;
5349 case 'Gecko': /// Gecko based browsers
5351 if (substr_count($agent, 'Camino')) {
5352 // MacOS X Camino support
5353 $version = 20041110;
5356 // the proper string - Gecko/CCYYMMDD Vendor/Version
5357 // Faster version and work-a-round No IDN problem.
5358 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5359 if ($match[1] > $version) {
5360 return true;
5363 break;
5366 case 'MSIE': /// Internet Explorer
5368 if (strpos($agent, 'Opera')) { // Reject Opera
5369 return false;
5371 $string = explode(';', $agent);
5372 if (!isset($string[1])) {
5373 return false;
5375 $string = explode(' ', trim($string[1]));
5376 if (!isset($string[0]) and !isset($string[1])) {
5377 return false;
5379 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5380 return true;
5382 break;
5384 case 'Opera': /// Opera
5386 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5387 if (version_compare($match[1], $version) >= 0) {
5388 return true;
5391 break;
5393 case 'Safari': /// Safari
5394 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5395 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5396 return false;
5397 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5398 return false;
5399 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5400 return false;
5403 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5404 if (version_compare($match[1], $version) >= 0) {
5405 return true;
5409 break;
5413 return false;
5417 * This function makes the return value of ini_get consistent if you are
5418 * setting server directives through the .htaccess file in apache.
5419 * Current behavior for value set from php.ini On = 1, Off = [blank]
5420 * Current behavior for value set from .htaccess On = On, Off = Off
5421 * Contributed by jdell @ unr.edu
5423 * @param string $ini_get_arg ?
5424 * @return bool
5425 * @todo Finish documenting this function
5427 function ini_get_bool($ini_get_arg) {
5428 $temp = ini_get($ini_get_arg);
5430 if ($temp == '1' or strtolower($temp) == 'on') {
5431 return true;
5433 return false;
5437 * Compatibility stub to provide backward compatibility
5439 * Determines if the HTML editor is enabled.
5440 * @deprecated Use {@link can_use_html_editor()} instead.
5442 function can_use_richtext_editor() {
5443 return can_use_html_editor();
5447 * Determines if the HTML editor is enabled.
5449 * This depends on site and user
5450 * settings, as well as the current browser being used.
5452 * @return string|false Returns false if editor is not being used, otherwise
5453 * returns 'MSIE' or 'Gecko'.
5455 function can_use_html_editor() {
5456 global $USER, $CFG;
5458 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
5459 if (check_browser_version('MSIE', 5.5)) {
5460 return 'MSIE';
5461 } else if (check_browser_version('Gecko', 20030516)) {
5462 return 'Gecko';
5465 return false;
5469 * Hack to find out the GD version by parsing phpinfo output
5471 * @return int GD version (1, 2, or 0)
5473 function check_gd_version() {
5474 $gdversion = 0;
5476 if (function_exists('gd_info')){
5477 $gd_info = gd_info();
5478 if (substr_count($gd_info['GD Version'], '2.')) {
5479 $gdversion = 2;
5480 } else if (substr_count($gd_info['GD Version'], '1.')) {
5481 $gdversion = 1;
5484 } else {
5485 ob_start();
5486 phpinfo(8);
5487 $phpinfo = ob_get_contents();
5488 ob_end_clean();
5490 $phpinfo = explode("\n", $phpinfo);
5493 foreach ($phpinfo as $text) {
5494 $parts = explode('</td>', $text);
5495 foreach ($parts as $key => $val) {
5496 $parts[$key] = trim(strip_tags($val));
5498 if ($parts[0] == 'GD Version') {
5499 if (substr_count($parts[1], '2.0')) {
5500 $parts[1] = '2.0';
5502 $gdversion = intval($parts[1]);
5507 return $gdversion; // 1, 2 or 0
5511 * Determine if moodle installation requires update
5513 * Checks version numbers of main code and all modules to see
5514 * if there are any mismatches
5516 * @uses $CFG
5517 * @return bool
5519 function moodle_needs_upgrading() {
5520 global $CFG;
5522 $version = null;
5523 include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
5524 if ($CFG->version) {
5525 if ($version > $CFG->version) {
5526 return true;
5528 if ($mods = get_list_of_plugins('mod')) {
5529 foreach ($mods as $mod) {
5530 $fullmod = $CFG->dirroot .'/mod/'. $mod;
5531 $module = new object();
5532 if (!is_readable($fullmod .'/version.php')) {
5533 notify('Module "'. $mod .'" is not readable - check permissions');
5534 continue;
5536 include_once($fullmod .'/version.php'); # defines $module with version etc
5537 if ($currmodule = get_record('modules', 'name', $mod)) {
5538 if ($module->version > $currmodule->version) {
5539 return true;
5544 } else {
5545 return true;
5547 return false;
5551 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5554 * Notify admin users or admin user of any failed logins (since last notification).
5556 * @uses $CFG
5557 * @uses $db
5558 * @uses HOURSECS
5560 function notify_login_failures() {
5561 global $CFG, $db;
5563 switch ($CFG->notifyloginfailures) {
5564 case 'mainadmin' :
5565 $recip = array(get_admin());
5566 break;
5567 case 'alladmins':
5568 $recip = get_admins();
5569 break;
5572 if (empty($CFG->lastnotifyfailure)) {
5573 $CFG->lastnotifyfailure=0;
5576 // we need to deal with the threshold stuff first.
5577 if (empty($CFG->notifyloginthreshold)) {
5578 $CFG->notifyloginthreshold = 10; // default to something sensible.
5581 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5582 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold);
5584 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5585 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold);
5587 if ($notifyipsrs) {
5588 $ipstr = '';
5589 while ($row = rs_fetch_next_record($notifyipsrs)) {
5590 $ipstr .= "'". $row->ip ."',";
5592 rs_close($notifyipsrs);
5593 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5595 if ($notifyusersrs) {
5596 $userstr = '';
5597 while ($row = rs_fetch_next_record($notifyusersrs)) {
5598 $userstr .= "'". $row->info ."',";
5600 rs_close($notifyusersrs);
5601 $userstr = substr($userstr,0,strlen($userstr)-1);
5604 if (strlen($userstr) > 0 || strlen($ipstr) > 0) {
5605 $count = 0;
5606 $logs = get_logs('time > '. $CFG->lastnotifyfailure .' AND module=\'login\' AND action=\'error\' '
5607 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ? ' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5608 : ((strlen($ipstr) != 0) ? ' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5610 // 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
5611 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS) > $CFG->lastnotifyfailure)
5612 and is_array($logs) and count($logs) > 0) {
5614 $message = '';
5615 $site = get_site();
5616 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
5617 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot)
5618 .(($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n";
5619 foreach ($logs as $log) {
5620 $log->time = userdate($log->time);
5621 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5623 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
5624 foreach ($recip as $admin) {
5625 mtrace('Emailing '. $admin->username .' about '. count($logs) .' failed login attempts');
5626 email_to_user($admin,get_admin(),$subject,$message);
5628 $conf = new object();
5629 $conf->name = 'lastnotifyfailure';
5630 $conf->value = time();
5631 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5632 $conf->id = $current->id;
5633 if (! update_record('config', $conf)) {
5634 mtrace('Could not update last notify time');
5637 } else if (! insert_record('config', $conf)) {
5638 mtrace('Could not set last notify time');
5645 * moodle_setlocale
5647 * @uses $CFG
5648 * @param string $locale ?
5649 * @todo Finish documenting this function
5651 function moodle_setlocale($locale='') {
5653 global $CFG;
5655 static $currentlocale = ''; // last locale caching
5657 $oldlocale = $currentlocale;
5659 /// Fetch the correct locale based on ostype
5660 if($CFG->ostype == 'WINDOWS') {
5661 $stringtofetch = 'localewin';
5662 } else {
5663 $stringtofetch = 'locale';
5666 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5667 if (!empty($locale)) {
5668 $currentlocale = $locale;
5669 } else if (!empty($CFG->locale)) { // override locale for all language packs
5670 $currentlocale = $CFG->locale;
5671 } else {
5672 $currentlocale = get_string($stringtofetch);
5675 /// do nothing if locale already set up
5676 if ($oldlocale == $currentlocale) {
5677 return;
5680 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5681 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5682 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5684 /// Get current values
5685 $monetary= setlocale (LC_MONETARY, 0);
5686 $numeric = setlocale (LC_NUMERIC, 0);
5687 $ctype = setlocale (LC_CTYPE, 0);
5688 if ($CFG->ostype != 'WINDOWS') {
5689 $messages= setlocale (LC_MESSAGES, 0);
5691 /// Set locale to all
5692 setlocale (LC_ALL, $currentlocale);
5693 /// Set old values
5694 setlocale (LC_MONETARY, $monetary);
5695 setlocale (LC_NUMERIC, $numeric);
5696 if ($CFG->ostype != 'WINDOWS') {
5697 setlocale (LC_MESSAGES, $messages);
5699 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5700 setlocale (LC_CTYPE, $ctype);
5705 * Converts string to lowercase using most compatible function available.
5707 * @param string $string The string to convert to all lowercase characters.
5708 * @param string $encoding The encoding on the string.
5709 * @return string
5710 * @todo Add examples of calling this function with/without encoding types
5711 * @deprecated Use textlib->strtolower($text) instead.
5713 function moodle_strtolower ($string, $encoding='') {
5715 //If not specified use utf8
5716 if (empty($encoding)) {
5717 $encoding = 'UTF-8';
5719 //Use text services
5720 $textlib = textlib_get_instance();
5722 return $textlib->strtolower($string, $encoding);
5726 * Count words in a string.
5728 * Words are defined as things between whitespace.
5730 * @param string $string The text to be searched for words.
5731 * @return int The count of words in the specified string
5733 function count_words($string) {
5734 $string = strip_tags($string);
5735 return count(preg_split("/\w\b/", $string)) - 1;
5738 /** Count letters in a string.
5740 * Letters are defined as chars not in tags and different from whitespace.
5742 * @param string $string The text to be searched for letters.
5743 * @return int The count of letters in the specified text.
5745 function count_letters($string) {
5746 /// Loading the textlib singleton instance. We are going to need it.
5747 $textlib = textlib_get_instance();
5749 $string = strip_tags($string); // Tags are out now
5750 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5752 return $textlib->strlen($string);
5756 * Generate and return a random string of the specified length.
5758 * @param int $length The length of the string to be created.
5759 * @return string
5761 function random_string ($length=15) {
5762 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5763 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5764 $pool .= '0123456789';
5765 $poollen = strlen($pool);
5766 mt_srand ((double) microtime() * 1000000);
5767 $string = '';
5768 for ($i = 0; $i < $length; $i++) {
5769 $string .= substr($pool, (mt_rand()%($poollen)), 1);
5771 return $string;
5775 * Given some text (which may contain HTML) and an ideal length,
5776 * this function truncates the text neatly on a word boundary if possible
5778 function shorten_text($text, $ideal=30) {
5780 global $CFG;
5783 $i = 0;
5784 $tag = false;
5785 $length = strlen($text);
5786 $count = 0;
5787 $stopzone = false;
5788 $truncate = 0;
5790 if ($length <= $ideal) {
5791 return $text;
5794 for ($i=0; $i<$length; $i++) {
5795 $char = $text[$i];
5797 switch ($char) {
5798 case "<":
5799 $tag = true;
5800 break;
5801 case ">":
5802 $tag = false;
5803 break;
5804 default:
5805 if (!$tag) {
5806 if ($stopzone) {
5807 if ($char == '.' or $char == ' ') {
5808 $truncate = $i+1;
5809 break 2;
5810 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5811 $truncate = $i; // can be truncated at any UTF-8
5812 break 2; // character boundary.
5815 $count++;
5817 break;
5819 if (!$stopzone) {
5820 if ($count > $ideal) {
5821 $stopzone = true;
5826 if (!$truncate) {
5827 $truncate = $i;
5830 $ellipse = ($truncate < $length) ? '...' : '';
5832 return substr($text, 0, $truncate).$ellipse;
5837 * Given dates in seconds, how many weeks is the date from startdate
5838 * The first week is 1, the second 2 etc ...
5840 * @uses WEEKSECS
5841 * @param ? $startdate ?
5842 * @param ? $thedate ?
5843 * @return string
5844 * @todo Finish documenting this function
5846 function getweek ($startdate, $thedate) {
5847 if ($thedate < $startdate) { // error
5848 return 0;
5851 return floor(($thedate - $startdate) / WEEKSECS) + 1;
5855 * returns a randomly generated password of length $maxlen. inspired by
5856 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
5858 * @param int $maxlength The maximum size of the password being generated.
5859 * @return string
5861 function generate_password($maxlen=10) {
5862 global $CFG;
5864 $fillers = '1234567890!$-+';
5865 $wordlist = file($CFG->wordlist);
5867 srand((double) microtime() * 1000000);
5868 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5869 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5870 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
5872 return substr($word1 . $filler1 . $word2, 0, $maxlen);
5876 * Given a float, prints it nicely.
5877 * Do NOT use the result in any calculation later!
5879 * @param float $flaot The float to print
5880 * @param int $places The number of decimal places to print.
5881 * @return string locale float
5883 function format_float($float, $decimalpoints=1) {
5884 if (is_null($float)) {
5885 return '';
5887 return number_format($float, $decimalpoints, get_string('decsep'), '');
5891 * Converts locale specific floating point/comma number back to standard PHP float value
5892 * Do NOT try to do any math operations before this conversion on any user submitted floats!
5894 * @param string $locale_float locale aware float representation
5896 function unformat_float($locale_float) {
5897 $locale_float = trim($locale_float);
5899 if ($locale_float == '') {
5900 return null;
5903 $locale_float = str_replace(' ', '', $locale_float); // no spaces - those might be used as thousand separators
5905 return (float)str_replace(get_string('decsep'), '.', $locale_float);
5909 * Given a simple array, this shuffles it up just like shuffle()
5910 * Unlike PHP's shuffle() this function works on any machine.
5912 * @param array $array The array to be rearranged
5913 * @return array
5915 function swapshuffle($array) {
5917 srand ((double) microtime() * 10000000);
5918 $last = count($array) - 1;
5919 for ($i=0;$i<=$last;$i++) {
5920 $from = rand(0,$last);
5921 $curr = $array[$i];
5922 $array[$i] = $array[$from];
5923 $array[$from] = $curr;
5925 return $array;
5929 * Like {@link swapshuffle()}, but works on associative arrays
5931 * @param array $array The associative array to be rearranged
5932 * @return array
5934 function swapshuffle_assoc($array) {
5937 $newkeys = swapshuffle(array_keys($array));
5938 foreach ($newkeys as $newkey) {
5939 $newarray[$newkey] = $array[$newkey];
5941 return $newarray;
5945 * Given an arbitrary array, and a number of draws,
5946 * this function returns an array with that amount
5947 * of items. The indexes are retained.
5949 * @param array $array ?
5950 * @param ? $draws ?
5951 * @return ?
5952 * @todo Finish documenting this function
5954 function draw_rand_array($array, $draws) {
5955 srand ((double) microtime() * 10000000);
5957 $return = array();
5959 $last = count($array);
5961 if ($draws > $last) {
5962 $draws = $last;
5965 while ($draws > 0) {
5966 $last--;
5968 $keys = array_keys($array);
5969 $rand = rand(0, $last);
5971 $return[$keys[$rand]] = $array[$keys[$rand]];
5972 unset($array[$keys[$rand]]);
5974 $draws--;
5977 return $return;
5981 * microtime_diff
5983 * @param string $a ?
5984 * @param string $b ?
5985 * @return string
5986 * @todo Finish documenting this function
5988 function microtime_diff($a, $b) {
5989 list($a_dec, $a_sec) = explode(' ', $a);
5990 list($b_dec, $b_sec) = explode(' ', $b);
5991 return $b_sec - $a_sec + $b_dec - $a_dec;
5995 * Given a list (eg a,b,c,d,e) this function returns
5996 * an array of 1->a, 2->b, 3->c etc
5998 * @param array $list ?
5999 * @param string $separator ?
6000 * @todo Finish documenting this function
6002 function make_menu_from_list($list, $separator=',') {
6004 $array = array_reverse(explode($separator, $list), true);
6005 foreach ($array as $key => $item) {
6006 $outarray[$key+1] = trim($item);
6008 return $outarray;
6012 * Creates an array that represents all the current grades that
6013 * can be chosen using the given grading type. Negative numbers
6014 * are scales, zero is no grade, and positive numbers are maximum
6015 * grades.
6017 * @param int $gradingtype ?
6018 * return int
6019 * @todo Finish documenting this function
6021 function make_grades_menu($gradingtype) {
6022 $grades = array();
6023 if ($gradingtype < 0) {
6024 if ($scale = get_record('scale', 'id', - $gradingtype)) {
6025 return make_menu_from_list($scale->scale);
6027 } else if ($gradingtype > 0) {
6028 for ($i=$gradingtype; $i>=0; $i--) {
6029 $grades[$i] = $i .' / '. $gradingtype;
6031 return $grades;
6033 return $grades;
6037 * This function returns the nummber of activities
6038 * using scaleid in a courseid
6040 * @param int $courseid ?
6041 * @param int $scaleid ?
6042 * @return int
6043 * @todo Finish documenting this function
6045 function course_scale_used($courseid, $scaleid) {
6047 global $CFG;
6049 $return = 0;
6051 if (!empty($scaleid)) {
6052 if ($cms = get_course_mods($courseid)) {
6053 foreach ($cms as $cm) {
6054 //Check cm->name/lib.php exists
6055 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
6056 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
6057 $function_name = $cm->modname.'_scale_used';
6058 if (function_exists($function_name)) {
6059 if ($function_name($cm->instance,$scaleid)) {
6060 $return++;
6067 // check if any course grade item makes use of the scale
6068 $return += count_records('grade_items', 'courseid', $courseid, 'scaleid', $scaleid);
6070 return $return;
6074 * This function returns the nummber of activities
6075 * using scaleid in the entire site
6077 * @param int $scaleid ?
6078 * @return int
6079 * @todo Finish documenting this function. Is return type correct?
6081 function site_scale_used($scaleid,&$courses) {
6083 global $CFG;
6085 $return = 0;
6087 if (!is_array($courses) || count($courses) == 0) {
6088 $courses = get_courses("all",false,"c.id,c.shortname");
6091 if (!empty($scaleid)) {
6092 if (is_array($courses) && count($courses) > 0) {
6093 foreach ($courses as $course) {
6094 $return += course_scale_used($course->id,$scaleid);
6098 return $return;
6102 * make_unique_id_code
6104 * @param string $extra ?
6105 * @return string
6106 * @todo Finish documenting this function
6108 function make_unique_id_code($extra='') {
6110 $hostname = 'unknownhost';
6111 if (!empty($_SERVER['HTTP_HOST'])) {
6112 $hostname = $_SERVER['HTTP_HOST'];
6113 } else if (!empty($_ENV['HTTP_HOST'])) {
6114 $hostname = $_ENV['HTTP_HOST'];
6115 } else if (!empty($_SERVER['SERVER_NAME'])) {
6116 $hostname = $_SERVER['SERVER_NAME'];
6117 } else if (!empty($_ENV['SERVER_NAME'])) {
6118 $hostname = $_ENV['SERVER_NAME'];
6121 $date = gmdate("ymdHis");
6123 $random = random_string(6);
6125 if ($extra) {
6126 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6127 } else {
6128 return $hostname .'+'. $date .'+'. $random;
6134 * Function to check the passed address is within the passed subnet
6136 * The parameter is a comma separated string of subnet definitions.
6137 * Subnet strings can be in one of three formats:
6138 * 1: xxx.xxx.xxx.xxx/xx
6139 * 2: xxx.xxx
6140 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
6141 * Code for type 1 modified from user posted comments by mediator at
6142 * {@link http://au.php.net/manual/en/function.ip2long.php}
6144 * @param string $addr The address you are checking
6145 * @param string $subnetstr The string of subnet addresses
6146 * @return bool
6148 function address_in_subnet($addr, $subnetstr) {
6150 $subnets = explode(',', $subnetstr);
6151 $found = false;
6152 $addr = trim($addr);
6154 foreach ($subnets as $subnet) {
6155 $subnet = trim($subnet);
6156 if (strpos($subnet, '/') !== false) { /// type 1
6157 list($ip, $mask) = explode('/', $subnet);
6158 $mask = 0xffffffff << (32 - $mask);
6159 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
6160 } else if (strpos($subnet, '-') !== false) {/// type 3
6161 $subnetparts = explode('.', $subnet);
6162 $addrparts = explode('.', $addr);
6163 $subnetrange = explode('-', array_pop($subnetparts));
6164 if (count($subnetrange) == 2) {
6165 $lastaddrpart = array_pop($addrparts);
6166 $found = ($subnetparts == $addrparts &&
6167 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
6169 } else { /// type 2
6170 $found = (strpos($addr, $subnet) === 0);
6173 if ($found) {
6174 break;
6177 return $found;
6181 * This function sets the $HTTPSPAGEREQUIRED global
6182 * (used in some parts of moodle to change some links)
6183 * and calculate the proper wwwroot to be used
6185 * By using this function properly, we can ensure 100% https-ized pages
6186 * at our entire discretion (login, forgot_password, change_password)
6188 function httpsrequired() {
6190 global $CFG, $HTTPSPAGEREQUIRED;
6192 if (!empty($CFG->loginhttps)) {
6193 $HTTPSPAGEREQUIRED = true;
6194 $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
6195 $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
6197 // change theme URLs to https
6198 theme_setup();
6200 } else {
6201 $CFG->httpswwwroot = $CFG->wwwroot;
6202 $CFG->httpsthemewww = $CFG->themewww;
6207 * For outputting debugging info
6209 * @uses STDOUT
6210 * @param string $string ?
6211 * @param string $eol ?
6212 * @todo Finish documenting this function
6214 function mtrace($string, $eol="\n", $sleep=0) {
6216 if (defined('STDOUT')) {
6217 fwrite(STDOUT, $string.$eol);
6218 } else {
6219 echo $string . $eol;
6222 flush();
6224 //delay to keep message on user's screen in case of subsequent redirect
6225 if ($sleep) {
6226 sleep($sleep);
6230 //Replace 1 or more slashes or backslashes to 1 slash
6231 function cleardoubleslashes ($path) {
6232 return preg_replace('/(\/|\\\){1,}/','/',$path);
6235 function zip_files ($originalfiles, $destination) {
6236 //Zip an array of files/dirs to a destination zip file
6237 //Both parameters must be FULL paths to the files/dirs
6239 global $CFG;
6241 //Extract everything from destination
6242 $path_parts = pathinfo(cleardoubleslashes($destination));
6243 $destpath = $path_parts["dirname"]; //The path of the zip file
6244 $destfilename = $path_parts["basename"]; //The name of the zip file
6245 $extension = $path_parts["extension"]; //The extension of the file
6247 //If no file, error
6248 if (empty($destfilename)) {
6249 return false;
6252 //If no extension, add it
6253 if (empty($extension)) {
6254 $extension = 'zip';
6255 $destfilename = $destfilename.'.'.$extension;
6258 //Check destination path exists
6259 if (!is_dir($destpath)) {
6260 return false;
6263 //Check destination path is writable. TODO!!
6265 //Clean destination filename
6266 $destfilename = clean_filename($destfilename);
6268 //Now check and prepare every file
6269 $files = array();
6270 $origpath = NULL;
6272 foreach ($originalfiles as $file) { //Iterate over each file
6273 //Check for every file
6274 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6275 //Calculate the base path for all files if it isn't set
6276 if ($origpath === NULL) {
6277 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6279 //See if the file is readable
6280 if (!is_readable($tempfile)) { //Is readable
6281 continue;
6283 //See if the file/dir is in the same directory than the rest
6284 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6285 continue;
6287 //Add the file to the array
6288 $files[] = $tempfile;
6291 //Everything is ready:
6292 // -$origpath is the path where ALL the files to be compressed reside (dir).
6293 // -$destpath is the destination path where the zip file will go (dir).
6294 // -$files is an array of files/dirs to compress (fullpath)
6295 // -$destfilename is the name of the zip file (without path)
6297 //print_object($files); //Debug
6299 if (empty($CFG->zip)) { // Use built-in php-based zip function
6301 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6302 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6303 $zipfiles = array();
6304 $start = strlen($origpath)+1;
6305 foreach($files as $file) {
6306 $tf = array();
6307 $tf[PCLZIP_ATT_FILE_NAME] = $file;
6308 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME] = substr($file, $start);
6309 $zipfiles[] = $tf;
6311 //create the archive
6312 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6313 if (($list = $archive->create($zipfiles) == 0)) {
6314 notice($archive->errorInfo(true));
6315 return false;
6318 } else { // Use external zip program
6320 $filestozip = "";
6321 foreach ($files as $filetozip) {
6322 $filestozip .= escapeshellarg(basename($filetozip));
6323 $filestozip .= " ";
6325 //Construct the command
6326 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6327 $command = 'cd '.escapeshellarg($origpath).$separator.
6328 escapeshellarg($CFG->zip).' -r '.
6329 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6330 //All converted to backslashes in WIN
6331 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6332 $command = str_replace('/','\\',$command);
6334 Exec($command);
6336 return true;
6339 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6340 //Unzip one zip file to a destination dir
6341 //Both parameters must be FULL paths
6342 //If destination isn't specified, it will be the
6343 //SAME directory where the zip file resides.
6345 global $CFG;
6347 //Extract everything from zipfile
6348 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6349 $zippath = $path_parts["dirname"]; //The path of the zip file
6350 $zipfilename = $path_parts["basename"]; //The name of the zip file
6351 $extension = $path_parts["extension"]; //The extension of the file
6353 //If no file, error
6354 if (empty($zipfilename)) {
6355 return false;
6358 //If no extension, error
6359 if (empty($extension)) {
6360 return false;
6363 //Clear $zipfile
6364 $zipfile = cleardoubleslashes($zipfile);
6366 //Check zipfile exists
6367 if (!file_exists($zipfile)) {
6368 return false;
6371 //If no destination, passed let's go with the same directory
6372 if (empty($destination)) {
6373 $destination = $zippath;
6376 //Clear $destination
6377 $destpath = rtrim(cleardoubleslashes($destination), "/");
6379 //Check destination path exists
6380 if (!is_dir($destpath)) {
6381 return false;
6384 //Check destination path is writable. TODO!!
6386 //Everything is ready:
6387 // -$zippath is the path where the zip file resides (dir)
6388 // -$zipfilename is the name of the zip file (without path)
6389 // -$destpath is the destination path where the zip file will uncompressed (dir)
6391 $list = null;
6393 if (empty($CFG->unzip)) { // Use built-in php-based unzip function
6395 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6396 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6397 if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
6398 PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename',
6399 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $destpath)) {
6400 notice($archive->errorInfo(true));
6401 return false;
6404 } else { // Use external unzip program
6406 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6407 $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
6409 $command = 'cd '.escapeshellarg($zippath).$separator.
6410 escapeshellarg($CFG->unzip).' -o '.
6411 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6412 escapeshellarg($destpath).$redirection;
6413 //All converted to backslashes in WIN
6414 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6415 $command = str_replace('/','\\',$command);
6417 Exec($command,$list);
6420 //Display some info about the unzip execution
6421 if ($showstatus) {
6422 unzip_show_status($list,$destpath);
6425 return true;
6428 function unzip_cleanfilename ($p_event, &$p_header) {
6429 //This function is used as callback in unzip_file() function
6430 //to clean illegal characters for given platform and to prevent directory traversal.
6431 //Produces the same result as info-zip unzip.
6432 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6433 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6434 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6435 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6436 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6437 } else {
6438 //Add filtering for other systems here
6439 // BSD: none (tested)
6440 // Linux: ??
6441 // MacosX: ??
6443 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6444 return 1;
6447 function unzip_show_status ($list,$removepath) {
6448 //This function shows the results of the unzip execution
6449 //depending of the value of the $CFG->zip, results will be
6450 //text or an array of files.
6452 global $CFG;
6454 if (empty($CFG->unzip)) { // Use built-in php-based zip function
6455 $strname = get_string("name");
6456 $strsize = get_string("size");
6457 $strmodified = get_string("modified");
6458 $strstatus = get_string("status");
6459 echo "<table width=\"640\">";
6460 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6461 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6462 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6463 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6464 foreach ($list as $item) {
6465 echo "<tr>";
6466 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6467 print_cell("left", s($item['filename']));
6468 if (! $item['folder']) {
6469 print_cell("right", display_size($item['size']));
6470 } else {
6471 echo "<td>&nbsp;</td>";
6473 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6474 print_cell("right", $filedate);
6475 print_cell("right", $item['status']);
6476 echo "</tr>";
6478 echo "</table>";
6480 } else { // Use external zip program
6481 print_simple_box_start("center");
6482 echo "<pre>";
6483 foreach ($list as $item) {
6484 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6486 echo "</pre>";
6487 print_simple_box_end();
6492 * Returns most reliable client address
6494 * @return string The remote IP address
6496 function getremoteaddr() {
6497 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6498 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6500 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6501 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6503 if (!empty($_SERVER['REMOTE_ADDR'])) {
6504 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6506 return '';
6510 * Cleans a remote address ready to put into the log table
6512 function cleanremoteaddr($addr) {
6513 $originaladdr = $addr;
6514 $matches = array();
6515 // first get all things that look like IP addresses.
6516 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER)) {
6517 return '';
6519 $goodmatches = array();
6520 $lanmatches = array();
6521 foreach ($matches as $match) {
6522 // print_r($match);
6523 // check to make sure it's not an internal address.
6524 // the following are reserved for private lans...
6525 // 10.0.0.0 - 10.255.255.255
6526 // 172.16.0.0 - 172.31.255.255
6527 // 192.168.0.0 - 192.168.255.255
6528 // 169.254.0.0 -169.254.255.255
6529 $bits = explode('.',$match[0]);
6530 if (count($bits) != 4) {
6531 // weird, preg match shouldn't give us it.
6532 continue;
6534 if (($bits[0] == 10)
6535 || ($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6536 || ($bits[0] == 192 && $bits[1] == 168)
6537 || ($bits[0] == 169 && $bits[1] == 254)) {
6538 $lanmatches[] = $match[0];
6539 continue;
6541 // finally, it's ok
6542 $goodmatches[] = $match[0];
6544 if (!count($goodmatches)) {
6545 // perhaps we have a lan match, it's probably better to return that.
6546 if (!count($lanmatches)) {
6547 return '';
6548 } else {
6549 return array_pop($lanmatches);
6552 if (count($goodmatches) == 1) {
6553 return $goodmatches[0];
6555 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6556 // we need to return something, so
6557 return array_pop($goodmatches);
6561 * file_put_contents is only supported by php 5.0 and higher
6562 * so if it is not predefined, define it here
6564 * @param $file full path of the file to write
6565 * @param $contents contents to be sent
6566 * @return number of bytes written (false on error)
6568 if(!function_exists('file_put_contents')) {
6569 function file_put_contents($file, $contents) {
6570 $result = false;
6571 if ($f = fopen($file, 'w')) {
6572 $result = fwrite($f, $contents);
6573 fclose($f);
6575 return $result;
6580 * The clone keyword is only supported from PHP 5 onwards.
6581 * The behaviour of $obj2 = $obj1 differs fundamentally
6582 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6583 * created, in PHP 5 $obj1 is referenced. To create a copy
6584 * in PHP 5 the clone keyword was introduced. This function
6585 * simulates this behaviour for PHP < 5.0.0.
6586 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6588 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6589 * Found a better implementation (more checks and possibilities) from PEAR:
6590 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6592 * @param object $obj
6593 * @return object
6595 if(!check_php_version('5.0.0')) {
6596 // the eval is needed to prevent PHP 5 from getting a parse error!
6597 eval('
6598 function clone($obj) {
6599 /// Sanity check
6600 if (!is_object($obj)) {
6601 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6602 return;
6605 /// Use serialize/unserialize trick to deep copy the object
6606 $obj = unserialize(serialize($obj));
6608 /// If there is a __clone method call it on the "new" class
6609 if (method_exists($obj, \'__clone\')) {
6610 $obj->__clone();
6613 return $obj;
6616 // Supply the PHP5 function scandir() to older versions.
6617 function scandir($directory) {
6618 $files = array();
6619 if ($dh = opendir($directory)) {
6620 while (($file = readdir($dh)) !== false) {
6621 $files[] = $file;
6623 closedir($dh);
6625 return $files;
6628 // Supply the PHP5 function array_combine() to older versions.
6629 function array_combine($keys, $values) {
6630 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6631 return false;
6633 reset($values);
6634 $result = array();
6635 foreach ($keys as $key) {
6636 $result[$key] = current($values);
6637 next($values);
6639 return $result;
6645 * This function will make a complete copy of anything it's given,
6646 * regardless of whether it's an object or not.
6647 * @param mixed $thing
6648 * @return mixed
6650 function fullclone($thing) {
6651 return unserialize(serialize($thing));
6656 * This function expects to called during shutdown
6657 * should be set via register_shutdown_function()
6658 * in lib/setup.php .
6660 * Right now we do it only if we are under apache, to
6661 * make sure apache children that hog too much mem are
6662 * killed.
6665 function moodle_request_shutdown() {
6667 global $CFG;
6669 // initially, we are only ever called under apache
6670 // but check just in case
6671 if (function_exists('apache_child_terminate')
6672 && function_exists('memory_get_usage')
6673 && ini_get_bool('child_terminate')) {
6674 if (empty($CFG->apachemaxmem)) {
6675 $CFG->apachemaxmem = 25000000; // default 25MiB
6677 if (memory_get_usage() > (int)$CFG->apachemaxmem) {
6678 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
6679 @apache_child_terminate();
6685 * If new messages are waiting for the current user, then return
6686 * Javascript code to create a popup window
6688 * @return string Javascript code
6690 function message_popup_window() {
6691 global $USER;
6693 $popuplimit = 30; // Minimum seconds between popups
6695 if (!defined('MESSAGE_WINDOW')) {
6696 if (isset($USER->id)) {
6697 if (!isset($USER->message_lastpopup)) {
6698 $USER->message_lastpopup = 0;
6700 if ((time() - $USER->message_lastpopup) > $popuplimit) { /// It's been long enough
6701 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6702 if (count_records_select('message', 'useridto = \''.$USER->id.'\' AND timecreated > \''.$USER->message_lastpopup.'\'')) {
6703 $USER->message_lastpopup = time();
6704 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6705 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6712 return '';
6715 // Used to make sure that $min <= $value <= $max
6716 function bounded_number($min, $value, $max) {
6717 if($value < $min) {
6718 return $min;
6720 if($value > $max) {
6721 return $max;
6723 return $value;
6726 function array_is_nested($array) {
6727 foreach ($array as $value) {
6728 if (is_array($value)) {
6729 return true;
6732 return false;
6736 *** get_performance_info() pairs up with init_performance_info()
6737 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6738 *** values ready for use, and each of the individual stats provided
6739 *** separately as well.
6742 function get_performance_info() {
6743 global $CFG, $PERF, $rcache;
6745 $info = array();
6746 $info['html'] = ''; // holds userfriendly HTML representation
6747 $info['txt'] = me() . ' '; // holds log-friendly representation
6749 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
6751 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6752 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6754 if (function_exists('memory_get_usage')) {
6755 $info['memory_total'] = memory_get_usage();
6756 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
6757 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6758 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6761 $inc = get_included_files();
6762 //error_log(print_r($inc,1));
6763 $info['includecount'] = count($inc);
6764 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6765 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6767 if (!empty($PERF->dbqueries)) {
6768 $info['dbqueries'] = $PERF->dbqueries;
6769 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6770 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6773 if (!empty($PERF->logwrites)) {
6774 $info['logwrites'] = $PERF->logwrites;
6775 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6776 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6779 if (!empty($PERF->profiling) && $PERF->profiling) {
6780 require_once($CFG->dirroot .'/lib/profilerlib.php');
6781 $info['html'] .= '<span class="profilinginfo">'.Profiler::get_profiling(array('-R')).'</span>';
6784 if (function_exists('posix_times')) {
6785 $ptimes = posix_times();
6786 if (is_array($ptimes)) {
6787 foreach ($ptimes as $key => $val) {
6788 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
6790 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6791 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6795 // Grab the load average for the last minute
6796 // /proc will only work under some linux configurations
6797 // while uptime is there under MacOSX/Darwin and other unices
6798 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
6799 list($server_load) = explode(' ', $loadavg[0]);
6800 unset($loadavg);
6801 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
6802 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
6803 $server_load = $matches[1];
6804 } else {
6805 trigger_error('Could not parse uptime output!');
6808 if (!empty($server_load)) {
6809 $info['serverload'] = $server_load;
6810 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
6811 $info['txt'] .= "serverload: {$info['serverload']} ";
6814 if (isset($rcache->hits) && isset($rcache->misses)) {
6815 $info['rcachehits'] = $rcache->hits;
6816 $info['rcachemisses'] = $rcache->misses;
6817 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
6818 "{$rcache->hits}/{$rcache->misses}</span> ";
6819 $info['txt'] .= 'rcache: '.
6820 "{$rcache->hits}/{$rcache->misses} ";
6822 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
6823 return $info;
6826 function apd_get_profiling() {
6827 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
6830 function remove_dir($dir, $content_only=false) {
6831 // if content_only=true then delete all but
6832 // the directory itself
6834 $handle = opendir($dir);
6835 while (false!==($item = readdir($handle))) {
6836 if($item != '.' && $item != '..') {
6837 if(is_dir($dir.'/'.$item)) {
6838 remove_dir($dir.'/'.$item);
6839 }else{
6840 unlink($dir.'/'.$item);
6844 closedir($handle);
6845 if ($content_only) {
6846 return true;
6848 return rmdir($dir);
6852 * Function to check if a directory exists and optionally create it.
6854 * @param string absolute directory path
6855 * @param boolean create directory if does not exist
6856 * @param boolean create directory recursively
6858 * @return boolean true if directory exists or created
6860 function check_dir_exists($dir, $create=false, $recursive=false) {
6862 global $CFG;
6864 $status = true;
6866 if(!is_dir($dir)) {
6867 if (!$create) {
6868 $status = false;
6869 } else {
6870 umask(0000);
6871 if ($recursive) {
6872 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
6873 $dir = str_replace('\\', '/', $dir); //windows compatibility
6874 $dirs = explode('/', $dir);
6875 $dir = array_shift($dirs).'/'; //skip root or drive letter
6876 foreach ($dirs as $part) {
6877 if ($part == '') {
6878 continue;
6880 $dir .= $part.'/';
6881 if (!is_dir($dir)) {
6882 if (!mkdir($dir, $CFG->directorypermissions)) {
6883 $status = false;
6884 break;
6888 } else {
6889 $status = mkdir($dir, $CFG->directorypermissions);
6893 return $status;
6896 function report_session_error() {
6897 global $CFG, $FULLME;
6899 if (empty($CFG->lang)) {
6900 $CFG->lang = "en";
6902 // Set up default theme and locale
6903 theme_setup();
6904 moodle_setlocale();
6906 //clear session cookies
6907 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
6908 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
6909 //increment database error counters
6910 if (isset($CFG->session_error_counter)) {
6911 set_config('session_error_counter', 1 + $CFG->session_error_counter);
6912 } else {
6913 set_config('session_error_counter', 1);
6915 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
6920 * Detect if an object or a class contains a given property
6921 * will take an actual object or the name of a class
6922 * @param mix $obj Name of class or real object to test
6923 * @param string $property name of property to find
6924 * @return bool true if property exists
6926 function object_property_exists( $obj, $property ) {
6927 if (is_string( $obj )) {
6928 $properties = get_class_vars( $obj );
6930 else {
6931 $properties = get_object_vars( $obj );
6933 return array_key_exists( $property, $properties );
6938 * Detect a custom script replacement in the data directory that will
6939 * replace an existing moodle script
6940 * @param string $urlpath path to the original script
6941 * @return string full path name if a custom script exists
6942 * @return bool false if no custom script exists
6944 function custom_script_path($urlpath='') {
6945 global $CFG;
6947 // set default $urlpath, if necessary
6948 if (empty($urlpath)) {
6949 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
6952 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
6953 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot) === false )) {
6954 return false;
6957 // replace wwwroot with the path to the customscripts folder and clean path
6958 $scriptpath = $CFG->customscripts . clean_param(substr($urlpath, strlen($CFG->wwwroot)), PARAM_PATH);
6960 // remove the query string, if any
6961 if (($strpos = strpos($scriptpath, '?')) !== false) {
6962 $scriptpath = substr($scriptpath, 0, $strpos);
6965 // remove trailing slashes, if any
6966 $scriptpath = rtrim($scriptpath, '/\\');
6968 // append index.php, if necessary
6969 if (is_dir($scriptpath)) {
6970 $scriptpath .= '/index.php';
6973 // check the custom script exists
6974 if (file_exists($scriptpath)) {
6975 return $scriptpath;
6976 } else {
6977 return false;
6982 * Wrapper function to load necessary editor scripts
6983 * to $CFG->editorsrc array. Params can be coursei id
6984 * or associative array('courseid' => value, 'name' => 'editorname').
6985 * @uses $CFG
6986 * @param mixed $args Courseid or associative array.
6988 function loadeditor($args) {
6989 global $CFG;
6990 include($CFG->libdir .'/editorlib.php');
6991 return editorObject::loadeditor($args);
6995 * Returns whether or not the user object is a remote MNET user. This function
6996 * is in moodlelib because it does not rely on loading any of the MNET code.
6998 * @param object $user A valid user object
6999 * @return bool True if the user is from a remote Moodle.
7001 function is_mnet_remote_user($user) {
7002 global $CFG;
7004 if (!isset($CFG->mnet_localhost_id)) {
7005 include_once $CFG->dirroot . '/mnet/lib.php';
7006 $env = new mnet_environment();
7007 $env->init();
7008 unset($env);
7011 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
7015 * Checks if a given plugin is in the list of enabled enrolment plugins.
7017 * @param string $auth Enrolment plugin.
7018 * @return boolean Whether the plugin is enabled.
7020 function is_enabled_enrol($enrol='') {
7021 global $CFG;
7023 // use the global default if not specified
7024 if ($enrol == '') {
7025 $enrol = $CFG->enrol;
7027 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
7031 * This function will search for browser prefereed languages, setting Moodle
7032 * to use the best one available if $SESSION->lang is undefined
7034 function setup_lang_from_browser() {
7036 global $CFG, $SESSION, $USER;
7038 if (!empty($SESSION->lang) or !empty($USER->lang)) {
7039 // Lang is defined in session or user profile, nothing to do
7040 return;
7043 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
7044 return;
7047 /// Extract and clean langs from headers
7048 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
7049 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
7050 $rawlangs = explode(',', $rawlangs); // Convert to array
7051 $langs = array();
7053 $order = 1.0;
7054 foreach ($rawlangs as $lang) {
7055 if (strpos($lang, ';') === false) {
7056 $langs[(string)$order] = $lang;
7057 $order = $order-0.01;
7058 } else {
7059 $parts = explode(';', $lang);
7060 $pos = strpos($parts[1], '=');
7061 $langs[substr($parts[1], $pos+1)] = $parts[0];
7064 krsort($langs, SORT_NUMERIC);
7066 $langlist = get_list_of_languages();
7068 /// Look for such langs under standard locations
7069 foreach ($langs as $lang) {
7070 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR)); // clean it properly for include
7071 if (!array_key_exists($lang, $langlist)) {
7072 continue; // language not allowed, try next one
7074 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
7075 $SESSION->lang = $lang; /// Lang exists, set it in session
7076 break; /// We have finished. Go out
7079 return;
7083 ////////////////////////////////////////////////////////////////////////////////
7085 * This function will build the navigation string to be used by print_header
7086 * and others
7087 * @uses $CFG
7088 * @uses $THEME
7089 * @param $extranavlinks - array of associative arrays, keys: name, link, type
7090 * @return $navigation as an object so it can be differentiated from old style
7091 * navigation strings.
7093 function build_navigation($extranavlinks) {
7094 global $CFG, $COURSE;
7096 $navigation = '';
7097 $navlinks = array();
7099 //Site name
7100 if ($site = get_site()) {
7101 $navlinks[] = array('name' => format_string($site->shortname),
7102 'link' => "$CFG->wwwroot/",
7103 'type' => 'home');
7107 if ($COURSE) {
7108 if ($COURSE->id != SITEID) {
7109 //Course
7110 $navlinks[] = array('name' => format_string($COURSE->shortname),
7111 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",
7112 'type' => 'course');
7116 //Merge in extra navigation links
7117 $navlinks = array_merge($navlinks, $extranavlinks);
7119 //Construct an unordered list from $navlinks
7120 //Accessibility: heading hidden from visual browsers by default.
7121 $navigation = '<h2 class="accesshide">'.get_string('youarehere','access')."</h2> <ul>\n";
7122 $countlinks = count($navlinks);
7123 $i = 0;
7124 foreach ($navlinks as $navlink) {
7125 if ($i >= $countlinks || !is_array($navlink)) {
7126 continue;
7128 // Check the link type to see if this link should appear in the trail
7129 $cap = has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $COURSE->id));
7130 $hidetype_is2 = $CFG->hideactivitytypenavlink == 2;
7131 $hidetype_is1 = $CFG->hideactivitytypenavlink == 1;
7133 if ($navlink['type'] == 'activity' &&
7134 $i+1 < $countlinks &&
7135 ($hidetype_is2 || ($hidetype_is1 && !$cap))) {
7136 continue;
7138 $navigation .= '<li class="first">';
7139 if ($i > 0) {
7140 $navigation .= get_separator();
7142 if ($navlink['link'] && $i+1 < $countlinks) {
7143 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlink['link']}\">";
7145 $navigation .= "{$navlink['name']}";
7146 if ($navlink['link'] && $i+1 < $countlinks) {
7147 $navigation .= "</a>";
7150 $navigation .= "</li>";
7151 $i++;
7154 $navigation .= "</ul>";
7156 return(array('newnav' => true, 'navlinks' => $navigation));
7159 function is_newnav($navigation) {
7160 if (is_array($navigation) && $navigation['newnav']) {
7161 return(true);
7162 } else {
7163 return(false);
7168 * Checks whether the given variable name is defined as a variable within the given object.
7169 * @note This will NOT work with stdClass objects, which have no class variables.
7170 * @param string $var The variable name
7171 * @param object $object The object to check
7172 * @return boolean
7174 function in_object_vars($var, $object) {
7175 $class_vars = get_class_vars(get_class($object));
7176 $class_vars = array_keys($class_vars);
7177 return in_array($var, $class_vars);
7181 * Returns an array without repeated objects.
7182 * This function is similar to array_unique, but for arrays that have objects as values
7184 * @param unknown_type $array
7185 * @param unknown_type $keep_key_assoc
7186 * @return unknown
7188 function object_array_unique($array, $keep_key_assoc = true) {
7189 $duplicate_keys = array();
7190 $tmp = array();
7192 foreach ($array as $key=>$val) {
7193 // convert objects to arrays, in_array() does not support objects
7194 if (is_object($val)) {
7195 $val = (array)$val;
7198 if (!in_array($val, $tmp)) {
7199 $tmp[] = $val;
7200 } else {
7201 $duplicate_keys[] = $key;
7205 foreach ($duplicate_keys as $key) {
7206 unset($array[$key]);
7209 return $keep_key_assoc ? $array : array_values($array);
7212 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: