adding some strings
[moodle-linuxchix.git] / lib / moodlelib.php
bloba8397801cf7ddec8b4ea71997e415987d80f5fdd
1 <?php // $Id$
3 ///////////////////////////////////////////////////////////////////////////
4 // //
5 // NOTICE OF COPYRIGHT //
6 // //
7 // Moodle - Modular Object-Oriented Dynamic Learning Environment //
8 // http://moodle.org //
9 // //
10 // Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
11 // //
12 // This program is free software; you can redistribute it and/or modify //
13 // it under the terms of the GNU General Public License as published by //
14 // the Free Software Foundation; either version 2 of the License, or //
15 // (at your option) any later version. //
16 // //
17 // This program is distributed in the hope that it will be useful, //
18 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
19 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
20 // GNU General Public License for more details: //
21 // //
22 // http://www.gnu.org/copyleft/gpl.html //
23 // //
24 ///////////////////////////////////////////////////////////////////////////
26 /**
27 * moodlelib.php - Moodle main library
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
33 * @author Martin Dougiamas
34 * @version $Id$
35 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
36 * @package moodlecore
39 /// CONSTANTS (Encased in phpdoc proper comments)/////////////////////////
41 /**
42 * Used by some scripts to check they are being called by Moodle
44 define('MOODLE_INTERNAL', true);
46 /**
47 * No groups used?
49 define('NOGROUPS', 0);
51 /**
52 * Groups used?
54 define('SEPARATEGROUPS', 1);
56 /**
57 * Groups visible?
59 define('VISIBLEGROUPS', 2);
61 /// Date and time constants ///
62 /**
63 * Time constant - the number of seconds in a year
66 define('YEARSECS', 31536000);
68 /**
69 * Time constant - the number of seconds in a week
71 define('WEEKSECS', 604800);
73 /**
74 * Time constant - the number of seconds in a day
76 define('DAYSECS', 86400);
78 /**
79 * Time constant - the number of seconds in an hour
81 define('HOURSECS', 3600);
83 /**
84 * Time constant - the number of seconds in a minute
86 define('MINSECS', 60);
88 /**
89 * Time constant - the number of minutes in a day
91 define('DAYMINS', 1440);
93 /**
94 * Time constant - the number of minutes in an hour
96 define('HOURMINS', 60);
98 /// Parameter constants - every call to optional_param(), required_param() ///
99 /// or clean_param() should have a specified type of parameter. //////////////
102 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way;
103 * originally was 0, but changed because we need to detect unknown
104 * parameter types and swiched order in clean_param().
106 define('PARAM_RAW', 666);
109 * PARAM_CLEAN - obsoleted, please try to use more specific type of parameter.
110 * It was one of the first types, that is why it is abused so much ;-)
112 define('PARAM_CLEAN', 0x0001);
115 * PARAM_INT - integers only, use when expecting only numbers.
117 define('PARAM_INT', 0x0002);
120 * PARAM_INTEGER - an alias for PARAM_INT
122 define('PARAM_INTEGER', 0x0002);
125 * PARAM_NUMBER - a real/floating point number.
127 define('PARAM_NUMBER', 0x000a);
130 * PARAM_ALPHA - contains only english letters.
132 define('PARAM_ALPHA', 0x0004);
135 * PARAM_ACTION - an alias for PARAM_ALPHA, use for various actions in formas and urls
136 * @TODO: should we alias it to PARAM_ALPHANUM ?
138 define('PARAM_ACTION', 0x0004);
141 * PARAM_FORMAT - an alias for PARAM_ALPHA, use for names of plugins, formats, etc.
142 * @TODO: should we alias it to PARAM_ALPHANUM ?
144 define('PARAM_FORMAT', 0x0004);
147 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
149 define('PARAM_NOTAGS', 0x0008);
152 * PARAM_MULTILANG - alias of PARAM_TEXT.
154 define('PARAM_MULTILANG', 0x0009);
157 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags.
159 define('PARAM_TEXT', 0x0009);
162 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
164 define('PARAM_FILE', 0x0010);
167 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
168 * note: the leading slash is not removed, window drive letter is not allowed
170 define('PARAM_PATH', 0x0020);
173 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
175 define('PARAM_HOST', 0x0040);
178 * PARAM_URL - expected properly formatted URL.
180 define('PARAM_URL', 0x0080);
183 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the others! Implies PARAM_URL!)
185 define('PARAM_LOCALURL', 0x0180);
188 * PARAM_CLEANFILE - safe file name, all dangerous and regional chars are removed,
189 * use when you want to store a new file submitted by students
191 define('PARAM_CLEANFILE',0x0200);
194 * PARAM_ALPHANUM - expected numbers and letters only.
196 define('PARAM_ALPHANUM', 0x0400);
199 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
201 define('PARAM_BOOL', 0x0800);
204 * PARAM_CLEANHTML - cleans submitted HTML code and removes slashes
205 * note: do not forget to addslashes() before storing into database!
207 define('PARAM_CLEANHTML',0x1000);
210 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "/-_" allowed,
211 * suitable for include() and require()
212 * @TODO: should we rename this function to PARAM_SAFEDIRS??
214 define('PARAM_ALPHAEXT', 0x2000);
217 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
219 define('PARAM_SAFEDIR', 0x4000);
222 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
224 define('PARAM_SEQUENCE', 0x8000);
227 * PARAM_PEM - Privacy Enhanced Mail format
229 define('PARAM_PEM', 0x10000);
232 * PARAM_BASE64 - Base 64 encoded format
234 define('PARAM_BASE64', 0x20000);
237 /// Page types ///
239 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
241 define('PAGE_COURSE_VIEW', 'course-view');
243 /// Debug levels ///
244 /** no warnings at all */
245 define ('DEBUG_NONE', 0);
246 /** E_ERROR | E_PARSE */
247 define ('DEBUG_MINIMAL', 5);
248 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
249 define ('DEBUG_NORMAL', 15);
250 /** E_ALL without E_STRICT and E_RECOVERABLE_ERROR for now */
251 define ('DEBUG_ALL', 2047);
252 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
253 define ('DEBUG_DEVELOPER', 34815);
256 * Blog access level constant declaration
258 define ('BLOG_USER_LEVEL', 1);
259 define ('BLOG_GROUP_LEVEL', 2);
260 define ('BLOG_COURSE_LEVEL', 3);
261 define ('BLOG_SITE_LEVEL', 4);
262 define ('BLOG_GLOBAL_LEVEL', 5);
266 /// PARAMETER HANDLING ////////////////////////////////////////////////////
269 * Returns a particular value for the named variable, taken from
270 * POST or GET. If the parameter doesn't exist then an error is
271 * thrown because we require this variable.
273 * This function should be used to initialise all required values
274 * in a script that are based on parameters. Usually it will be
275 * used like this:
276 * $id = required_param('id');
278 * @param string $parname the name of the page parameter we want
279 * @param int $type expected type of parameter
280 * @return mixed
282 function required_param($parname, $type=PARAM_CLEAN) {
284 // detect_unchecked_vars addition
285 global $CFG;
286 if (!empty($CFG->detect_unchecked_vars)) {
287 global $UNCHECKED_VARS;
288 unset ($UNCHECKED_VARS->vars[$parname]);
291 if (isset($_POST[$parname])) { // POST has precedence
292 $param = $_POST[$parname];
293 } else if (isset($_GET[$parname])) {
294 $param = $_GET[$parname];
295 } else {
296 error('A required parameter ('.$parname.') was missing');
299 return clean_param($param, $type);
303 * Returns a particular value for the named variable, taken from
304 * POST or GET, otherwise returning a given default.
306 * This function should be used to initialise all optional values
307 * in a script that are based on parameters. Usually it will be
308 * used like this:
309 * $name = optional_param('name', 'Fred');
311 * @param string $parname the name of the page parameter we want
312 * @param mixed $default the default value to return if nothing is found
313 * @param int $type expected type of parameter
314 * @return mixed
316 function optional_param($parname, $default=NULL, $type=PARAM_CLEAN) {
318 // detect_unchecked_vars addition
319 global $CFG;
320 if (!empty($CFG->detect_unchecked_vars)) {
321 global $UNCHECKED_VARS;
322 unset ($UNCHECKED_VARS->vars[$parname]);
325 if (isset($_POST[$parname])) { // POST has precedence
326 $param = $_POST[$parname];
327 } else if (isset($_GET[$parname])) {
328 $param = $_GET[$parname];
329 } else {
330 return $default;
333 return clean_param($param, $type);
337 * Used by {@link optional_param()} and {@link required_param()} to
338 * clean the variables and/or cast to specific types, based on
339 * an options field.
340 * <code>
341 * $course->format = clean_param($course->format, PARAM_ALPHA);
342 * $selectedgrade_item = clean_param($selectedgrade_item, PARAM_CLEAN);
343 * </code>
345 * @uses $CFG
346 * @uses PARAM_CLEAN
347 * @uses PARAM_INT
348 * @uses PARAM_INTEGER
349 * @uses PARAM_ALPHA
350 * @uses PARAM_ALPHANUM
351 * @uses PARAM_NOTAGS
352 * @uses PARAM_ALPHAEXT
353 * @uses PARAM_BOOL
354 * @uses PARAM_SAFEDIR
355 * @uses PARAM_CLEANFILE
356 * @uses PARAM_FILE
357 * @uses PARAM_PATH
358 * @uses PARAM_HOST
359 * @uses PARAM_URL
360 * @uses PARAM_LOCALURL
361 * @uses PARAM_CLEANHTML
362 * @uses PARAM_SEQUENCE
363 * @param mixed $param the variable we are cleaning
364 * @param int $type expected format of param after cleaning.
365 * @return mixed
367 function clean_param($param, $type) {
369 global $CFG;
371 if (is_array($param)) { // Let's loop
372 $newparam = array();
373 foreach ($param as $key => $value) {
374 $newparam[$key] = clean_param($value, $type);
376 return $newparam;
379 switch ($type) {
380 case PARAM_RAW: // no cleaning at all
381 return $param;
383 case PARAM_CLEAN: // General HTML cleaning, try to use more specific type if possible
384 if (is_numeric($param)) {
385 return $param;
387 $param = stripslashes($param); // Needed for kses to work fine
388 $param = clean_text($param); // Sweep for scripts, etc
389 return addslashes($param); // Restore original request parameter slashes
391 case PARAM_CLEANHTML: // prepare html fragment for display, do not store it into db!!
392 $param = stripslashes($param); // Remove any slashes
393 $param = clean_text($param); // Sweep for scripts, etc
394 return trim($param);
396 case PARAM_INT:
397 return (int)$param; // Convert to integer
399 case PARAM_NUMBER:
400 return (float)$param; // Convert to integer
402 case PARAM_ALPHA: // Remove everything not a-z
403 return eregi_replace('[^a-zA-Z]', '', $param);
405 case PARAM_ALPHANUM: // Remove everything not a-zA-Z0-9
406 return eregi_replace('[^A-Za-z0-9]', '', $param);
408 case PARAM_ALPHAEXT: // Remove everything not a-zA-Z/_-
409 return eregi_replace('[^a-zA-Z/_-]', '', $param);
411 case PARAM_SEQUENCE: // Remove everything not 0-9,
412 return eregi_replace('[^0-9,]', '', $param);
414 case PARAM_BOOL: // Convert to 1 or 0
415 $tempstr = strtolower($param);
416 if ($tempstr == 'on' or $tempstr == 'yes' ) {
417 $param = 1;
418 } else if ($tempstr == 'off' or $tempstr == 'no') {
419 $param = 0;
420 } else {
421 $param = empty($param) ? 0 : 1;
423 return $param;
425 case PARAM_NOTAGS: // Strip all tags
426 return strip_tags($param);
428 case PARAM_TEXT: // leave only tags needed for multilang
429 return clean_param(strip_tags($param, '<lang><span>'), PARAM_CLEAN);
431 case PARAM_SAFEDIR: // Remove everything not a-zA-Z0-9_-
432 return eregi_replace('[^a-zA-Z0-9_-]', '', $param);
434 case PARAM_CLEANFILE: // allow only safe characters
435 return clean_filename($param);
437 case PARAM_FILE: // Strip all suspicious characters from filename
438 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':\\/]', '', $param);
439 $param = ereg_replace('\.\.+', '', $param);
440 if($param == '.') {
441 $param = '';
443 return $param;
445 case PARAM_PATH: // Strip all suspicious characters from file path
446 $param = str_replace('\\\'', '\'', $param);
447 $param = str_replace('\\"', '"', $param);
448 $param = str_replace('\\', '/', $param);
449 $param = ereg_replace('[[:cntrl:]]|[<>"`\|\':]', '', $param);
450 $param = ereg_replace('\.\.+', '', $param);
451 $param = ereg_replace('//+', '/', $param);
452 return ereg_replace('/(\./)+', '/', $param);
454 case PARAM_HOST: // allow FQDN or IPv4 dotted quad
455 preg_replace('/[^\.\d\w-]/','', $param ); // only allowed chars
456 // match ipv4 dotted quad
457 if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/',$param, $match)){
458 // confirm values are ok
459 if ( $match[0] > 255
460 || $match[1] > 255
461 || $match[3] > 255
462 || $match[4] > 255 ) {
463 // hmmm, what kind of dotted quad is this?
464 $param = '';
466 } elseif ( preg_match('/^[\w\d\.-]+$/', $param) // dots, hyphens, numbers
467 && !preg_match('/^[\.-]/', $param) // no leading dots/hyphens
468 && !preg_match('/[\.-]$/', $param) // no trailing dots/hyphens
470 // all is ok - $param is respected
471 } else {
472 // all is not ok...
473 $param='';
475 return $param;
477 case PARAM_URL: // allow safe ftp, http, mailto urls
478 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
479 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
480 // all is ok, param is respected
481 } else {
482 $param =''; // not really ok
484 return $param;
486 case PARAM_LOCALURL: // allow http absolute, root relative and relative URLs within wwwroot
487 $param = clean_param($param, PARAM_URL);
488 if (!empty($param)) {
489 if (preg_match(':^/:', $param)) {
490 // root-relative, ok!
491 } elseif (preg_match('/^'.preg_quote($CFG->wwwroot, '/').'/i',$param)) {
492 // absolute, and matches our wwwroot
493 } else {
494 // relative - let's make sure there are no tricks
495 if (validateUrlSyntax($param, 's-u-P-a-p-f+q?r?')) {
496 // looks ok.
497 } else {
498 $param = '';
502 return $param;
503 case PARAM_PEM:
504 $param = trim($param);
505 // PEM formatted strings may contain letters/numbers and the symbols
506 // forward slash: /
507 // plus sign: +
508 // equal sign: =
509 // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes
510 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
511 list($wholething, $body) = $matches;
512 unset($wholething, $matches);
513 $b64 = clean_param($body, PARAM_BASE64);
514 if (!empty($b64)) {
515 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
516 } else {
517 return '';
520 return '';
521 case PARAM_BASE64:
522 if (!empty($param)) {
523 // PEM formatted strings may contain letters/numbers and the symbols
524 // forward slash: /
525 // plus sign: +
526 // equal sign: =
527 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
528 return '';
530 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
531 // Each line of base64 encoded data must be 64 characters in
532 // length, except for the last line which may be less than (or
533 // equal to) 64 characters long.
534 for ($i=0, $j=count($lines); $i < $j; $i++) {
535 if ($i + 1 == $j) {
536 if (64 < strlen($lines[$i])) {
537 return '';
539 continue;
542 if (64 != strlen($lines[$i])) {
543 return '';
546 return implode("\n",$lines);
547 } else {
548 return '';
550 default: // throw error, switched parameters in optional_param or another serious problem
551 error("Unknown parameter type: $type");
558 * Set a key in global configuration
560 * Set a key/value pair in both this session's {@link $CFG} global variable
561 * and in the 'config' database table for future sessions.
563 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
564 * In that case it doesn't affect $CFG.
566 * @param string $name the key to set
567 * @param string $value the value to set (without magic quotes)
568 * @param string $plugin (optional) the plugin scope
569 * @uses $CFG
570 * @return bool
572 function set_config($name, $value, $plugin=NULL) {
573 /// No need for get_config because they are usually always available in $CFG
575 global $CFG;
577 if (empty($plugin)) {
578 $CFG->$name = $value; // So it's defined for this invocation at least
580 if (get_field('config', 'name', 'name', $name)) {
581 return set_field('config', 'value', addslashes($value), 'name', $name);
582 } else {
583 $config = new object();
584 $config->name = $name;
585 $config->value = addslashes($value);
586 return insert_record('config', $config);
588 } else { // plugin scope
589 if ($id = get_field('config_plugins', 'id', 'name', $name, 'plugin', $plugin)) {
590 return set_field('config_plugins', 'value', addslashes($value), 'id', $id);
591 } else {
592 $config = new object();
593 $config->plugin = addslashes($plugin);
594 $config->name = $name;
595 $config->value = addslashes($value);
596 return insert_record('config_plugins', $config);
602 * Get configuration values from the global config table
603 * or the config_plugins table.
605 * If called with no parameters it will do the right thing
606 * generating $CFG safely from the database without overwriting
607 * existing values.
609 * If called with 2 parameters it will return a $string single
610 * value or false of the value is not found.
612 * @param string $plugin
613 * @param string $name
614 * @uses $CFG
615 * @return hash-like object or single value
618 function get_config($plugin=NULL, $name=NULL) {
620 global $CFG;
622 if (!empty($name)) { // the user is asking for a specific value
623 if (!empty($plugin)) {
624 return get_field('config_plugins', 'value', 'plugin' , $plugin, 'name', $name);
625 } else {
626 return get_field('config', 'value', 'name', $name);
630 // the user is after a recordset
631 if (!empty($plugin)) {
632 if ($configs=get_records('config_plugins', 'plugin', $plugin, '', 'name,value')) {
633 $configs = (array)$configs;
634 $localcfg = array();
635 foreach ($configs as $config) {
636 $localcfg[$config->name] = $config->value;
638 return (object)$localcfg;
639 } else {
640 return false;
642 } else {
643 // this was originally in setup.php
644 if ($configs = get_records('config')) {
645 $localcfg = (array)$CFG;
646 foreach ($configs as $config) {
647 if (!isset($localcfg[$config->name])) {
648 $localcfg[$config->name] = $config->value;
649 } else {
650 if ($localcfg[$config->name] != $config->value ) {
651 // complain if the DB has a different
652 // value than config.php does
653 error_log("\$CFG->{$config->name} in config.php ({$localcfg[$config->name]}) overrides database setting ({$config->value})");
658 $localcfg = (object)$localcfg;
659 return $localcfg;
660 } else {
661 // preserve $CFG if DB returns nothing or error
662 return $CFG;
669 * Removes a key from global configuration
671 * @param string $name the key to set
672 * @param string $plugin (optional) the plugin scope
673 * @uses $CFG
674 * @return bool
676 function unset_config($name, $plugin=NULL) {
678 global $CFG;
680 unset($CFG->$name);
682 if (empty($plugin)) {
683 return delete_records('config', 'name', $name);
684 } else {
685 return delete_records('config_plugins', 'name', $name, 'plugin', $plugin);
691 * Refresh current $USER session global variable with all their current preferences.
692 * @uses $USER
694 function reload_user_preferences() {
696 global $USER;
698 //reset preference
699 $USER->preference = array();
701 if (!isloggedin() or isguestuser()) {
702 // no pernament storage for not-logged-in user and guest
704 } else if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
705 foreach ($preferences as $preference) {
706 $USER->preference[$preference->name] = $preference->value;
710 return true;
714 * Sets a preference for the current user
715 * Optionally, can set a preference for a different user object
716 * @uses $USER
717 * @todo Add a better description and include usage examples. Add inline links to $USER and user functions in above line.
719 * @param string $name The key to set as preference for the specified user
720 * @param string $value The value to set forthe $name key in the specified user's record
721 * @param int $otheruserid A moodle user ID
722 * @return bool
724 function set_user_preference($name, $value, $otheruserid=NULL) {
726 global $USER;
728 if (!isset($USER->preference)) {
729 reload_user_preferences();
732 if (empty($name)) {
733 return false;
736 $nostore = false;
738 if (empty($otheruserid)){
739 if (!isloggedin() or isguestuser()) {
740 $nostore = true;
742 $userid = $USER->id;
743 } else {
744 if (isguestuser($otheruserid)) {
745 $nostore = true;
747 $userid = $otheruserid;
750 $return = true;
751 if ($nostore) {
752 // no pernament storage for not-logged-in user and guest
754 } else if ($preference = get_record('user_preferences', 'userid', $userid, 'name', addslashes($name))) {
755 if (!set_field('user_preferences', 'value', addslashes((string)$value), 'id', $preference->id)) {
756 $return = false;
759 } else {
760 $preference = new object();
761 $preference->userid = $userid;
762 $preference->name = addslashes($name);
763 $preference->value = addslashes((string)$value);
764 if (!insert_record('user_preferences', $preference)) {
765 $return = false;
769 // update value in USER session if needed
770 if ($userid == $USER->id) {
771 $USER->preference[$name] = (string)$value;
774 return $return;
778 * Unsets a preference completely by deleting it from the database
779 * Optionally, can set a preference for a different user id
780 * @uses $USER
781 * @param string $name The key to unset as preference for the specified user
782 * @param int $otheruserid A moodle user ID
784 function unset_user_preference($name, $otheruserid=NULL) {
786 global $USER;
788 if (!isset($USER->preference)) {
789 reload_user_preferences();
792 if (empty($otheruserid)){
793 $userid = $USER->id;
794 } else {
795 $userid = $otheruserid;
798 //Delete the preference from $USER if needed
799 if ($userid == $USER->id) {
800 unset($USER->preference[$name]);
803 //Then from DB
804 return delete_records('user_preferences', 'userid', $userid, 'name', addslashes($name));
809 * Sets a whole array of preferences for the current user
810 * @param array $prefarray An array of key/value pairs to be set
811 * @param int $otheruserid A moodle user ID
812 * @return bool
814 function set_user_preferences($prefarray, $otheruserid=NULL) {
816 if (!is_array($prefarray) or empty($prefarray)) {
817 return false;
820 $return = true;
821 foreach ($prefarray as $name => $value) {
822 // The order is important; test for return is done first
823 $return = (set_user_preference($name, $value, $otheruserid) && $return);
825 return $return;
829 * If no arguments are supplied this function will return
830 * all of the current user preferences as an array.
831 * If a name is specified then this function
832 * attempts to return that particular preference value. If
833 * none is found, then the optional value $default is returned,
834 * otherwise NULL.
835 * @param string $name Name of the key to use in finding a preference value
836 * @param string $default Value to be returned if the $name key is not set in the user preferences
837 * @param int $otheruserid A moodle user ID
838 * @uses $USER
839 * @return string
841 function get_user_preferences($name=NULL, $default=NULL, $otheruserid=NULL) {
842 global $USER;
844 if (!isset($USER->preference)) {
845 reload_user_preferences();
848 if (empty($otheruserid)){
849 $userid = $USER->id;
850 } else {
851 $userid = $otheruserid;
854 if ($userid == $USER->id) {
855 $preference = $USER->preference;
857 } else {
858 $preference = array();
859 if ($prefdata = get_records('user_preferences', 'userid', $userid)) {
860 foreach ($prefdata as $pref) {
861 $preference[$pref->name] = $pref->value;
866 if (empty($name)) {
867 return $preference; // All values
869 } else if (array_key_exists($name, $preference)) {
870 return $preference[$name]; // The single value
872 } else {
873 return $default; // Default value (or NULL)
878 /// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
881 * Given date parts in user time produce a GMT timestamp.
883 * @param int $year The year part to create timestamp of
884 * @param int $month The month part to create timestamp of
885 * @param int $day The day part to create timestamp of
886 * @param int $hour The hour part to create timestamp of
887 * @param int $minute The minute part to create timestamp of
888 * @param int $second The second part to create timestamp of
889 * @param float $timezone ?
890 * @param bool $applydst ?
891 * @return int timestamp
892 * @todo Finish documenting this function
894 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
896 $timezone = get_user_timezone_offset($timezone);
898 if (abs($timezone) > 13) {
899 $time = mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
900 } else {
901 $time = gmmktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year);
902 $time = usertime($time, $timezone);
903 if($applydst) {
904 $time -= dst_offset_on($time);
908 return $time;
913 * Given an amount of time in seconds, returns string
914 * formatted nicely as weeks, days, hours etc as needed
916 * @uses MINSECS
917 * @uses HOURSECS
918 * @uses DAYSECS
919 * @uses YEARSECS
920 * @param int $totalsecs ?
921 * @param array $str ?
922 * @return string
924 function format_time($totalsecs, $str=NULL) {
926 $totalsecs = abs($totalsecs);
928 if (!$str) { // Create the str structure the slow way
929 $str->day = get_string('day');
930 $str->days = get_string('days');
931 $str->hour = get_string('hour');
932 $str->hours = get_string('hours');
933 $str->min = get_string('min');
934 $str->mins = get_string('mins');
935 $str->sec = get_string('sec');
936 $str->secs = get_string('secs');
937 $str->year = get_string('year');
938 $str->years = get_string('years');
942 $years = floor($totalsecs/YEARSECS);
943 $remainder = $totalsecs - ($years*YEARSECS);
944 $days = floor($remainder/DAYSECS);
945 $remainder = $totalsecs - ($days*DAYSECS);
946 $hours = floor($remainder/HOURSECS);
947 $remainder = $remainder - ($hours*HOURSECS);
948 $mins = floor($remainder/MINSECS);
949 $secs = $remainder - ($mins*MINSECS);
951 $ss = ($secs == 1) ? $str->sec : $str->secs;
952 $sm = ($mins == 1) ? $str->min : $str->mins;
953 $sh = ($hours == 1) ? $str->hour : $str->hours;
954 $sd = ($days == 1) ? $str->day : $str->days;
955 $sy = ($years == 1) ? $str->year : $str->years;
957 $oyears = '';
958 $odays = '';
959 $ohours = '';
960 $omins = '';
961 $osecs = '';
963 if ($years) $oyears = $years .' '. $sy;
964 if ($days) $odays = $days .' '. $sd;
965 if ($hours) $ohours = $hours .' '. $sh;
966 if ($mins) $omins = $mins .' '. $sm;
967 if ($secs) $osecs = $secs .' '. $ss;
969 if ($years) return trim($oyears .' '. $odays);
970 if ($days) return trim($odays .' '. $ohours);
971 if ($hours) return trim($ohours .' '. $omins);
972 if ($mins) return trim($omins .' '. $osecs);
973 if ($secs) return $osecs;
974 return get_string('now');
978 * Returns a formatted string that represents a date in user time
979 * <b>WARNING: note that the format is for strftime(), not date().</b>
980 * Because of a bug in most Windows time libraries, we can't use
981 * the nicer %e, so we have to use %d which has leading zeroes.
982 * A lot of the fuss in the function is just getting rid of these leading
983 * zeroes as efficiently as possible.
985 * If parameter fixday = true (default), then take off leading
986 * zero from %d, else mantain it.
988 * @uses HOURSECS
989 * @param int $date timestamp in GMT
990 * @param string $format strftime format
991 * @param float $timezone
992 * @param bool $fixday If true (default) then the leading
993 * zero from %d is removed. If false then the leading zero is mantained.
994 * @return string
996 function userdate($date, $format='', $timezone=99, $fixday = true) {
998 global $CFG;
1000 if (empty($format)) {
1001 $format = get_string('strftimedaydatetime');
1004 if (!empty($CFG->nofixday)) { // Config.php can force %d not to be fixed.
1005 $fixday = false;
1006 } else if ($fixday) {
1007 $formatnoday = str_replace('%d', 'DD', $format);
1008 $fixday = ($formatnoday != $format);
1011 $date += dst_offset_on($date);
1013 $timezone = get_user_timezone_offset($timezone);
1015 if (abs($timezone) > 13) { /// Server time
1016 if ($fixday) {
1017 $datestring = strftime($formatnoday, $date);
1018 $daystring = str_replace(' 0', '', strftime(' %d', $date));
1019 $datestring = str_replace('DD', $daystring, $datestring);
1020 } else {
1021 $datestring = strftime($format, $date);
1023 } else {
1024 $date += (int)($timezone * 3600);
1025 if ($fixday) {
1026 $datestring = gmstrftime($formatnoday, $date);
1027 $daystring = str_replace(' 0', '', gmstrftime(' %d', $date));
1028 $datestring = str_replace('DD', $daystring, $datestring);
1029 } else {
1030 $datestring = gmstrftime($format, $date);
1034 /// If we are running under Windows convert from windows encoding to UTF-8
1035 /// (because it's impossible to specify UTF-8 to fetch locale info in Win32)
1037 if ($CFG->ostype == 'WINDOWS') {
1038 if ($localewincharset = get_string('localewincharset')) {
1039 $textlib = textlib_get_instance();
1040 $datestring = $textlib->convert($datestring, $localewincharset, 'utf-8');
1044 return $datestring;
1048 * Given a $time timestamp in GMT (seconds since epoch),
1049 * returns an array that represents the date in user time
1051 * @uses HOURSECS
1052 * @param int $time Timestamp in GMT
1053 * @param float $timezone ?
1054 * @return array An array that represents the date in user time
1055 * @todo Finish documenting this function
1057 function usergetdate($time, $timezone=99) {
1059 $timezone = get_user_timezone_offset($timezone);
1061 if (abs($timezone) > 13) { // Server time
1062 return getdate($time);
1065 // There is no gmgetdate so we use gmdate instead
1066 $time += dst_offset_on($time);
1067 $time += intval((float)$timezone * HOURSECS);
1069 $datestring = gmstrftime('%S_%M_%H_%d_%m_%Y_%w_%j_%A_%B', $time);
1071 list(
1072 $getdate['seconds'],
1073 $getdate['minutes'],
1074 $getdate['hours'],
1075 $getdate['mday'],
1076 $getdate['mon'],
1077 $getdate['year'],
1078 $getdate['wday'],
1079 $getdate['yday'],
1080 $getdate['weekday'],
1081 $getdate['month']
1082 ) = explode('_', $datestring);
1084 return $getdate;
1088 * Given a GMT timestamp (seconds since epoch), offsets it by
1089 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1091 * @uses HOURSECS
1092 * @param int $date Timestamp in GMT
1093 * @param float $timezone
1094 * @return int
1096 function usertime($date, $timezone=99) {
1098 $timezone = get_user_timezone_offset($timezone);
1100 if (abs($timezone) > 13) {
1101 return $date;
1103 return $date - (int)($timezone * HOURSECS);
1107 * Given a time, return the GMT timestamp of the most recent midnight
1108 * for the current user.
1110 * @param int $date Timestamp in GMT
1111 * @param float $timezone ?
1112 * @return ?
1114 function usergetmidnight($date, $timezone=99) {
1116 $timezone = get_user_timezone_offset($timezone);
1117 $userdate = usergetdate($date, $timezone);
1119 // Time of midnight of this user's day, in GMT
1120 return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
1125 * Returns a string that prints the user's timezone
1127 * @param float $timezone The user's timezone
1128 * @return string
1130 function usertimezone($timezone=99) {
1132 $tz = get_user_timezone($timezone);
1134 if (!is_float($tz)) {
1135 return $tz;
1138 if(abs($tz) > 13) { // Server time
1139 return get_string('serverlocaltime');
1142 if($tz == intval($tz)) {
1143 // Don't show .0 for whole hours
1144 $tz = intval($tz);
1147 if($tz == 0) {
1148 return 'GMT';
1150 else if($tz > 0) {
1151 return 'GMT+'.$tz;
1153 else {
1154 return 'GMT'.$tz;
1160 * Returns a float which represents the user's timezone difference from GMT in hours
1161 * Checks various settings and picks the most dominant of those which have a value
1163 * @uses $CFG
1164 * @uses $USER
1165 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1166 * @return int
1168 function get_user_timezone_offset($tz = 99) {
1170 global $USER, $CFG;
1172 $tz = get_user_timezone($tz);
1174 if (is_float($tz)) {
1175 return $tz;
1176 } else {
1177 $tzrecord = get_timezone_record($tz);
1178 if (empty($tzrecord)) {
1179 return 99.0;
1181 return (float)$tzrecord->gmtoff / HOURMINS;
1186 * Returns a float or a string which denotes the user's timezone
1187 * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
1188 * means that for this timezone there are also DST rules to be taken into account
1189 * Checks various settings and picks the most dominant of those which have a value
1191 * @uses $USER
1192 * @uses $CFG
1193 * @param float $tz If this value is provided and not equal to 99, it will be returned as is and no other settings will be checked
1194 * @return mixed
1196 function get_user_timezone($tz = 99) {
1197 global $USER, $CFG;
1199 $timezones = array(
1200 $tz,
1201 isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
1202 isset($USER->timezone) ? $USER->timezone : 99,
1203 isset($CFG->timezone) ? $CFG->timezone : 99,
1206 $tz = 99;
1208 while(($tz == '' || $tz == 99) && $next = each($timezones)) {
1209 $tz = $next['value'];
1212 return is_numeric($tz) ? (float) $tz : $tz;
1218 * @uses $CFG
1219 * @uses $db
1220 * @param string $timezonename ?
1221 * @return object
1223 function get_timezone_record($timezonename) {
1224 global $CFG, $db;
1225 static $cache = NULL;
1227 if ($cache === NULL) {
1228 $cache = array();
1231 if (isset($cache[$timezonename])) {
1232 return $cache[$timezonename];
1235 return $cache[$timezonename] = get_record_sql('SELECT * FROM '.$CFG->prefix.'timezone
1236 WHERE name = '.$db->qstr($timezonename).' ORDER BY year DESC', true);
1242 * @uses $CFG
1243 * @uses $USER
1244 * @param ? $fromyear ?
1245 * @param ? $to_year ?
1246 * @return bool
1248 function calculate_user_dst_table($from_year = NULL, $to_year = NULL) {
1249 global $CFG, $SESSION;
1251 $usertz = get_user_timezone();
1253 if (is_float($usertz)) {
1254 // Trivial timezone, no DST
1255 return false;
1258 if (!empty($SESSION->dst_offsettz) && $SESSION->dst_offsettz != $usertz) {
1259 // We have precalculated values, but the user's effective TZ has changed in the meantime, so reset
1260 unset($SESSION->dst_offsets);
1261 unset($SESSION->dst_range);
1264 if (!empty($SESSION->dst_offsets) && empty($from_year) && empty($to_year)) {
1265 // Repeat calls which do not request specific year ranges stop here, we have already calculated the table
1266 // This will be the return path most of the time, pretty light computationally
1267 return true;
1270 // Reaching here means we either need to extend our table or create it from scratch
1272 // Remember which TZ we calculated these changes for
1273 $SESSION->dst_offsettz = $usertz;
1275 if(empty($SESSION->dst_offsets)) {
1276 // If we 're creating from scratch, put the two guard elements in there
1277 $SESSION->dst_offsets = array(1 => NULL, 0 => NULL);
1279 if(empty($SESSION->dst_range)) {
1280 // If creating from scratch
1281 $from = max((empty($from_year) ? intval(date('Y')) - 3 : $from_year), 1971);
1282 $to = min((empty($to_year) ? intval(date('Y')) + 3 : $to_year), 2035);
1284 // Fill in the array with the extra years we need to process
1285 $yearstoprocess = array();
1286 for($i = $from; $i <= $to; ++$i) {
1287 $yearstoprocess[] = $i;
1290 // Take note of which years we have processed for future calls
1291 $SESSION->dst_range = array($from, $to);
1293 else {
1294 // If needing to extend the table, do the same
1295 $yearstoprocess = array();
1297 $from = max((empty($from_year) ? $SESSION->dst_range[0] : $from_year), 1971);
1298 $to = min((empty($to_year) ? $SESSION->dst_range[1] : $to_year), 2035);
1300 if($from < $SESSION->dst_range[0]) {
1301 // Take note of which years we need to process and then note that we have processed them for future calls
1302 for($i = $from; $i < $SESSION->dst_range[0]; ++$i) {
1303 $yearstoprocess[] = $i;
1305 $SESSION->dst_range[0] = $from;
1307 if($to > $SESSION->dst_range[1]) {
1308 // Take note of which years we need to process and then note that we have processed them for future calls
1309 for($i = $SESSION->dst_range[1] + 1; $i <= $to; ++$i) {
1310 $yearstoprocess[] = $i;
1312 $SESSION->dst_range[1] = $to;
1316 if(empty($yearstoprocess)) {
1317 // This means that there was a call requesting a SMALLER range than we have already calculated
1318 return true;
1321 // From now on, we know that the array has at least the two guard elements, and $yearstoprocess has the years we need
1322 // Also, the array is sorted in descending timestamp order!
1324 // Get DB data
1325 $presetrecords = get_records('timezone', 'name', $usertz, 'year DESC', 'year, gmtoff, dstoff, dst_month, dst_startday, dst_weekday, dst_skipweeks, dst_time, std_month, std_startday, std_weekday, std_skipweeks, std_time');
1326 if(empty($presetrecords)) {
1327 return false;
1330 // Remove ending guard (first element of the array)
1331 reset($SESSION->dst_offsets);
1332 unset($SESSION->dst_offsets[key($SESSION->dst_offsets)]);
1334 // Add all required change timestamps
1335 foreach($yearstoprocess as $y) {
1336 // Find the record which is in effect for the year $y
1337 foreach($presetrecords as $year => $preset) {
1338 if($year <= $y) {
1339 break;
1343 $changes = dst_changes_for_year($y, $preset);
1345 if($changes === NULL) {
1346 continue;
1348 if($changes['dst'] != 0) {
1349 $SESSION->dst_offsets[$changes['dst']] = $preset->dstoff * MINSECS;
1351 if($changes['std'] != 0) {
1352 $SESSION->dst_offsets[$changes['std']] = 0;
1356 // Put in a guard element at the top
1357 $maxtimestamp = max(array_keys($SESSION->dst_offsets));
1358 $SESSION->dst_offsets[($maxtimestamp + DAYSECS)] = NULL; // DAYSECS is arbitrary, any "small" number will do
1360 // Sort again
1361 krsort($SESSION->dst_offsets);
1363 return true;
1366 function dst_changes_for_year($year, $timezone) {
1368 if($timezone->dst_startday == 0 && $timezone->dst_weekday == 0 && $timezone->std_startday == 0 && $timezone->std_weekday == 0) {
1369 return NULL;
1372 $monthdaydst = find_day_in_month($timezone->dst_startday, $timezone->dst_weekday, $timezone->dst_month, $year);
1373 $monthdaystd = find_day_in_month($timezone->std_startday, $timezone->std_weekday, $timezone->std_month, $year);
1375 list($dst_hour, $dst_min) = explode(':', $timezone->dst_time);
1376 list($std_hour, $std_min) = explode(':', $timezone->std_time);
1378 $timedst = make_timestamp($year, $timezone->dst_month, $monthdaydst, 0, 0, 0, 99, false);
1379 $timestd = make_timestamp($year, $timezone->std_month, $monthdaystd, 0, 0, 0, 99, false);
1381 // Instead of putting hour and minute in make_timestamp(), we add them afterwards.
1382 // This has the advantage of being able to have negative values for hour, i.e. for timezones
1383 // where GMT time would be in the PREVIOUS day than the local one on which DST changes.
1385 $timedst += $dst_hour * HOURSECS + $dst_min * MINSECS;
1386 $timestd += $std_hour * HOURSECS + $std_min * MINSECS;
1388 return array('dst' => $timedst, 0 => $timedst, 'std' => $timestd, 1 => $timestd);
1391 // $time must NOT be compensated at all, it has to be a pure timestamp
1392 function dst_offset_on($time) {
1393 global $SESSION;
1395 if(!calculate_user_dst_table() || empty($SESSION->dst_offsets)) {
1396 return 0;
1399 reset($SESSION->dst_offsets);
1400 while(list($from, $offset) = each($SESSION->dst_offsets)) {
1401 if($from <= $time) {
1402 break;
1406 // This is the normal return path
1407 if($offset !== NULL) {
1408 return $offset;
1411 // Reaching this point means we haven't calculated far enough, do it now:
1412 // Calculate extra DST changes if needed and recurse. The recursion always
1413 // moves toward the stopping condition, so will always end.
1415 if($from == 0) {
1416 // We need a year smaller than $SESSION->dst_range[0]
1417 if($SESSION->dst_range[0] == 1971) {
1418 return 0;
1420 calculate_user_dst_table($SESSION->dst_range[0] - 5, NULL);
1421 return dst_offset_on($time);
1423 else {
1424 // We need a year larger than $SESSION->dst_range[1]
1425 if($SESSION->dst_range[1] == 2035) {
1426 return 0;
1428 calculate_user_dst_table(NULL, $SESSION->dst_range[1] + 5);
1429 return dst_offset_on($time);
1433 function find_day_in_month($startday, $weekday, $month, $year) {
1435 $daysinmonth = days_in_month($month, $year);
1437 if($weekday == -1) {
1438 // Don't care about weekday, so return:
1439 // abs($startday) if $startday != -1
1440 // $daysinmonth otherwise
1441 return ($startday == -1) ? $daysinmonth : abs($startday);
1444 // From now on we 're looking for a specific weekday
1446 // Give "end of month" its actual value, since we know it
1447 if($startday == -1) {
1448 $startday = -1 * $daysinmonth;
1451 // Starting from day $startday, the sign is the direction
1453 if($startday < 1) {
1455 $startday = abs($startday);
1456 $lastmonthweekday = strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1458 // This is the last such weekday of the month
1459 $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
1460 if($lastinmonth > $daysinmonth) {
1461 $lastinmonth -= 7;
1464 // Find the first such weekday <= $startday
1465 while($lastinmonth > $startday) {
1466 $lastinmonth -= 7;
1469 return $lastinmonth;
1472 else {
1474 $indexweekday = strftime('%w', mktime(12, 0, 0, $month, $startday, $year, 0));
1476 $diff = $weekday - $indexweekday;
1477 if($diff < 0) {
1478 $diff += 7;
1481 // This is the first such weekday of the month equal to or after $startday
1482 $firstfromindex = $startday + $diff;
1484 return $firstfromindex;
1490 * Calculate the number of days in a given month
1492 * @param int $month The month whose day count is sought
1493 * @param int $year The year of the month whose day count is sought
1494 * @return int
1496 function days_in_month($month, $year) {
1497 return intval(date('t', mktime(12, 0, 0, $month, 1, $year, 0)));
1501 * Calculate the position in the week of a specific calendar day
1503 * @param int $day The day of the date whose position in the week is sought
1504 * @param int $month The month of the date whose position in the week is sought
1505 * @param int $year The year of the date whose position in the week is sought
1506 * @return int
1508 function dayofweek($day, $month, $year) {
1509 // I wonder if this is any different from
1510 // strftime('%w', mktime(12, 0, 0, $month, $daysinmonth, $year, 0));
1511 return intval(date('w', mktime(12, 0, 0, $month, $day, $year, 0)));
1514 /// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
1517 * Makes sure that $USER->sesskey exists, if $USER itself exists. It sets a new sesskey
1518 * if one does not already exist, but does not overwrite existing sesskeys. Returns the
1519 * sesskey string if $USER exists, or boolean false if not.
1521 * @uses $USER
1522 * @return string
1524 function sesskey() {
1525 global $USER;
1527 if(!isset($USER)) {
1528 return false;
1531 if (empty($USER->sesskey)) {
1532 $USER->sesskey = random_string(10);
1535 return $USER->sesskey;
1540 * For security purposes, this function will check that the currently
1541 * given sesskey (passed as a parameter to the script or this function)
1542 * matches that of the current user.
1544 * @param string $sesskey optionally provided sesskey
1545 * @return bool
1547 function confirm_sesskey($sesskey=NULL) {
1548 global $USER;
1550 if (!empty($USER->ignoresesskey) || !empty($CFG->ignoresesskey)) {
1551 return true;
1554 if (empty($sesskey)) {
1555 $sesskey = required_param('sesskey', PARAM_RAW); // Check script parameters
1558 if (!isset($USER->sesskey)) {
1559 return false;
1562 return ($USER->sesskey === $sesskey);
1566 * Setup all global $CFG course variables, set locale and also themes
1567 * This function can be used on pages that do not require login instead of require_login()
1569 * @param mixed $courseorid id of the course or course object
1571 function course_setup($courseorid=0) {
1572 global $COURSE, $CFG, $SITE;
1574 /// Redefine global $COURSE if needed
1575 if (empty($courseorid)) {
1576 // no change in global $COURSE - for backwards compatibiltiy
1577 // if require_rogin() used after require_login($courseid);
1578 } else if (is_object($courseorid)) {
1579 $COURSE = clone($courseorid);
1580 } else {
1581 global $course; // used here only to prevent repeated fetching from DB - may be removed later
1582 if (!empty($course->id) and $course->id == SITEID) {
1583 $COURSE = clone($SITE);
1584 } else if (!empty($course->id) and $course->id == $courseorid) {
1585 $COURSE = clone($course);
1586 } else {
1587 if (!$COURSE = get_record('course', 'id', $courseorid)) {
1588 error('Invalid course ID');
1593 /// set locale and themes
1594 moodle_setlocale();
1595 theme_setup();
1600 * This function checks that the current user is logged in and has the
1601 * required privileges
1603 * This function checks that the current user is logged in, and optionally
1604 * whether they are allowed to be in a particular course and view a particular
1605 * course module.
1606 * If they are not logged in, then it redirects them to the site login unless
1607 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
1608 * case they are automatically logged in as guests.
1609 * If $courseid is given and the user is not enrolled in that course then the
1610 * user is redirected to the course enrolment page.
1611 * If $cm is given and the coursemodule is hidden and the user is not a teacher
1612 * in the course then the user is redirected to the course home page.
1614 * @uses $CFG
1615 * @uses $SESSION
1616 * @uses $USER
1617 * @uses $FULLME
1618 * @uses SITEID
1619 * @uses $COURSE
1620 * @param mixed $courseorid id of the course or course object
1621 * @param bool $autologinguest
1622 * @param object $cm course module object
1624 function require_login($courseorid=0, $autologinguest=true, $cm=null) {
1626 global $CFG, $SESSION, $USER, $COURSE, $FULLME;
1628 /// setup global $COURSE, themes, language and locale
1629 course_setup($courseorid);
1631 /// If the user is not even logged in yet then make sure they are
1632 if (!isloggedin()) {
1633 //NOTE: $USER->site check was obsoleted by session test cookie,
1634 // $USER->confirmed test is in login/index.php
1635 $SESSION->wantsurl = $FULLME;
1636 if (!empty($_SERVER['HTTP_REFERER'])) {
1637 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
1639 if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests) and ($COURSE->id == SITEID or $COURSE->guest) ) {
1640 $loginguest = '?loginguest=true';
1641 } else {
1642 $loginguest = '';
1644 if (empty($CFG->loginhttps) or $loginguest) { //do not require https for guest logins
1645 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
1646 } else {
1647 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1648 redirect($wwwroot .'/login/index.php');
1650 exit;
1653 /// loginas as redirection if needed
1654 if ($COURSE->id != SITEID and !empty($USER->realuser)) {
1655 if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
1656 if ($USER->loginascontext->instanceid != $COURSE->id) {
1657 print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
1663 /// check whether the user should be changing password (but only if it is REALLY them)
1664 $userauth = get_auth_plugin($USER->auth);
1665 if (get_user_preferences('auth_forcepasswordchange') && empty($USER->realuser)) {
1666 if ($userauth->can_change_password()) {
1667 $SESSION->wantsurl = $FULLME;
1668 if ($changeurl = $userauth->change_password_url()) {
1669 //use plugin custom url
1670 redirect($changeurl);
1671 } else {
1672 //use moodle internal method
1673 if (empty($CFG->loginhttps)) {
1674 redirect($CFG->wwwroot .'/login/change_password.php');
1675 } else {
1676 $wwwroot = str_replace('http:','https:', $CFG->wwwroot);
1677 redirect($wwwroot .'/login/change_password.php');
1680 } else {
1681 error(get_string('nopasswordchangeforced', 'auth'));
1685 /// Check that the user account is properly set up
1686 if (user_not_fully_set_up($USER)) {
1687 $SESSION->wantsurl = $FULLME;
1688 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
1691 /// Make sure current IP matches the one for this session (if required)
1692 if (!empty($CFG->tracksessionip)) {
1693 if ($USER->sessionIP != md5(getremoteaddr())) {
1694 error(get_string('sessionipnomatch', 'error'));
1698 /// Make sure the USER has a sesskey set up. Used for checking script parameters.
1699 sesskey();
1701 // Check that the user has agreed to a site policy if there is one
1702 if (!empty($CFG->sitepolicy)) {
1703 if (!$USER->policyagreed) {
1704 $SESSION->wantsurl = $FULLME;
1705 redirect($CFG->wwwroot .'/user/policy.php');
1709 /// If the site is currently under maintenance, then print a message
1710 if (!has_capability('moodle/site:config',get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1711 if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
1712 print_maintenance_message();
1713 exit;
1718 if ($COURSE->id == SITEID) {
1719 /// We can eliminate hidden site activities straight away
1720 if (!empty($cm) && !$cm->visible and !has_capability('moodle/course:viewhiddenactivities',
1721 get_context_instance(CONTEXT_SYSTEM, SITEID))) {
1722 redirect($CFG->wwwroot, get_string('activityiscurrentlyhidden'));
1724 return;
1726 } else {
1727 /// Check if the user can be in a particular course
1728 if (!$context = get_context_instance(CONTEXT_COURSE, $COURSE->id)) {
1729 print_error('nocontext');
1732 if (empty($USER->switchrole[$context->id]) &&
1733 !($COURSE->visible && course_parent_visible($COURSE)) &&
1734 !has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $COURSE->id)) ){
1735 print_header_simple();
1736 notice(get_string('coursehidden'), $CFG->wwwroot .'/');
1739 /// Non-guests who don't currently have access, check if they can be allowed in as a guest
1741 if ($USER->username != 'guest' and !has_capability('moodle/course:view', $context)) {
1742 if ($COURSE->guest == 1) {
1743 // Temporarily assign them guest role for this context, if it fails later user is asked to enrol
1744 has_capability('clearcache'); // Must clear cache
1745 $guestcaps = get_role_context_caps($CFG->guestroleid, $context);
1746 $USER->capabilities = merge_role_caps($USER->capabilities, $guestcaps);
1750 /// If the user is a guest then treat them according to the course policy about guests
1752 if (has_capability('moodle/legacy:guest', $context, NULL, false)) {
1753 switch ($COURSE->guest) { /// Check course policy about guest access
1755 case 1: /// Guests always allowed
1756 if (!has_capability('moodle/course:view', $context)) { // Prohibited by capability
1757 print_header_simple();
1758 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1760 if (!empty($cm) and !$cm->visible) { // Not allowed to see module, send to course page
1761 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course,
1762 get_string('activityiscurrentlyhidden'));
1765 return; // User is allowed to see this course
1767 break;
1769 case 2: /// Guests allowed with key
1770 if (!empty($USER->enrolkey[$COURSE->id])) { // Set by enrol/manual/enrol.php
1771 return true;
1773 // otherwise drop through to logic below (--> enrol.php)
1774 break;
1776 default: /// Guests not allowed
1777 print_header_simple('', '', get_string('loggedinasguest'));
1778 if (empty($USER->switchrole[$context->id])) { // Normal guest
1779 notice(get_string('guestsnotallowed', '', format_string($COURSE->fullname)), "$CFG->wwwroot/login/index.php");
1780 } else {
1781 notify(get_string('guestsnotallowed', '', format_string($COURSE->fullname)));
1782 echo '<div class="notifyproblem">'.switchroles_form($COURSE->id).'</div>';
1783 print_footer($COURSE);
1784 exit;
1786 break;
1789 /// For non-guests, check if they have course view access
1791 } else if (has_capability('moodle/course:view', $context)) {
1792 if (!empty($USER->realuser)) { // Make sure the REAL person can also access this course
1793 if (!has_capability('moodle/course:view', $context, $USER->realuser)) {
1794 print_header_simple();
1795 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
1799 /// Make sure they can read this activity too, if specified
1801 if (!empty($cm) and !$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $context)) {
1802 redirect($CFG->wwwroot.'/course/view.php?id='.$cm->course, get_string('activityiscurrentlyhidden'));
1804 return; // User is allowed to see this course
1809 /// Currently not enrolled in the course, so see if they want to enrol
1810 $SESSION->wantsurl = $FULLME;
1811 redirect($CFG->wwwroot .'/course/enrol.php?id='. $COURSE->id);
1812 die;
1819 * This function just makes sure a user is logged out.
1821 * @uses $CFG
1822 * @uses $USER
1824 function require_logout() {
1826 global $USER, $CFG, $SESSION;
1828 if (isloggedin()) {
1829 add_to_log(SITEID, "user", "logout", "view.php?id=$USER->id&course=".SITEID, $USER->id, 0, $USER->id);
1831 $authsequence = get_enabled_auth_plugins(); // auths, in sequence
1832 foreach($authsequence as $authname) {
1833 $authplugin = get_auth_plugin($authname);
1834 $authplugin->prelogout_hook();
1838 if (ini_get_bool("register_globals") and check_php_version("4.3.0")) {
1839 // This method is just to try to avoid silly warnings from PHP 4.3.0
1840 session_unregister("USER");
1841 session_unregister("SESSION");
1844 // Initialize variable to pass-by-reference to headers_sent(&$file, &$line)
1845 $file = $line = null;
1846 if (headers_sent($file, $line)) {
1847 error_log('MoodleSessionTest cookie could not be set in moodlelib.php:'.__LINE__);
1848 error_log('Headers were already sent in file: '.$file.' on line '.$line);
1849 } else {
1850 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
1853 unset($_SESSION['USER']);
1854 unset($_SESSION['SESSION']);
1856 unset($SESSION);
1857 unset($USER);
1862 * This is a weaker version of {@link require_login()} which only requires login
1863 * when called from within a course rather than the site page, unless
1864 * the forcelogin option is turned on.
1866 * @uses $CFG
1867 * @param mixed $courseorid The course object or id in question
1868 * @param bool $autologinguest Allow autologin guests if that is wanted
1869 * @param object $cm Course activity module if known
1871 function require_course_login($courseorid, $autologinguest=true, $cm=null) {
1872 global $CFG;
1873 if (!empty($CFG->forcelogin)) {
1874 // login required for both SITE and courses
1875 require_login($courseorid, $autologinguest, $cm);
1877 } else if (!empty($cm) and !$cm->visible) {
1878 // always login for hidden activities
1879 require_login($courseorid, $autologinguest, $cm);
1881 } else if ((is_object($courseorid) and $courseorid->id == SITEID)
1882 or (!is_object($courseorid) and $courseorid == SITEID)) {
1883 //login for SITE not required
1884 return;
1886 } else {
1887 // course login always required
1888 require_login($courseorid, $autologinguest, $cm);
1893 * Modify the user table by setting the currently logged in user's
1894 * last login to now.
1896 * @uses $USER
1897 * @return bool
1899 function update_user_login_times() {
1900 global $USER;
1902 $user = new object();
1903 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
1904 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1906 $user->id = $USER->id;
1908 return update_record('user', $user);
1912 * Determines if a user has completed setting up their account.
1914 * @param user $user A {@link $USER} object to test for the existance of a valid name and email
1915 * @return bool
1917 function user_not_fully_set_up($user) {
1918 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)));
1921 function over_bounce_threshold($user) {
1923 global $CFG;
1925 if (empty($CFG->handlebounces)) {
1926 return false;
1928 // set sensible defaults
1929 if (empty($CFG->minbounces)) {
1930 $CFG->minbounces = 10;
1932 if (empty($CFG->bounceratio)) {
1933 $CFG->bounceratio = .20;
1935 $bouncecount = 0;
1936 $sendcount = 0;
1937 if ($bounce = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1938 $bouncecount = $bounce->value;
1940 if ($send = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1941 $sendcount = $send->value;
1943 return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
1947 * @param $user - object containing an id
1948 * @param $reset - will reset the count to 0
1950 function set_send_count($user,$reset=false) {
1951 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_send_count')) {
1952 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1953 update_record('user_preferences',$pref);
1955 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1956 // make a new one
1957 $pref->name = 'email_send_count';
1958 $pref->value = 1;
1959 $pref->userid = $user->id;
1960 insert_record('user_preferences',$pref, false);
1965 * @param $user - object containing an id
1966 * @param $reset - will reset the count to 0
1968 function set_bounce_count($user,$reset=false) {
1969 if ($pref = get_record('user_preferences','userid',$user->id,'name','email_bounce_count')) {
1970 $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
1971 update_record('user_preferences',$pref);
1973 else if (!empty($reset)) { // if it's not there and we're resetting, don't bother.
1974 // make a new one
1975 $pref->name = 'email_bounce_count';
1976 $pref->value = 1;
1977 $pref->userid = $user->id;
1978 insert_record('user_preferences',$pref, false);
1983 * Keeps track of login attempts
1985 * @uses $SESSION
1987 function update_login_count() {
1989 global $SESSION;
1991 $max_logins = 10;
1993 if (empty($SESSION->logincount)) {
1994 $SESSION->logincount = 1;
1995 } else {
1996 $SESSION->logincount++;
1999 if ($SESSION->logincount > $max_logins) {
2000 unset($SESSION->wantsurl);
2001 error(get_string('errortoomanylogins'));
2006 * Resets login attempts
2008 * @uses $SESSION
2010 function reset_login_count() {
2011 global $SESSION;
2013 $SESSION->logincount = 0;
2016 function sync_metacourses() {
2018 global $CFG;
2020 if (!$courses = get_records('course', 'metacourse', 1)) {
2021 return;
2024 foreach ($courses as $course) {
2025 sync_metacourse($course);
2030 * Goes through all enrolment records for the courses inside the metacourse and sync with them.
2032 * @param mixed $course the metacourse to synch. Either the course object itself, or the courseid.
2034 function sync_metacourse($course) {
2035 global $CFG;
2037 // Check the course is valid.
2038 if (!is_object($course)) {
2039 if (!$course = get_record('course', 'id', $course)) {
2040 return false; // invalid course id
2044 // Check that we actually have a metacourse.
2045 if (empty($course->metacourse)) {
2046 return false;
2049 // Get a list of roles that should not be synced.
2050 if (!empty($CFG->nonmetacoursesyncroleids)) {
2051 $roleexclusions = 'ra.roleid NOT IN (' . $CFG->nonmetacoursesyncroleids . ') AND';
2052 } else {
2053 $roleexclusions = '';
2056 // Get the context of the metacourse.
2057 $context = get_context_instance(CONTEXT_COURSE, $course->id); // SITEID can not be a metacourse
2059 // We do not ever want to unassign the list of metacourse manager, so get a list of them.
2060 if ($users = get_users_by_capability($context, 'moodle/course:managemetacourse')) {
2061 $managers = array_keys($users);
2062 } else {
2063 $managers = array();
2066 // Get assignments of a user to a role that exist in a child course, but
2067 // not in the meta coure. That is, get a list of the assignments that need to be made.
2068 if (!$assignments = get_records_sql("
2069 SELECT
2070 ra.id, ra.roleid, ra.userid
2071 FROM
2072 {$CFG->prefix}role_assignments ra,
2073 {$CFG->prefix}context con,
2074 {$CFG->prefix}course_meta cm
2075 WHERE
2076 ra.contextid = con.id AND
2077 con.contextlevel = " . CONTEXT_COURSE . " AND
2078 con.instanceid = cm.child_course AND
2079 cm.parent_course = {$course->id} AND
2080 $roleexclusions
2081 NOT EXISTS (
2082 SELECT 1 FROM
2083 {$CFG->prefix}role_assignments ra2
2084 WHERE
2085 ra2.userid = ra.userid AND
2086 ra2.roleid = ra.roleid AND
2087 ra2.contextid = {$context->id}
2089 ")) {
2090 $assignments = array();
2093 // Get assignments of a user to a role that exist in the meta course, but
2094 // not in any child courses. That is, get a list of the unassignments that need to be made.
2095 if (!$unassignments = get_records_sql("
2096 SELECT
2097 ra.id, ra.roleid, ra.userid
2098 FROM
2099 {$CFG->prefix}role_assignments ra
2100 WHERE
2101 ra.contextid = {$context->id} AND
2102 $roleexclusions
2103 NOT EXISTS (
2104 SELECT 1 FROM
2105 {$CFG->prefix}role_assignments ra2,
2106 {$CFG->prefix}context con2,
2107 {$CFG->prefix}course_meta cm
2108 WHERE
2109 ra2.userid = ra.userid AND
2110 ra2.roleid = ra.roleid AND
2111 ra2.contextid = con2.id AND
2112 con2.contextlevel = " . CONTEXT_COURSE . " AND
2113 con2.instanceid = cm.child_course AND
2114 cm.parent_course = {$course->id}
2116 ")) {
2117 $unassignments = array();
2120 $success = true;
2122 // Make the unassignments, if they are not managers.
2123 foreach ($unassignments as $unassignment) {
2124 if (!in_array($unassignment->userid, $managers)) {
2125 $success = role_unassign($unassignment->roleid, $unassignment->userid, 0, $context->id) && $success;
2129 // Make the assignments.
2130 foreach ($assignments as $assignment) {
2131 $success = role_assign($assignment->roleid, $assignment->userid, 0, $context->id) && $success;
2134 return $success;
2136 // TODO: finish timeend and timestart
2137 // maybe we could rely on cron job to do the cleaning from time to time
2141 * Adds a record to the metacourse table and calls sync_metacoures
2143 function add_to_metacourse ($metacourseid, $courseid) {
2145 if (!$metacourse = get_record("course","id",$metacourseid)) {
2146 return false;
2149 if (!$course = get_record("course","id",$courseid)) {
2150 return false;
2153 if (!$record = get_record("course_meta","parent_course",$metacourseid,"child_course",$courseid)) {
2154 $rec = new object();
2155 $rec->parent_course = $metacourseid;
2156 $rec->child_course = $courseid;
2157 if (!insert_record('course_meta',$rec)) {
2158 return false;
2160 return sync_metacourse($metacourseid);
2162 return true;
2167 * Removes the record from the metacourse table and calls sync_metacourse
2169 function remove_from_metacourse($metacourseid, $courseid) {
2171 if (delete_records('course_meta','parent_course',$metacourseid,'child_course',$courseid)) {
2172 return sync_metacourse($metacourseid);
2174 return false;
2179 * Determines if a user is currently logged in
2181 * @uses $USER
2182 * @return bool
2184 function isloggedin() {
2185 global $USER;
2187 return (!empty($USER->id));
2191 * Determines if a user is logged in as real guest user with username 'guest'.
2192 * This function is similar to original isguest() in 1.6 and earlier.
2193 * Current isguest() is deprecated - do not use it anymore.
2195 * @param $user mixed user object or id, $USER if not specified
2196 * @return bool true if user is the real guest user, false if not logged in or other user
2198 function isguestuser($user=NULL) {
2199 global $USER;
2200 if ($user === NULL) {
2201 $user = $USER;
2202 } else if (is_numeric($user)) {
2203 $user = get_record('user', 'id', $user, '', '', '', '', 'id, username');
2206 if (empty($user->id)) {
2207 return false; // not logged in, can not be guest
2210 return ($user->username == 'guest');
2214 * Determines if the currently logged in user is in editing mode
2216 * @uses $USER
2217 * @param int $courseid The id of the course being tested
2218 * @param user $user A {@link $USER} object. If null then the currently logged in user is used.
2219 * @return bool
2221 function isediting($courseid, $user=NULL) {
2222 global $USER;
2223 if (!$user) {
2224 $user = $USER;
2226 if (empty($user->editing)) {
2227 return false;
2230 $capcheck = false;
2231 $coursecontext = get_context_instance(CONTEXT_COURSE, $courseid);
2233 if (has_capability('moodle/course:manageactivities', $coursecontext) ||
2234 has_capability('moodle/site:manageblocks', $coursecontext)) {
2235 $capcheck = true;
2236 } else {
2237 // loop through all child context, see if user has moodle/course:manageactivities or moodle/site:manageblocks
2238 if ($children = get_child_contexts($coursecontext)) {
2239 foreach ($children as $child) {
2240 $childcontext = get_record('context', 'id', $child);
2241 if (has_capability('moodle/course:manageactivities', $childcontext) ||
2242 has_capability('moodle/site:manageblocks', $childcontext)) {
2243 $capcheck = true;
2244 break;
2250 return ($user->editing && $capcheck);
2251 //return ($user->editing and has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $courseid)));
2255 * Determines if the logged in user is currently moving an activity
2257 * @uses $USER
2258 * @param int $courseid The id of the course being tested
2259 * @return bool
2261 function ismoving($courseid) {
2262 global $USER;
2264 if (!empty($USER->activitycopy)) {
2265 return ($USER->activitycopycourse == $courseid);
2267 return false;
2271 * Given an object containing firstname and lastname
2272 * values, this function returns a string with the
2273 * full name of the person.
2274 * The result may depend on system settings
2275 * or language. 'override' will force both names
2276 * to be used even if system settings specify one.
2278 * @uses $CFG
2279 * @uses $SESSION
2280 * @param object $user A {@link $USER} object to get full name of
2281 * @param bool $override If true then the name will be first name followed by last name rather than adhering to fullnamedisplay setting.
2283 function fullname($user, $override=false) {
2285 global $CFG, $SESSION;
2287 if (!isset($user->firstname) and !isset($user->lastname)) {
2288 return '';
2291 if (!$override) {
2292 if (!empty($CFG->forcefirstname)) {
2293 $user->firstname = $CFG->forcefirstname;
2295 if (!empty($CFG->forcelastname)) {
2296 $user->lastname = $CFG->forcelastname;
2300 if (!empty($SESSION->fullnamedisplay)) {
2301 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
2304 if ($CFG->fullnamedisplay == 'firstname lastname') {
2305 return $user->firstname .' '. $user->lastname;
2307 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
2308 return $user->lastname .' '. $user->firstname;
2310 } else if ($CFG->fullnamedisplay == 'firstname') {
2311 if ($override) {
2312 return get_string('fullnamedisplay', '', $user);
2313 } else {
2314 return $user->firstname;
2318 return get_string('fullnamedisplay', '', $user);
2322 * Sets a moodle cookie with an encrypted string
2324 * @uses $CFG
2325 * @uses DAYSECS
2326 * @uses HOURSECS
2327 * @param string $thing The string to encrypt and place in a cookie
2329 function set_moodle_cookie($thing) {
2330 global $CFG;
2332 if ($thing == 'guest') { // Ignore guest account
2333 return;
2336 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2338 $days = 60;
2339 $seconds = DAYSECS*$days;
2341 setCookie($cookiename, '', time() - HOURSECS, '/');
2342 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
2346 * Gets a moodle cookie with an encrypted string
2348 * @uses $CFG
2349 * @return string
2351 function get_moodle_cookie() {
2352 global $CFG;
2354 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
2356 if (empty($_COOKIE[$cookiename])) {
2357 return '';
2358 } else {
2359 $thing = rc4decrypt($_COOKIE[$cookiename]);
2360 return ($thing == 'guest') ? '': $thing; // Ignore guest account
2365 * Returns whether a given authentication plugin exists.
2367 * @uses $CFG
2368 * @param string $auth Form of authentication to check for. Defaults to the
2369 * global setting in {@link $CFG}.
2370 * @return boolean Whether the plugin is available.
2372 function exists_auth_plugin($auth) {
2373 global $CFG;
2375 if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
2376 return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
2378 return false;
2382 * Checks if a given plugin is in the list of enabled authentication plugins.
2384 * @param string $auth Authentication plugin.
2385 * @return boolean Whether the plugin is enabled.
2387 function is_enabled_auth($auth) {
2388 if (empty($auth)) {
2389 return false;
2392 $enabled = get_enabled_auth_plugins();
2394 return in_array($auth, $enabled);
2398 * Returns an authentication plugin instance.
2400 * @uses $CFG
2401 * @param string $auth name of authentication plugin
2402 * @return object An instance of the required authentication plugin.
2404 function get_auth_plugin($auth) {
2405 global $CFG;
2407 // check the plugin exists first
2408 if (! exists_auth_plugin($auth)) {
2409 error("Authentication plugin '$auth' not found.");
2412 // return auth plugin instance
2413 require_once "{$CFG->dirroot}/auth/$auth/auth.php";
2414 $class = "auth_plugin_$auth";
2415 return new $class;
2419 * Returns array of active auth plugins.
2421 * @param bool $fix fix $CFG->auth if needed
2422 * @return array
2424 function get_enabled_auth_plugins($fix=false) {
2425 global $CFG;
2427 $default = array('manual', 'nologin');
2429 if (empty($CFG->auth)) {
2430 $auths = array();
2431 } else {
2432 $auths = explode(',', $CFG->auth);
2435 if ($fix) {
2436 $auths = array_unique($auths);
2437 foreach($auths as $k=>$authname) {
2438 if (!exists_auth_plugin($authname) or in_array($authname, $default)) {
2439 unset($auths[$k]);
2442 $newconfig = implode(',', $auths);
2443 if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
2444 set_config('auth', $newconfig);
2448 return (array_merge($default, $auths));
2452 * Returns true if an internal authentication method is being used.
2453 * if method not specified then, global default is assumed
2455 * @uses $CFG
2456 * @param string $auth Form of authentication required
2457 * @return bool
2459 function is_internal_auth($auth) {
2460 $authplugin = get_auth_plugin($auth); // throws error if bad $auth
2461 return $authplugin->is_internal();
2465 * Returns an array of user fields
2467 * @uses $CFG
2468 * @uses $db
2469 * @return array User field/column names
2471 function get_user_fieldnames() {
2473 global $CFG, $db;
2475 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
2476 unset($fieldarray['ID']);
2478 return $fieldarray;
2482 * Creates the default "guest" user. Used both from
2483 * admin/index.php and login/index.php
2484 * @return mixed user object created or boolean false if the creation has failed
2486 function create_guest_record() {
2488 global $CFG;
2490 $guest->auth = 'manual';
2491 $guest->username = 'guest';
2492 $guest->password = hash_internal_user_password('guest');
2493 $guest->firstname = addslashes(get_string('guestuser'));
2494 $guest->lastname = ' ';
2495 $guest->email = 'root@localhost';
2496 $guest->description = addslashes(get_string('guestuserinfo'));
2497 $guest->mnethostid = $CFG->mnet_localhost_id;
2498 $guest->confirmed = 1;
2499 $guest->lang = $CFG->lang;
2500 $guest->timemodified= time();
2502 if (! $guest->id = insert_record("user", $guest)) {
2503 return false;
2506 return $guest;
2510 * Creates a bare-bones user record
2512 * @uses $CFG
2513 * @param string $username New user's username to add to record
2514 * @param string $password New user's password to add to record
2515 * @param string $auth Form of authentication required
2516 * @return object A {@link $USER} object
2517 * @todo Outline auth types and provide code example
2519 function create_user_record($username, $password, $auth='manual') {
2520 global $CFG;
2522 //just in case check text case
2523 $username = trim(moodle_strtolower($username));
2525 $authplugin = get_auth_plugin($auth);
2527 if ($newinfo = $authplugin->get_userinfo($username)) {
2528 $newinfo = truncate_userinfo($newinfo);
2529 foreach ($newinfo as $key => $value){
2530 $newuser->$key = addslashes($value);
2534 if (!empty($newuser->email)) {
2535 if (email_is_not_allowed($newuser->email)) {
2536 unset($newuser->email);
2540 $newuser->auth = $auth;
2541 $newuser->username = $username;
2543 // fix for MDL-8480
2544 // user CFG lang for user if $newuser->lang is empty
2545 // or $user->lang is not an installed language
2546 $sitelangs = array_keys(get_list_of_languages());
2547 if (empty($newuser->lang) || !in_array($newuser->lang, $sitelangs)) {
2548 $newuser -> lang = $CFG->lang;
2550 $newuser->confirmed = 1;
2551 $newuser->lastip = getremoteaddr();
2552 $newuser->timemodified = time();
2553 $newuser->mnethostid = $CFG->mnet_localhost_id;
2555 if (insert_record('user', $newuser)) {
2556 $user = get_complete_user_data('username', $newuser->username);
2557 if(!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})){
2558 set_user_preference('auth_forcepasswordchange', 1, $user->id);
2560 update_internal_user_password($user, $password);
2561 return $user;
2563 return false;
2567 * Will update a local user record from an external source
2569 * @uses $CFG
2570 * @param string $username New user's username to add to record
2571 * @return user A {@link $USER} object
2573 function update_user_record($username, $authplugin) {
2574 $username = trim(moodle_strtolower($username)); /// just in case check text case
2576 $oldinfo = get_record('user', 'username', $username, '','','','', 'username, auth');
2577 $userauth = get_auth_plugin($oldinfo->auth);
2579 if ($newinfo = $userauth->get_userinfo($username)) {
2580 $newinfo = truncate_userinfo($newinfo);
2581 foreach ($newinfo as $key => $value){
2582 $confkey = 'field_updatelocal_' . $key;
2583 if (!empty($userauth->config->$confkey) and $userauth->config->$confkey === 'onlogin') {
2584 $value = addslashes(stripslashes($value)); // Just in case
2585 set_field('user', $key, $value, 'username', $username)
2586 or error_log("Error updating $key for $username");
2591 return get_complete_user_data('username', $username);
2594 function truncate_userinfo($info) {
2595 /// will truncate userinfo as it comes from auth_get_userinfo (from external auth)
2596 /// which may have large fields
2598 // define the limits
2599 $limit = array(
2600 'username' => 100,
2601 'idnumber' => 64,
2602 'firstname' => 100,
2603 'lastname' => 100,
2604 'email' => 100,
2605 'icq' => 15,
2606 'phone1' => 20,
2607 'phone2' => 20,
2608 'institution' => 40,
2609 'department' => 30,
2610 'address' => 70,
2611 'city' => 20,
2612 'country' => 2,
2613 'url' => 255,
2616 // apply where needed
2617 foreach (array_keys($info) as $key) {
2618 if (!empty($limit[$key])) {
2619 $info[$key] = trim(substr($info[$key],0, $limit[$key]));
2623 return $info;
2627 * Retrieve the guest user object
2629 * @uses $CFG
2630 * @return user A {@link $USER} object
2632 function guest_user() {
2633 global $CFG;
2635 if ($newuser = get_record('user', 'username', 'guest', 'mnethostid', $CFG->mnet_localhost_id)) {
2636 $newuser->confirmed = 1;
2637 $newuser->lang = $CFG->lang;
2638 $newuser->lastip = getremoteaddr();
2641 return $newuser;
2645 * Given a username and password, this function looks them
2646 * up using the currently selected authentication mechanism,
2647 * and if the authentication is successful, it returns a
2648 * valid $user object from the 'user' table.
2650 * Uses auth_ functions from the currently active auth module
2652 * @uses $CFG
2653 * @param string $username User's username (with system magic quotes)
2654 * @param string $password User's password (with system magic quotes)
2655 * @return user|flase A {@link $USER} object or false if error
2657 function authenticate_user_login($username, $password) {
2659 global $CFG;
2661 $authsenabled = get_enabled_auth_plugins();
2663 if ($user = get_complete_user_data('username', $username)) {
2664 $auth = empty($user->auth) ? 'manual' : $user->auth; // use manual if auth not set
2665 if ($auth=='nologin' or !is_enabled_auth($auth)) {
2666 add_to_log(0, 'login', 'error', 'index.php', $username);
2667 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Disabled Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2668 return false;
2670 if (!empty($user->deleted)) {
2671 add_to_log(0, 'login', 'error', 'index.php', $username);
2672 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Deleted Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2673 return false;
2675 $auths = array($auth);
2677 } else {
2678 $auths = $authsenabled;
2679 $user = new object();
2680 $user->id = 0; // User does not exist
2683 foreach ($auths as $auth) {
2684 $authplugin = get_auth_plugin($auth);
2686 // on auth fail fall through to the next plugin
2687 if (!$authplugin->user_login($username, $password)) {
2688 continue;
2691 // successful authentication
2692 if ($user->id) { // User already exists in database
2693 if (empty($user->auth)) { // For some reason auth isn't set yet
2694 set_field('user', 'auth', $auth, 'username', $username);
2695 $user->auth = $auth;
2698 update_internal_user_password($user, $password); // just in case salt or encoding were changed (magic quotes too one day)
2700 if (!$authplugin->is_internal()) { // update user record from external DB
2701 $user = update_user_record($username, get_auth_plugin($user->auth));
2703 } else {
2704 // if user not found, create him
2705 $user = create_user_record($username, $password, $auth);
2708 $authplugin->sync_roles($user);
2710 foreach ($authsenabled as $hau) {
2711 $hauth = get_auth_plugin($hau);
2712 $hauth->user_authenticated_hook($user, $username, $password);
2715 /// Log in to a second system if necessary
2716 /// NOTICE: /sso/ will be moved to auth and deprecated soon; use user_authenticated_hook() instead
2717 if (!empty($CFG->sso)) {
2718 include_once($CFG->dirroot .'/sso/'. $CFG->sso .'/lib.php');
2719 if (function_exists('sso_user_login')) {
2720 if (!sso_user_login($username, $password)) { // Perform the signon process
2721 notify('Second sign-on failed');
2726 return $user;
2730 // failed if all the plugins have failed
2731 add_to_log(0, 'login', 'error', 'index.php', $username);
2732 error_log('[client '.$_SERVER['REMOTE_ADDR']."] $CFG->wwwroot Failed Login: $username ".$_SERVER['HTTP_USER_AGENT']);
2733 return false;
2737 * Compare password against hash stored in internal user table.
2738 * If necessary it also updates the stored hash to new format.
2740 * @param object user
2741 * @param string plain text password
2742 * @return bool is password valid?
2744 function validate_internal_user_password(&$user, $password) {
2745 global $CFG;
2747 if (!isset($CFG->passwordsaltmain)) {
2748 $CFG->passwordsaltmain = '';
2751 $validated = false;
2753 // get password original encoding in case it was not updated to unicode yet
2754 $textlib = textlib_get_instance();
2755 $convpassword = $textlib->convert($password, 'utf-8', get_string('oldcharset'));
2757 if ($user->password == md5($password.$CFG->passwordsaltmain) or $user->password == md5($password)
2758 or $user->password == md5($convpassword.$CFG->passwordsaltmain) or $user->password == md5($convpassword)) {
2759 $validated = true;
2760 } else {
2761 for ($i=1; $i<=20; $i++) { //20 alternative salts should be enough, right?
2762 $alt = 'passwordsaltalt'.$i;
2763 if (!empty($CFG->$alt)) {
2764 if ($user->password == md5($password.$CFG->$alt) or $user->password == md5($convpassword.$CFG->$alt)) {
2765 $validated = true;
2766 break;
2772 if ($validated) {
2773 // force update of password hash using latest main password salt and encoding if needed
2774 update_internal_user_password($user, $password);
2777 return $validated;
2781 * Calculate hashed value from password using current hash mechanism.
2783 * @param string password
2784 * @return string password hash
2786 function hash_internal_user_password($password) {
2787 global $CFG;
2789 if (isset($CFG->passwordsaltmain)) {
2790 return md5($password.$CFG->passwordsaltmain);
2791 } else {
2792 return md5($password);
2797 * Update pssword hash in user object.
2799 * @param object user
2800 * @param string plain text password
2801 * @param bool store changes also in db, default true
2802 * @return true if hash changed
2804 function update_internal_user_password(&$user, $password) {
2805 global $CFG;
2807 $authplugin = get_auth_plugin($user->auth);
2808 if (!empty($authplugin->config->preventpassindb)) {
2809 $hashedpassword = 'not cached';
2810 } else {
2811 $hashedpassword = hash_internal_user_password($password);
2814 return set_field('user', 'password', $hashedpassword, 'id', $user->id);
2818 * Get a complete user record, which includes all the info
2819 * in the user record
2820 * Intended for setting as $USER session variable
2822 * @uses $CFG
2823 * @uses SITEID
2824 * @param string $field The user field to be checked for a given value.
2825 * @param string $value The value to match for $field.
2826 * @return user A {@link $USER} object.
2828 function get_complete_user_data($field, $value, $mnethostid=null) {
2830 global $CFG;
2832 if (!$field || !$value) {
2833 return false;
2836 /// Build the WHERE clause for an SQL query
2838 $constraints = $field .' = \''. $value .'\' AND deleted <> \'1\'';
2840 if (is_null($mnethostid)) {
2841 // if null, we restrict to local users
2842 // ** testing for local user can be done with
2843 // mnethostid = $CFG->mnet_localhost_id
2844 // or with
2845 // auth != 'mnet'
2846 // but the first one is FAST with our indexes
2847 $mnethostid = $CFG->mnet_localhost_id;
2849 $mnethostid = (int)$mnethostid;
2850 $constraints .= ' AND mnethostid = \''.$mnethostid.'\'';
2852 /// Get all the basic user data
2854 if (! $user = get_record_select('user', $constraints)) {
2855 return false;
2858 /// Get various settings and preferences
2860 if ($displays = get_records('course_display', 'userid', $user->id)) {
2861 foreach ($displays as $display) {
2862 $user->display[$display->course] = $display->display;
2866 $user->preference = get_user_preferences(null, null, $user->id);
2868 if ($lastaccesses = get_records('user_lastaccess', 'userid', $user->id)) {
2869 foreach ($lastaccesses as $lastaccess) {
2870 $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
2874 if ($groupids = groups_get_all_groups_for_user($user->id)) { //TODO:check.
2875 foreach ($groupids as $groupid) {
2876 $courseid = groups_get_course($groupid);
2877 //change this to 2D array so we can put multiple groups in a course
2878 $user->groupmember[$courseid][] = $groupid;
2882 /// Rewrite some variables if necessary
2883 if (!empty($user->description)) {
2884 $user->description = true; // No need to cart all of it around
2886 if ($user->username == 'guest') {
2887 $user->lang = $CFG->lang; // Guest language always same as site
2888 $user->firstname = get_string('guestuser'); // Name always in current language
2889 $user->lastname = ' ';
2892 $user->sesskey = random_string(10);
2893 $user->sessionIP = md5(getremoteaddr()); // Store the current IP in the session
2895 return $user;
2899 * @uses $CFG
2900 * @param string $password the password to be checked agains the password policy
2901 * @param string $errmsg the error message to display when the password doesn't comply with the policy.
2902 * @return bool true if the password is valid according to the policy. false otherwise.
2904 function check_password_policy($password, &$errmsg) {
2905 global $CFG;
2907 if (empty($CFG->passwordpolicy)) {
2908 return true;
2911 $textlib = new textlib();
2912 $errmsg = '';
2913 if ($textlib->strlen($password) < $CFG->minpasswordlength) {
2914 $errmsg = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
2916 } else if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
2917 $errmsg = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
2919 } else if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
2920 $errmsg = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
2922 } else if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
2923 $errmsg = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
2925 } else if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
2926 $errmsg = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
2928 } else if ($password == 'admin' or $password == 'password') {
2929 $errmsg = get_string('unsafepassword');
2932 if ($errmsg == '') {
2933 return true;
2934 } else {
2935 return false;
2941 * When logging in, this function is run to set certain preferences
2942 * for the current SESSION
2944 function set_login_session_preferences() {
2945 global $SESSION, $CFG;
2947 $SESSION->justloggedin = true;
2949 unset($SESSION->lang);
2951 // Restore the calendar filters, if saved
2952 if (intval(get_user_preferences('calendar_persistflt', 0))) {
2953 include_once($CFG->dirroot.'/calendar/lib.php');
2954 calendar_set_filters_status(get_user_preferences('calendav_savedflt', 0xff));
2960 * Delete a course, including all related data from the database,
2961 * and any associated files from the moodledata folder.
2963 * @param int $courseid The id of the course to delete.
2964 * @param bool $showfeedback Whether to display notifications of each action the function performs.
2965 * @return bool true if all the removals succeeded. false if there were any failures. If this
2966 * method returns false, some of the removals will probably have succeeded, and others
2967 * failed, but you have no way of knowing which.
2969 function delete_course($courseid, $showfeedback = true) {
2970 global $CFG;
2971 $result = true;
2973 if (!remove_course_contents($courseid, $showfeedback)) {
2974 if ($showfeedback) {
2975 notify("An error occurred while deleting some of the course contents.");
2977 $result = false;
2980 if (!delete_records("course", "id", $courseid)) {
2981 if ($showfeedback) {
2982 notify("An error occurred while deleting the main course record.");
2984 $result = false;
2987 if (!delete_records('context', 'contextlevel', CONTEXT_COURSE, 'instanceid', $courseid)) {
2988 if ($showfeedback) {
2989 notify("An error occurred while deleting the main context record.");
2991 $result = false;
2994 if (!fulldelete($CFG->dataroot.'/'.$courseid)) {
2995 if ($showfeedback) {
2996 notify("An error occurred while deleting the course files.");
2998 $result = false;
3001 return $result;
3005 * Clear a course out completely, deleting all content
3006 * but don't delete the course itself
3008 * @uses $CFG
3009 * @param int $courseid The id of the course that is being deleted
3010 * @param bool $showfeedback Whether to display notifications of each action the function performs.
3011 * @return bool true if all the removals succeeded. false if there were any failures. If this
3012 * method returns false, some of the removals will probably have succeeded, and others
3013 * failed, but you have no way of knowing which.
3015 function remove_course_contents($courseid, $showfeedback=true) {
3017 global $CFG;
3019 $result = true;
3021 if (! $course = get_record('course', 'id', $courseid)) {
3022 error('Course ID was incorrect (can\'t find it)');
3025 $strdeleted = get_string('deleted');
3027 /// First delete every instance of every module
3029 if ($allmods = get_records('modules') ) {
3030 foreach ($allmods as $mod) {
3031 $modname = $mod->name;
3032 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3033 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
3034 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
3035 $count=0;
3036 if (file_exists($modfile)) {
3037 include_once($modfile);
3038 if (function_exists($moddelete)) {
3039 if ($instances = get_records($modname, 'course', $course->id)) {
3040 foreach ($instances as $instance) {
3041 if ($cm = get_coursemodule_from_instance($modname, $instance->id, $course->id)) {
3042 delete_context(CONTEXT_MODULE, $cm->id);
3044 if ($moddelete($instance->id)) {
3045 $count++;
3047 } else {
3048 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. format_string($instance->name) .')');
3049 $result = false;
3053 } else {
3054 notify('Function '. $moddelete() .'doesn\'t exist!');
3055 $result = false;
3058 if (function_exists($moddeletecourse)) {
3059 $moddeletecourse($course, $showfeedback);
3062 if ($showfeedback) {
3063 notify($strdeleted .' '. $count .' x '. $modname);
3066 } else {
3067 error('No modules are installed!');
3070 /// Give local code a chance to delete its references to this course.
3071 require_once('locallib.php');
3072 notify_local_delete_course($courseid, $showfeedback);
3074 /// Delete course blocks
3076 if ($blocks = get_records_sql("SELECT *
3077 FROM {$CFG->prefix}block_instance
3078 WHERE pagetype = '".PAGE_COURSE_VIEW."'
3079 AND pageid = $course->id")) {
3080 if (delete_records('block_instance', 'pagetype', PAGE_COURSE_VIEW, 'pageid', $course->id)) {
3081 if ($showfeedback) {
3082 notify($strdeleted .' block_instance');
3085 require_once($CFG->libdir.'/blocklib.php');
3086 foreach ($blocks as $block) { /// Delete any associated contexts for this block
3088 // Block instances are rarely created. Since the block instance is gone from the above delete
3089 // statement, calling delete_context() will generate a warning as get_context_instance could
3090 // no longer create the context as the block is already gone.
3091 if (record_exists('context', 'contextlevel', CONTEXT_BLOCK, 'instanceid', $block->id)) {
3092 delete_context(CONTEXT_BLOCK, $block->id);
3095 // fix for MDL-7164
3096 // Get the block object and call instance_delete()
3097 if (!$record = blocks_get_record($block->blockid)) {
3098 $result = false;
3099 continue;
3101 if (!$obj = block_instance($record->name, $block)) {
3102 $result = false;
3103 continue;
3105 // Return value ignored, in core mods this does not do anything, but just in case
3106 // third party blocks might have stuff to clean up
3107 // we execute this anyway
3108 $obj->instance_delete();
3110 } else {
3111 $result = false;
3115 /// Delete any groups, removing members and grouping/course links first.
3116 //TODO: If groups or groupings are to be shared between courses, think again!
3117 if ($groupids = groups_get_groups($course->id)) {
3118 foreach ($groupids as $groupid) {
3119 if (groups_remove_all_members($groupid)) {
3120 if ($showfeedback) {
3121 notify($strdeleted .' groups_members');
3123 } else {
3124 $result = false;
3126 /// Delete any associated context for this group ??
3127 delete_context(CONTEXT_GROUP, $groupid);
3129 if (groups_delete_group($groupid)) {
3130 if ($showfeedback) {
3131 notify($strdeleted .' groups');
3133 } else {
3134 $result = false;
3138 /// Delete any groupings.
3139 $result = groups_delete_all_groupings($course->id);
3140 if ($result && $showfeedback) {
3141 notify($strdeleted .' groupings');
3144 /// Delete all related records in other tables that may have a courseid
3145 /// This array stores the tables that need to be cleared, as
3146 /// table_name => column_name that contains the course id.
3148 $tablestoclear = array(
3149 'event' => 'courseid', // Delete events
3150 'log' => 'course', // Delete logs
3151 'course_sections' => 'course', // Delete any course stuff
3152 'course_modules' => 'course',
3153 'grade_category' => 'courseid', // Delete gradebook stuff
3154 'grade_exceptions' => 'courseid',
3155 'grade_item' => 'courseid',
3156 'grade_letter' => 'courseid',
3157 'grade_preferences' => 'courseid',
3158 'backup_courses' => 'courseid', // Delete scheduled backup stuff
3159 'backup_log' => 'courseid'
3161 foreach ($tablestoclear as $table => $col) {
3162 if (delete_records($table, $col, $course->id)) {
3163 if ($showfeedback) {
3164 notify($strdeleted . ' ' . $table);
3166 } else {
3167 $result = false;
3172 /// Clean up metacourse stuff
3174 if ($course->metacourse) {
3175 delete_records("course_meta","parent_course",$course->id);
3176 sync_metacourse($course->id); // have to do it here so the enrolments get nuked. sync_metacourses won't find it without the id.
3177 if ($showfeedback) {
3178 notify("$strdeleted course_meta");
3180 } else {
3181 if ($parents = get_records("course_meta","child_course",$course->id)) {
3182 foreach ($parents as $parent) {
3183 remove_from_metacourse($parent->parent_course,$parent->child_course); // this will do the unenrolments as well.
3185 if ($showfeedback) {
3186 notify("$strdeleted course_meta");
3191 /// Delete questions and question categories
3192 include_once($CFG->libdir.'/questionlib.php');
3193 question_delete_course($course, $showfeedback);
3195 /// Delete all roles and overiddes in the course context (but keep the course context)
3196 if ($courseid != SITEID) {
3197 delete_context(CONTEXT_COURSE, $course->id);
3200 // fix for MDL-9016
3201 // clear the cache because the course context is deleted, and
3202 // we don't want to write assignment, overrides and context_rel table
3203 // with this old context id!
3204 get_context_instance('clearcache');
3205 return $result;
3210 * This function will empty a course of USER data as much as
3211 /// possible. It will retain the activities and the structure
3212 /// of the course.
3214 * @uses $USER
3215 * @uses $SESSION
3216 * @uses $CFG
3217 * @param object $data an object containing all the boolean settings and courseid
3218 * @param bool $showfeedback if false then do it all silently
3219 * @return bool
3220 * @todo Finish documenting this function
3222 function reset_course_userdata($data, $showfeedback=true) {
3224 global $CFG, $USER, $SESSION;
3226 $result = true;
3228 $strdeleted = get_string('deleted');
3230 // Look in every instance of every module for data to delete
3232 if ($allmods = get_records('modules') ) {
3233 foreach ($allmods as $mod) {
3234 $modname = $mod->name;
3235 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
3236 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3237 if (file_exists($modfile)) {
3238 @include_once($modfile);
3239 if (function_exists($moddeleteuserdata)) {
3240 $moddeleteuserdata($data, $showfeedback);
3244 } else {
3245 error('No modules are installed!');
3248 // Delete other stuff
3249 $coursecontext = get_context_instance(CONTEXT_COURSE, $data->courseid);
3251 if (!empty($data->reset_students) or !empty($data->reset_teachers)) {
3252 $teachers = array_keys(get_users_by_capability($coursecontext, 'moodle/course:update'));
3253 $participants = array_keys(get_users_by_capability($coursecontext, 'moodle/course:view'));
3254 $students = array_diff($participants, $teachers);
3256 if (!empty($data->reset_students)) {
3257 foreach ($students as $studentid) {
3258 role_unassign(0, $studentid, 0, $coursecontext->id);
3260 if ($showfeedback) {
3261 notify($strdeleted .' '.get_string('students'), 'notifysuccess');
3264 /// Delete group members (but keep the groups) TODO:check.
3265 if ($groupids = groups_get_groups($data->courseid)) {
3266 foreach ($groupids as $groupid) {
3267 if (groups_remove_all_group_members($groupid)) {
3268 if ($showfeedback) {
3269 notify($strdeleted .' groups_members', 'notifysuccess');
3271 } else {
3272 $result = false;
3278 if (!empty($data->reset_teachers)) {
3279 foreach ($teachers as $teacherid) {
3280 role_unassign(0, $teacherid, 0, $coursecontext->id);
3282 if ($showfeedback) {
3283 notify($strdeleted .' '.get_string('teachers'), 'notifysuccess');
3288 if (!empty($data->reset_groups)) {
3289 if ($groupids = groups_get_groups($data->courseid)) {
3290 foreach ($groupids as $groupid) {
3291 if (groups_delete_group($groupid)) {
3292 if ($showfeedback) {
3293 notify($strdeleted .' groups', 'notifysuccess');
3295 } else {
3296 $result = false;
3302 if (!empty($data->reset_events)) {
3303 if (delete_records('event', 'courseid', $data->courseid)) {
3304 if ($showfeedback) {
3305 notify($strdeleted .' event', 'notifysuccess');
3307 } else {
3308 $result = false;
3312 if (!empty($data->reset_logs)) {
3313 if (delete_records('log', 'course', $data->courseid)) {
3314 if ($showfeedback) {
3315 notify($strdeleted .' log', 'notifysuccess');
3317 } else {
3318 $result = false;
3322 // deletes all role assignments, and local override, these have no courseid in table and needs separate process
3323 $context = get_context_instance(CONTEXT_COURSE, $data->courseid);
3324 delete_records('role_capabilities', 'contextid', $context->id);
3326 return $result;
3330 require_once($CFG->dirroot.'/group/lib.php');
3331 /*TODO: functions moved to /group/lib/legacylib.php
3333 ismember
3334 add_user_to_group
3335 mygroupid
3336 groupmode
3337 set_current_group
3338 ... */
3341 function generate_email_processing_address($modid,$modargs) {
3342 global $CFG;
3344 if (empty($CFG->siteidentifier)) { // Unique site identification code
3345 set_config('siteidentifier', random_string(32));
3348 $header = $CFG->mailprefix . substr(base64_encode(pack('C',$modid)),0,2).$modargs;
3349 return $header . substr(md5($header.$CFG->siteidentifier),0,16).'@'.$CFG->maildomain;
3353 function moodle_process_email($modargs,$body) {
3354 // the first char should be an unencoded letter. We'll take this as an action
3355 switch ($modargs{0}) {
3356 case 'B': { // bounce
3357 list(,$userid) = unpack('V',base64_decode(substr($modargs,1,8)));
3358 if ($user = get_record_select("user","id=$userid","id,email")) {
3359 // check the half md5 of their email
3360 $md5check = substr(md5($user->email),0,16);
3361 if ($md5check == substr($modargs, -16)) {
3362 set_bounce_count($user);
3364 // else maybe they've already changed it?
3367 break;
3368 // maybe more later?
3372 /// CORRESPONDENCE ////////////////////////////////////////////////
3375 * Send an email to a specified user
3377 * @uses $CFG
3378 * @uses $FULLME
3379 * @uses SITEID
3380 * @param user $user A {@link $USER} object
3381 * @param user $from A {@link $USER} object
3382 * @param string $subject plain text subject line of the email
3383 * @param string $messagetext plain text version of the message
3384 * @param string $messagehtml complete html version of the message (optional)
3385 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
3386 * @param string $attachname the name of the file (extension indicates MIME)
3387 * @param bool $usetrueaddress determines whether $from email address should
3388 * be sent out. Will be overruled by user profile setting for maildisplay
3389 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3390 * was blocked by user and "false" if there was another sort of error.
3392 function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true, $replyto='', $replytoname='') {
3394 global $CFG, $FULLME;
3396 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
3398 /// We are going to use textlib services here
3399 $textlib = textlib_get_instance();
3401 if (empty($user)) {
3402 return false;
3405 // skip mail to suspended users
3406 if (isset($user->auth) && $user->auth=='nologin') {
3407 return true;
3410 if (!empty($user->emailstop)) {
3411 return 'emailstop';
3414 if (over_bounce_threshold($user)) {
3415 error_log("User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
3416 return false;
3419 $mail = new phpmailer;
3421 $mail->Version = 'Moodle '. $CFG->version; // mailer version
3422 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
3424 $mail->CharSet = 'UTF-8';
3426 if ($CFG->smtphosts == 'qmail') {
3427 $mail->IsQmail(); // use Qmail system
3429 } else if (empty($CFG->smtphosts)) {
3430 $mail->IsMail(); // use PHP mail() = sendmail
3432 } else {
3433 $mail->IsSMTP(); // use SMTP directly
3434 if (!empty($CFG->debugsmtp)) {
3435 echo '<pre>' . "\n";
3436 $mail->SMTPDebug = true;
3438 $mail->Host = $CFG->smtphosts; // specify main and backup servers
3440 if ($CFG->smtpuser) { // Use SMTP authentication
3441 $mail->SMTPAuth = true;
3442 $mail->Username = $CFG->smtpuser;
3443 $mail->Password = $CFG->smtppass;
3447 $adminuser = get_admin();
3449 // make up an email address for handling bounces
3450 if (!empty($CFG->handlebounces)) {
3451 $modargs = 'B'.base64_encode(pack('V',$user->id)).substr(md5($user->email),0,16);
3452 $mail->Sender = generate_email_processing_address(0,$modargs);
3454 else {
3455 $mail->Sender = $adminuser->email;
3458 if (is_string($from)) { // So we can pass whatever we want if there is need
3459 $mail->From = $CFG->noreplyaddress;
3460 $mail->FromName = $from;
3461 } else if ($usetrueaddress and $from->maildisplay) {
3462 $mail->From = $from->email;
3463 $mail->FromName = fullname($from);
3464 } else {
3465 $mail->From = $CFG->noreplyaddress;
3466 $mail->FromName = fullname($from);
3467 if (empty($replyto)) {
3468 $mail->AddReplyTo($CFG->noreplyaddress,get_string('noreplyname'));
3472 if (!empty($replyto)) {
3473 $mail->AddReplyTo($replyto,$replytoname);
3476 $mail->Subject = substr(stripslashes($subject), 0, 900);
3478 $mail->AddAddress($user->email, fullname($user) );
3480 $mail->WordWrap = 79; // set word wrap
3482 if (!empty($from->customheaders)) { // Add custom headers
3483 if (is_array($from->customheaders)) {
3484 foreach ($from->customheaders as $customheader) {
3485 $mail->AddCustomHeader($customheader);
3487 } else {
3488 $mail->AddCustomHeader($from->customheaders);
3492 if (!empty($from->priority)) {
3493 $mail->Priority = $from->priority;
3496 if ($messagehtml && $user->mailformat == 1) { // Don't ever send HTML to users who don't want it
3497 $mail->IsHTML(true);
3498 $mail->Encoding = 'quoted-printable'; // Encoding to use
3499 $mail->Body = $messagehtml;
3500 $mail->AltBody = "\n$messagetext\n";
3501 } else {
3502 $mail->IsHTML(false);
3503 $mail->Body = "\n$messagetext\n";
3506 if ($attachment && $attachname) {
3507 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
3508 $mail->AddAddress($adminuser->email, fullname($adminuser) );
3509 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
3510 } else {
3511 require_once($CFG->libdir.'/filelib.php');
3512 $mimetype = mimeinfo('type', $attachname);
3513 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
3519 /// If we are running under Unicode and sitemailcharset or allowusermailcharset are set, convert the email
3520 /// encoding to the specified one
3521 if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
3522 /// Set it to site mail charset
3523 $charset = $CFG->sitemailcharset;
3524 /// Overwrite it with the user mail charset
3525 if (!empty($CFG->allowusermailcharset)) {
3526 if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
3527 $charset = $useremailcharset;
3530 /// If it has changed, convert all the necessary strings
3531 $charsets = get_list_of_charsets();
3532 unset($charsets['UTF-8']);
3533 if (in_array($charset, $charsets)) {
3534 /// Save the new mail charset
3535 $mail->CharSet = $charset;
3536 /// And convert some strings
3537 $mail->FromName = $textlib->convert($mail->FromName, 'utf-8', $mail->CharSet); //From Name
3538 foreach ($mail->ReplyTo as $key => $rt) { //ReplyTo Names
3539 $mail->ReplyTo[$key][1] = $textlib->convert($rt, 'utf-8', $mail->CharSet);
3541 $mail->Subject = $textlib->convert($mail->Subject, 'utf-8', $mail->CharSet); //Subject
3542 foreach ($mail->to as $key => $to) {
3543 $mail->to[$key][1] = $textlib->convert($to, 'utf-8', $mail->CharSet); //To Names
3545 $mail->Body = $textlib->convert($mail->Body, 'utf-8', $mail->CharSet); //Body
3546 $mail->AltBody = $textlib->convert($mail->AltBody, 'utf-8', $mail->CharSet); //Subject
3550 if ($mail->Send()) {
3551 set_send_count($user);
3552 $mail->IsSMTP(); // use SMTP directly
3553 if (!empty($CFG->debugsmtp)) {
3554 echo '</pre>';
3556 return true;
3557 } else {
3558 mtrace('ERROR: '. $mail->ErrorInfo);
3559 add_to_log(SITEID, 'library', 'mailer', $FULLME, 'ERROR: '. $mail->ErrorInfo);
3560 if (!empty($CFG->debugsmtp)) {
3561 echo '</pre>';
3563 return false;
3568 * Sets specified user's password and send the new password to the user via email.
3570 * @uses $CFG
3571 * @param user $user A {@link $USER} object
3572 * @return boolean|string Returns "true" if mail was sent OK, "emailstop" if email
3573 * was blocked by user and "false" if there was another sort of error.
3575 function setnew_password_and_mail($user) {
3577 global $CFG;
3579 $site = get_site();
3580 $from = get_admin();
3582 $newpassword = generate_password();
3584 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
3585 trigger_error('Could not set user password!');
3586 return false;
3589 $a = new object();
3590 $a->firstname = $user->firstname;
3591 $a->sitename = format_string($site->fullname);
3592 $a->username = $user->username;
3593 $a->newpassword = $newpassword;
3594 $a->link = $CFG->wwwroot .'/login/';
3595 $a->signoff = fullname($from, true).' ('. $from->email .')';
3597 $message = get_string('newusernewpasswordtext', '', $a);
3599 $subject = format_string($site->fullname) .': '. get_string('newusernewpasswordsubj');
3601 return email_to_user($user, $from, $subject, $message);
3606 * Resets specified user's password and send the new password to the user via email.
3608 * @uses $CFG
3609 * @param user $user A {@link $USER} object
3610 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3611 * was blocked by user and "false" if there was another sort of error.
3613 function reset_password_and_mail($user) {
3615 global $CFG;
3617 $site = get_site();
3618 $from = get_admin();
3620 $userauth = get_auth_plugin($user->auth);
3621 if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
3622 trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
3623 return false;
3626 $newpassword = generate_password();
3628 if (!$userauth->user_update_password(addslashes_recursive($user), addslashes($newpassword))) {
3629 error("Could not set user password!");
3632 $a = new object();
3633 $a->firstname = $user->firstname;
3634 $a->sitename = format_string($site->fullname);
3635 $a->username = $user->username;
3636 $a->newpassword = $newpassword;
3637 $a->link = $CFG->httpswwwroot .'/login/change_password.php';
3638 $a->signoff = fullname($from, true).' ('. $from->email .')';
3640 $message = get_string('newpasswordtext', '', $a);
3642 $subject = format_string($site->fullname) .': '. get_string('changedpassword');
3644 return email_to_user($user, $from, $subject, $message);
3649 * Send email to specified user with confirmation text and activation link.
3651 * @uses $CFG
3652 * @param user $user A {@link $USER} object
3653 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3654 * was blocked by user and "false" if there was another sort of error.
3656 function send_confirmation_email($user) {
3658 global $CFG;
3660 $site = get_site();
3661 $from = get_admin();
3663 $data = new object();
3664 $data->firstname = fullname($user);
3665 $data->sitename = format_string($site->fullname);
3666 $data->admin = fullname($from) .' ('. $from->email .')';
3668 $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
3670 $data->link = $CFG->wwwroot .'/login/confirm.php?data='. $user->secret .'/'. urlencode($user->username);
3671 $message = get_string('emailconfirmation', '', $data);
3672 $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
3674 $user->mailformat = 1; // Always send HTML version as well
3676 return email_to_user($user, $from, $subject, $message, $messagehtml);
3681 * send_password_change_confirmation_email.
3683 * @uses $CFG
3684 * @param user $user A {@link $USER} object
3685 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3686 * was blocked by user and "false" if there was another sort of error.
3688 function send_password_change_confirmation_email($user) {
3690 global $CFG;
3692 $site = get_site();
3693 $from = get_admin();
3695 $data = new object();
3696 $data->firstname = $user->firstname;
3697 $data->sitename = format_string($site->fullname);
3698 $data->link = $CFG->httpswwwroot .'/login/forgot_password.php?p='. $user->secret .'&s='. urlencode($user->username);
3699 $data->admin = fullname($from).' ('. $from->email .')';
3701 $message = get_string('emailpasswordconfirmation', '', $data);
3702 $subject = get_string('emailpasswordconfirmationsubject', '', format_string($site->fullname));
3704 return email_to_user($user, $from, $subject, $message);
3709 * send_password_change_info.
3711 * @uses $CFG
3712 * @param user $user A {@link $USER} object
3713 * @return bool|string Returns "true" if mail was sent OK, "emailstop" if email
3714 * was blocked by user and "false" if there was another sort of error.
3716 function send_password_change_info($user) {
3718 global $CFG;
3720 $site = get_site();
3721 $from = get_admin();
3722 $systemcontext = get_context_instance(CONTEXT_SYSTEM);
3724 $data = new object();
3725 $data->firstname = $user->firstname;
3726 $data->sitename = format_string($site->fullname);
3727 $data->admin = fullname($from).' ('. $from->email .')';
3729 $userauth = get_auth_plugin($user->auth);
3731 if (!is_enabled_auth($user->auth) or $user->auth == 'nologin') {
3732 $message = get_string('emailpasswordchangeinfodisabled', '', $data);
3733 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3734 return email_to_user($user, $from, $subject, $message);
3737 if ($userauth->can_change_password() and $userauth->change_password_url()) {
3738 // we have some external url for password changing
3739 $data->link .= $userauth->change_password_url();
3741 } else {
3742 //no way to change password, sorry
3743 $data->link = '';
3746 if (!empty($data->link) and has_capability('moodle/user:changeownpassword', $systemcontext, $user->id)) {
3747 $message = get_string('emailpasswordchangeinfo', '', $data);
3748 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3749 } else {
3750 $message = get_string('emailpasswordchangeinfofail', '', $data);
3751 $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
3754 return email_to_user($user, $from, $subject, $message);
3759 * Check that an email is allowed. It returns an error message if there
3760 * was a problem.
3762 * @uses $CFG
3763 * @param string $email Content of email
3764 * @return string|false
3766 function email_is_not_allowed($email) {
3768 global $CFG;
3770 if (!empty($CFG->allowemailaddresses)) {
3771 $allowed = explode(' ', $CFG->allowemailaddresses);
3772 foreach ($allowed as $allowedpattern) {
3773 $allowedpattern = trim($allowedpattern);
3774 if (!$allowedpattern) {
3775 continue;
3777 if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) { // Match! (bug 5250)
3778 return false;
3781 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
3783 } else if (!empty($CFG->denyemailaddresses)) {
3784 $denied = explode(' ', $CFG->denyemailaddresses);
3785 foreach ($denied as $deniedpattern) {
3786 $deniedpattern = trim($deniedpattern);
3787 if (!$deniedpattern) {
3788 continue;
3790 if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) { // Match! (bug 5250)
3791 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
3796 return false;
3799 function email_welcome_message_to_user($course, $user=NULL) {
3800 global $CFG, $USER;
3802 if (empty($user)) {
3803 if (!isloggedin()) {
3804 return false;
3806 $user = $USER;
3809 if (!empty($course->welcomemessage)) {
3810 $subject = get_string('welcometocourse', '', format_string($course->fullname));
3812 $a->coursename = $course->fullname;
3813 $a->profileurl = "$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id";
3814 //$message = get_string("welcometocoursetext", "", $a);
3815 $message = $course->welcomemessage;
3817 if (! $teacher = get_teacher($course->id)) {
3818 $teacher = get_admin();
3820 email_to_user($user, $teacher, $subject, $message);
3824 /// FILE HANDLING /////////////////////////////////////////////
3828 * Makes an upload directory for a particular module.
3830 * @uses $CFG
3831 * @param int $courseid The id of the course in question - maps to id field of 'course' table.
3832 * @return string|false Returns full path to directory if successful, false if not
3834 function make_mod_upload_directory($courseid) {
3835 global $CFG;
3837 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
3838 return false;
3841 $strreadme = get_string('readme');
3843 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
3844 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3845 } else {
3846 copy($CFG->dirroot .'/lang/en_utf8/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
3848 return $moddata;
3852 * Returns current name of file on disk if it exists.
3854 * @param string $newfile File to be verified
3855 * @return string Current name of file on disk if true
3857 function valid_uploaded_file($newfile) {
3858 if (empty($newfile)) {
3859 return '';
3861 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
3862 return $newfile['tmp_name'];
3863 } else {
3864 return '';
3869 * Returns the maximum size for uploading files.
3871 * There are seven possible upload limits:
3872 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
3873 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
3874 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
3875 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
3876 * 5. by the Moodle admin in $CFG->maxbytes
3877 * 6. by the teacher in the current course $course->maxbytes
3878 * 7. by the teacher for the current module, eg $assignment->maxbytes
3880 * These last two are passed to this function as arguments (in bytes).
3881 * Anything defined as 0 is ignored.
3882 * The smallest of all the non-zero numbers is returned.
3884 * @param int $sizebytes ?
3885 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3886 * @param int $modulebytes Current module ->maxbytes (in bytes)
3887 * @return int The maximum size for uploading files.
3888 * @todo Finish documenting this function
3890 function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3892 if (! $filesize = ini_get('upload_max_filesize')) {
3893 $filesize = '5M';
3895 $minimumsize = get_real_size($filesize);
3897 if ($postsize = ini_get('post_max_size')) {
3898 $postsize = get_real_size($postsize);
3899 if ($postsize < $minimumsize) {
3900 $minimumsize = $postsize;
3904 if ($sitebytes and $sitebytes < $minimumsize) {
3905 $minimumsize = $sitebytes;
3908 if ($coursebytes and $coursebytes < $minimumsize) {
3909 $minimumsize = $coursebytes;
3912 if ($modulebytes and $modulebytes < $minimumsize) {
3913 $minimumsize = $modulebytes;
3916 return $minimumsize;
3920 * Related to {@link get_max_upload_file_size()} - this function returns an
3921 * array of possible sizes in an array, translated to the
3922 * local language.
3924 * @uses SORT_NUMERIC
3925 * @param int $sizebytes ?
3926 * @param int $coursebytes Current course $course->maxbytes (in bytes)
3927 * @param int $modulebytes Current module ->maxbytes (in bytes)
3928 * @return int
3929 * @todo Finish documenting this function
3931 function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
3932 global $CFG;
3934 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
3935 return array();
3938 $filesize[$maxsize] = display_size($maxsize);
3940 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
3941 5242880, 10485760, 20971520, 52428800, 104857600);
3943 // Allow maxbytes to be selected if it falls outside the above boundaries
3944 if( isset($CFG->maxbytes) && !in_array($CFG->maxbytes, $sizelist) ){
3945 $sizelist[] = $CFG->maxbytes;
3948 foreach ($sizelist as $sizebytes) {
3949 if ($sizebytes < $maxsize) {
3950 $filesize[$sizebytes] = display_size($sizebytes);
3954 krsort($filesize, SORT_NUMERIC);
3956 return $filesize;
3960 * If there has been an error uploading a file, print the appropriate error message
3961 * Numerical constants used as constant definitions not added until PHP version 4.2.0
3963 * $filearray is a 1-dimensional sub-array of the $_FILES array
3964 * eg $filearray = $_FILES['userfile1']
3965 * If left empty then the first element of the $_FILES array will be used
3967 * @uses $_FILES
3968 * @param array $filearray A 1-dimensional sub-array of the $_FILES array
3969 * @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.
3970 * @return bool|string
3972 function print_file_upload_error($filearray = '', $returnerror = false) {
3974 if ($filearray == '' or !isset($filearray['error'])) {
3976 if (empty($_FILES)) return false;
3978 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
3979 $filearray = array_shift($files); /// use first element of array
3982 switch ($filearray['error']) {
3984 case 0: // UPLOAD_ERR_OK
3985 if ($filearray['size'] > 0) {
3986 $errmessage = get_string('uploadproblem', $filearray['name']);
3987 } else {
3988 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
3990 break;
3992 case 1: // UPLOAD_ERR_INI_SIZE
3993 $errmessage = get_string('uploadserverlimit');
3994 break;
3996 case 2: // UPLOAD_ERR_FORM_SIZE
3997 $errmessage = get_string('uploadformlimit');
3998 break;
4000 case 3: // UPLOAD_ERR_PARTIAL
4001 $errmessage = get_string('uploadpartialfile');
4002 break;
4004 case 4: // UPLOAD_ERR_NO_FILE
4005 $errmessage = get_string('uploadnofilefound');
4006 break;
4008 default:
4009 $errmessage = get_string('uploadproblem', $filearray['name']);
4012 if ($returnerror) {
4013 return $errmessage;
4014 } else {
4015 notify($errmessage);
4016 return true;
4022 * handy function to loop through an array of files and resolve any filename conflicts
4023 * both in the array of filenames and for what is already on disk.
4024 * not really compatible with the similar function in uploadlib.php
4025 * but this could be used for files/index.php for moving files around.
4028 function resolve_filename_collisions($destination,$files,$format='%s_%d.%s') {
4029 foreach ($files as $k => $f) {
4030 if (check_potential_filename($destination,$f,$files)) {
4031 $bits = explode('.', $f);
4032 for ($i = 1; true; $i++) {
4033 $try = sprintf($format, $bits[0], $i, $bits[1]);
4034 if (!check_potential_filename($destination,$try,$files)) {
4035 $files[$k] = $try;
4036 break;
4041 return $files;
4045 * @used by resolve_filename_collisions
4047 function check_potential_filename($destination,$filename,$files) {
4048 if (file_exists($destination.'/'.$filename)) {
4049 return true;
4051 if (count(array_keys($files,$filename)) > 1) {
4052 return true;
4054 return false;
4059 * Returns an array with all the filenames in
4060 * all subdirectories, relative to the given rootdir.
4061 * If excludefile is defined, then that file/directory is ignored
4062 * If getdirs is true, then (sub)directories are included in the output
4063 * If getfiles is true, then files are included in the output
4064 * (at least one of these must be true!)
4066 * @param string $rootdir ?
4067 * @param string $excludefile If defined then the specified file/directory is ignored
4068 * @param bool $descend ?
4069 * @param bool $getdirs If true then (sub)directories are included in the output
4070 * @param bool $getfiles If true then files are included in the output
4071 * @return array An array with all the filenames in
4072 * all subdirectories, relative to the given rootdir
4073 * @todo Finish documenting this function. Add examples of $excludefile usage.
4075 function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
4077 $dirs = array();
4079 if (!$getdirs and !$getfiles) { // Nothing to show
4080 return $dirs;
4083 if (!is_dir($rootdir)) { // Must be a directory
4084 return $dirs;
4087 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
4088 return $dirs;
4091 if (!is_array($excludefiles)) {
4092 $excludefiles = array($excludefiles);
4095 while (false !== ($file = readdir($dir))) {
4096 $firstchar = substr($file, 0, 1);
4097 if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
4098 continue;
4100 $fullfile = $rootdir .'/'. $file;
4101 if (filetype($fullfile) == 'dir') {
4102 if ($getdirs) {
4103 $dirs[] = $file;
4105 if ($descend) {
4106 $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
4107 foreach ($subdirs as $subdir) {
4108 $dirs[] = $file .'/'. $subdir;
4111 } else if ($getfiles) {
4112 $dirs[] = $file;
4115 closedir($dir);
4117 asort($dirs);
4119 return $dirs;
4124 * Adds up all the files in a directory and works out the size.
4126 * @param string $rootdir ?
4127 * @param string $excludefile ?
4128 * @return array
4129 * @todo Finish documenting this function
4131 function get_directory_size($rootdir, $excludefile='') {
4133 global $CFG;
4135 // do it this way if we can, it's much faster
4136 if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
4137 $command = trim($CFG->pathtodu).' -sk --apparent-size '.escapeshellarg($rootdir);
4138 $output = null;
4139 $return = null;
4140 exec($command,$output,$return);
4141 if (is_array($output)) {
4142 return get_real_size(intval($output[0]).'k'); // we told it to return k.
4146 if (!is_dir($rootdir)) { // Must be a directory
4147 return 0;
4150 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
4151 return 0;
4154 $size = 0;
4156 while (false !== ($file = readdir($dir))) {
4157 $firstchar = substr($file, 0, 1);
4158 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
4159 continue;
4161 $fullfile = $rootdir .'/'. $file;
4162 if (filetype($fullfile) == 'dir') {
4163 $size += get_directory_size($fullfile, $excludefile);
4164 } else {
4165 $size += filesize($fullfile);
4168 closedir($dir);
4170 return $size;
4174 * Converts bytes into display form
4176 * @param string $size ?
4177 * @return string
4178 * @staticvar string $gb Localized string for size in gigabytes
4179 * @staticvar string $mb Localized string for size in megabytes
4180 * @staticvar string $kb Localized string for size in kilobytes
4181 * @staticvar string $b Localized string for size in bytes
4182 * @todo Finish documenting this function. Verify return type.
4184 function display_size($size) {
4186 static $gb, $mb, $kb, $b;
4188 if (empty($gb)) {
4189 $gb = get_string('sizegb');
4190 $mb = get_string('sizemb');
4191 $kb = get_string('sizekb');
4192 $b = get_string('sizeb');
4195 if ($size >= 1073741824) {
4196 $size = round($size / 1073741824 * 10) / 10 . $gb;
4197 } else if ($size >= 1048576) {
4198 $size = round($size / 1048576 * 10) / 10 . $mb;
4199 } else if ($size >= 1024) {
4200 $size = round($size / 1024 * 10) / 10 . $kb;
4201 } else {
4202 $size = $size .' '. $b;
4204 return $size;
4208 * Cleans a given filename by removing suspicious or troublesome characters
4209 * Only these are allowed: alphanumeric _ - .
4210 * Unicode characters can be enabled by setting $CFG->unicodecleanfilename = true in config.php
4212 * WARNING: unicode characters may not be compatible with zip compression in backup/restore,
4213 * because native zip binaries do weird character conversions. Use PHP zipping instead.
4215 * @param string $string file name
4216 * @return string cleaned file name
4218 function clean_filename($string) {
4219 global $CFG;
4220 if (empty($CFG->unicodecleanfilename)) {
4221 $textlib = textlib_get_instance();
4222 $string = $textlib->specialtoascii($string);
4223 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
4224 } else {
4225 //clean only ascii range
4226 $string = preg_replace("/[\\000-\\x2c\\x2f\\x3a-\\x40\\x5b-\\x5e\\x60\\x7b-\\177]/s", '_', $string);
4228 $string = preg_replace("/_+/", '_', $string);
4229 $string = preg_replace("/\.\.+/", '.', $string);
4230 return $string;
4234 /// STRING TRANSLATION ////////////////////////////////////////
4237 * Returns the code for the current language
4239 * @uses $CFG
4240 * @param $USER
4241 * @param $SESSION
4242 * @return string
4244 function current_language() {
4245 global $CFG, $USER, $SESSION, $COURSE;
4247 if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) { // Course language can override all other settings for this page
4248 $return = $COURSE->lang;
4250 } else if (!empty($SESSION->lang)) { // Session language can override other settings
4251 $return = $SESSION->lang;
4253 } else if (!empty($USER->lang)) {
4254 $return = $USER->lang;
4256 } else {
4257 $return = $CFG->lang;
4260 if ($return == 'en') {
4261 $return = 'en_utf8';
4264 return $return;
4268 * Prints out a translated string.
4270 * Prints out a translated string using the return value from the {@link get_string()} function.
4272 * Example usage of this function when the string is in the moodle.php file:<br/>
4273 * <code>
4274 * echo '<strong>';
4275 * print_string('wordforstudent');
4276 * echo '</strong>';
4277 * </code>
4279 * Example usage of this function when the string is not in the moodle.php file:<br/>
4280 * <code>
4281 * echo '<h1>';
4282 * print_string('typecourse', 'calendar');
4283 * echo '</h1>';
4284 * </code>
4286 * @param string $identifier The key identifier for the localized string
4287 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4288 * @param mixed $a An object, string or number that can be used
4289 * within translation strings
4291 function print_string($identifier, $module='', $a=NULL) {
4292 echo get_string($identifier, $module, $a);
4296 * fix up the optional data in get_string()/print_string() etc
4297 * ensure possible sprintf() format characters are escaped correctly
4298 * needs to handle arbitrary strings and objects
4299 * @param mixed $a An object, string or number that can be used
4300 * @return mixed the supplied parameter 'cleaned'
4302 function clean_getstring_data( $a ) {
4303 if (is_string($a)) {
4304 return str_replace( '%','%%',$a );
4306 elseif (is_object($a)) {
4307 $a_vars = get_object_vars( $a );
4308 $new_a_vars = array();
4309 foreach ($a_vars as $fname => $a_var) {
4310 $new_a_vars[$fname] = clean_getstring_data( $a_var );
4312 return (object)$new_a_vars;
4314 else {
4315 return $a;
4320 * @return array places to look for lang strings based on the prefix to the
4321 * module name. For example qtype_ in question/type. Used by get_string and
4322 * help.php.
4324 function places_to_search_for_lang_strings() {
4325 global $CFG;
4327 return array(
4328 '__exceptions' => array('moodle', 'langconfig'),
4329 'assignment_' => array('mod/assignment/type'),
4330 'auth_' => array('auth'),
4331 'block_' => array('blocks'),
4332 'datafield_' => array('mod/data/field'),
4333 'datapreset_' => array('mod/data/preset'),
4334 'enrol_' => array('enrol'),
4335 'format_' => array('course/format'),
4336 'qtype_' => array('question/type'),
4337 'report_' => array($CFG->admin.'/report', 'course/report', 'mod/quiz/report'),
4338 'resource_' => array('mod/resource/type'),
4339 '' => array('mod')
4344 * Returns a localized string.
4346 * Returns the translated string specified by $identifier as
4347 * for $module. Uses the same format files as STphp.
4348 * $a is an object, string or number that can be used
4349 * within translation strings
4351 * eg "hello \$a->firstname \$a->lastname"
4352 * or "hello \$a"
4354 * If you would like to directly echo the localized string use
4355 * the function {@link print_string()}
4357 * Example usage of this function involves finding the string you would
4358 * like a local equivalent of and using its identifier and module information
4359 * to retrive it.<br/>
4360 * If you open moodle/lang/en/moodle.php and look near line 1031
4361 * you will find a string to prompt a user for their word for student
4362 * <code>
4363 * $string['wordforstudent'] = 'Your word for Student';
4364 * </code>
4365 * So if you want to display the string 'Your word for student'
4366 * in any language that supports it on your site
4367 * you just need to use the identifier 'wordforstudent'
4368 * <code>
4369 * $mystring = '<strong>'. get_string('wordforstudent') .'</strong>';
4371 * </code>
4372 * If the string you want is in another file you'd take a slightly
4373 * different approach. Looking in moodle/lang/en/calendar.php you find
4374 * around line 75:
4375 * <code>
4376 * $string['typecourse'] = 'Course event';
4377 * </code>
4378 * If you want to display the string "Course event" in any language
4379 * supported you would use the identifier 'typecourse' and the module 'calendar'
4380 * (because it is in the file calendar.php):
4381 * <code>
4382 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
4383 * </code>
4385 * As a last resort, should the identifier fail to map to a string
4386 * the returned string will be [[ $identifier ]]
4388 * @uses $CFG
4389 * @param string $identifier The key identifier for the localized string
4390 * @param string $module The module where the key identifier is stored. If none is specified then moodle.php is used.
4391 * @param mixed $a An object, string or number that can be used
4392 * within translation strings
4393 * @param array $extralocations An array of strings with other locations to look for string files
4394 * @return string The localized string.
4396 function get_string($identifier, $module='', $a=NULL, $extralocations=NULL) {
4398 global $CFG;
4400 /// originally these special strings were stored in moodle.php now we are only in langconfig.php
4401 $langconfigstrs = array('alphabet', 'backupnameformat', 'firstdayofweek', 'locale',
4402 'localewin', 'localewincharset', 'oldcharset',
4403 'parentlanguage', 'strftimedate', 'strftimedateshort', 'strftimedatetime',
4404 'strftimedaydate', 'strftimedaydatetime', 'strftimedayshort', 'strftimedaytime',
4405 'strftimemonthyear', 'strftimerecent', 'strftimerecentfull', 'strftimetime',
4406 'thischarset', 'thisdirection', 'thislanguage');
4408 $filetocheck = 'langconfig.php';
4409 $defaultlang = 'en_utf8';
4410 if (in_array($identifier, $langconfigstrs)) {
4411 $module = 'langconfig'; //This strings are under langconfig.php for 1.6 lang packs
4414 $lang = current_language();
4416 if ($module == '') {
4417 $module = 'moodle';
4420 // if $a happens to have % in it, double it so sprintf() doesn't break
4421 if ($a) {
4422 $a = clean_getstring_data( $a );
4425 /// Define the two or three major locations of language strings for this module
4426 $locations = array();
4428 if (!empty($extralocations)) { // Calling code has a good idea where to look
4429 if (is_array($extralocations)) {
4430 $locations += $extralocations;
4431 } else if (is_string($extralocations)) {
4432 $locations[] = $extralocations;
4433 } else {
4434 debugging('Bad lang path provided');
4438 if (isset($CFG->running_installer)) {
4439 $module = 'installer';
4440 $filetocheck = 'installer.php';
4441 $locations += array( $CFG->dirroot.'/install/lang/', $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
4442 $defaultlang = 'en_utf8';
4443 } else {
4444 $locations += array( $CFG->dataroot.'/lang/', $CFG->dirroot.'/lang/' );
4447 /// Add extra places to look for strings for particular plugin types.
4448 $rules = places_to_search_for_lang_strings();
4449 $exceptions = $rules['__exceptions'];
4450 unset($rules['__exceptions']);
4452 if (!in_array($module, $exceptions)) {
4453 $dividerpos = strpos($module, '_');
4454 if ($dividerpos === false) {
4455 $type = '';
4456 $plugin = $module;
4457 } else {
4458 $type = substr($module, 0, $dividerpos + 1);
4459 $plugin = substr($module, $dividerpos + 1);
4461 if (!empty($rules[$type])) {
4462 foreach ($rules[$type] as $location) {
4463 $locations[] = $CFG->dirroot . "/$location/$plugin/lang/";
4468 /// First check all the normal locations for the string in the current language
4469 $resultstring = '';
4470 foreach ($locations as $location) {
4471 $locallangfile = $location.$lang.'_local'.'/'.$module.'.php'; //first, see if there's a local file
4472 if (file_exists($locallangfile)) {
4473 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4474 eval($result);
4475 return $resultstring;
4478 //if local directory not found, or particular string does not exist in local direcotry
4479 $langfile = $location.$lang.'/'.$module.'.php';
4480 if (file_exists($langfile)) {
4481 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4482 eval($result);
4483 return $resultstring;
4488 /// If the preferred language was English (utf8) we can abort now
4489 /// saving some checks beacuse it's the only "root" lang
4490 if ($lang == 'en_utf8') {
4491 return '[['. $identifier .']]';
4494 /// Is a parent language defined? If so, try to find this string in a parent language file
4496 foreach ($locations as $location) {
4497 $langfile = $location.$lang.'/'.$filetocheck;
4498 if (file_exists($langfile)) {
4499 if ($result = get_string_from_file('parentlanguage', $langfile, "\$parentlang")) {
4500 eval($result);
4501 if (!empty($parentlang)) { // found it!
4503 //first, see if there's a local file for parent
4504 $locallangfile = $location.$parentlang.'_local'.'/'.$module.'.php';
4505 if (file_exists($locallangfile)) {
4506 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4507 eval($result);
4508 return $resultstring;
4512 //if local directory not found, or particular string does not exist in local direcotry
4513 $langfile = $location.$parentlang.'/'.$module.'.php';
4514 if (file_exists($langfile)) {
4515 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4516 eval($result);
4517 return $resultstring;
4525 /// Our only remaining option is to try English
4527 foreach ($locations as $location) {
4528 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4529 if (file_exists($locallangfile)) {
4530 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4531 eval($result);
4532 return $resultstring;
4536 //if local_en not found, or string not found in local_en
4537 $langfile = $location.$defaultlang.'/'.$module.'.php';
4539 if (file_exists($langfile)) {
4540 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4541 eval($result);
4542 return $resultstring;
4547 /// And, because under 1.6 en is defined as en_utf8 child, me must try
4548 /// if it hasn't been queried before.
4549 if ($defaultlang == 'en') {
4550 $defaultlang = 'en_utf8';
4551 foreach ($locations as $location) {
4552 $locallangfile = $location.$defaultlang.'_local/'.$module.'.php'; //first, see if there's a local file
4553 if (file_exists($locallangfile)) {
4554 if ($result = get_string_from_file($identifier, $locallangfile, "\$resultstring")) {
4555 eval($result);
4556 return $resultstring;
4560 //if local_en not found, or string not found in local_en
4561 $langfile = $location.$defaultlang.'/'.$module.'.php';
4563 if (file_exists($langfile)) {
4564 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
4565 eval($result);
4566 return $resultstring;
4572 return '[['.$identifier.']]'; // Last resort
4576 * This function is only used from {@link get_string()}.
4578 * @internal Only used from get_string, not meant to be public API
4579 * @param string $identifier ?
4580 * @param string $langfile ?
4581 * @param string $destination ?
4582 * @return string|false ?
4583 * @staticvar array $strings Localized strings
4584 * @access private
4585 * @todo Finish documenting this function.
4587 function get_string_from_file($identifier, $langfile, $destination) {
4589 static $strings; // Keep the strings cached in memory.
4591 if (empty($strings[$langfile])) {
4592 $string = array();
4593 include ($langfile);
4594 $strings[$langfile] = $string;
4595 } else {
4596 $string = &$strings[$langfile];
4599 if (!isset ($string[$identifier])) {
4600 return false;
4603 return $destination .'= sprintf("'. $string[$identifier] .'");';
4607 * Converts an array of strings to their localized value.
4609 * @param array $array An array of strings
4610 * @param string $module The language module that these strings can be found in.
4611 * @return string
4613 function get_strings($array, $module='') {
4615 $string = NULL;
4616 foreach ($array as $item) {
4617 $string->$item = get_string($item, $module);
4619 return $string;
4623 * Returns a list of language codes and their full names
4624 * hides the _local files from everyone.
4625 * @param bool refreshcache force refreshing of lang cache
4626 * @param bool returnall ignore langlist, return all languages available
4627 * @return array An associative array with contents in the form of LanguageCode => LanguageName
4629 function get_list_of_languages($refreshcache=false, $returnall=false) {
4631 global $CFG;
4633 $languages = array();
4635 $filetocheck = 'langconfig.php';
4637 if (!$refreshcache && !$returnall && !empty($CFG->langcache) && file_exists($CFG->dataroot .'/cache/languages')) {
4638 /// read available langs from cache
4640 $lines = file($CFG->dataroot .'/cache/languages');
4641 foreach ($lines as $line) {
4642 $line = trim($line);
4643 if (preg_match('/^(\w+)\s+(.+)/', $line, $matches)) {
4644 $languages[$matches[1]] = $matches[2];
4647 unset($lines); unset($line); unset($matches);
4648 return $languages;
4651 if (!$returnall && !empty($CFG->langlist)) {
4652 /// return only languages allowed in langlist admin setting
4654 $langlist = explode(',', $CFG->langlist);
4655 // fix short lang names first - non existing langs are skipped anyway...
4656 foreach ($langlist as $lang) {
4657 if (strpos($lang, '_utf8') === false) {
4658 $langlist[] = $lang.'_utf8';
4661 // find existing langs from langlist
4662 foreach ($langlist as $lang) {
4663 $lang = trim($lang); //Just trim spaces to be a bit more permissive
4664 if (strstr($lang, '_local')!==false) {
4665 continue;
4667 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4668 $shortlang = substr($lang, 0, -5);
4669 } else {
4670 $shortlang = $lang;
4672 /// Search under dirroot/lang
4673 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4674 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4675 if (!empty($string['thislanguage'])) {
4676 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4678 unset($string);
4680 /// And moodledata/lang
4681 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4682 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4683 if (!empty($string['thislanguage'])) {
4684 $languages[$lang] = $string['thislanguage'].' ('. $shortlang .')';
4686 unset($string);
4690 } else {
4691 /// return all languages available in system
4692 /// Fetch langs from moodle/lang directory
4693 $langdirs = get_list_of_plugins('lang');
4694 /// Fetch langs from moodledata/lang directory
4695 $langdirs2 = get_list_of_plugins('lang', '', $CFG->dataroot);
4696 /// Merge both lists of langs
4697 $langdirs = array_merge($langdirs, $langdirs2);
4698 /// Sort all
4699 asort($langdirs);
4700 /// Get some info from each lang (first from moodledata, then from moodle)
4701 foreach ($langdirs as $lang) {
4702 if (strstr($lang, '_local')!==false) {
4703 continue;
4705 if (substr($lang, -5) == '_utf8') { //Remove the _utf8 suffix from the lang to show
4706 $shortlang = substr($lang, 0, -5);
4707 } else {
4708 $shortlang = $lang;
4710 /// Search under moodledata/lang
4711 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck)) {
4712 include($CFG->dataroot .'/lang/'. $lang .'/'. $filetocheck);
4713 if (!empty($string['thislanguage'])) {
4714 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4716 unset($string);
4718 /// And dirroot/lang
4719 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck)) {
4720 include($CFG->dirroot .'/lang/'. $lang .'/'. $filetocheck);
4721 if (!empty($string['thislanguage'])) {
4722 $languages[$lang] = $string['thislanguage'] .' ('. $shortlang .')';
4724 unset($string);
4729 if ($refreshcache && !empty($CFG->langcache)) {
4730 if ($returnall) {
4731 // we have a list of all langs only, just delete old cache
4732 @unlink($CFG->dataroot.'/cache/languages');
4734 } else {
4735 // store the list of allowed languages
4736 if ($file = fopen($CFG->dataroot .'/cache/languages', 'w')) {
4737 foreach ($languages as $key => $value) {
4738 fwrite($file, "$key $value\n");
4740 fclose($file);
4745 return $languages;
4749 * Returns a list of charset codes. It's hardcoded, so they should be added manually
4750 * (cheking that such charset is supported by the texlib library!)
4752 * @return array And associative array with contents in the form of charset => charset
4754 function get_list_of_charsets() {
4756 $charsets = array(
4757 'EUC-JP' => 'EUC-JP',
4758 'ISO-2022-JP'=> 'ISO-2022-JP',
4759 'ISO-8859-1' => 'ISO-8859-1',
4760 'SHIFT-JIS' => 'SHIFT-JIS',
4761 'GB2312' => 'GB2312',
4762 'GB18030' => 'GB18030', // gb18030 not supported by typo and mbstring
4763 'UTF-8' => 'UTF-8');
4765 asort($charsets);
4767 return $charsets;
4771 * Returns a list of country names in the current language
4773 * @uses $CFG
4774 * @uses $USER
4775 * @return array
4777 function get_list_of_countries() {
4778 global $CFG, $USER;
4780 $lang = current_language();
4782 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php') &&
4783 !file_exists($CFG->dataroot.'/lang/'. $lang .'/countries.php')) {
4784 if ($parentlang = get_string('parentlanguage')) {
4785 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/countries.php') ||
4786 file_exists($CFG->dataroot.'/lang/'. $parentlang .'/countries.php')) {
4787 $lang = $parentlang;
4788 } else {
4789 $lang = 'en_utf8'; // countries.php must exist in this pack
4791 } else {
4792 $lang = 'en_utf8'; // countries.php must exist in this pack
4796 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/countries.php')) {
4797 include($CFG->dataroot .'/lang/'. $lang .'/countries.php');
4798 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
4799 include($CFG->dirroot .'/lang/'. $lang .'/countries.php');
4802 if (!empty($string)) {
4803 asort($string);
4806 return $string;
4810 * Returns a list of valid and compatible themes
4812 * @uses $CFG
4813 * @return array
4815 function get_list_of_themes() {
4817 global $CFG;
4819 $themes = array();
4821 if (!empty($CFG->themelist)) { // use admin's list of themes
4822 $themelist = explode(',', $CFG->themelist);
4823 } else {
4824 $themelist = get_list_of_plugins("theme");
4827 foreach ($themelist as $key => $theme) {
4828 if (!file_exists("$CFG->themedir/$theme/config.php")) { // bad folder
4829 continue;
4831 $THEME = new object(); // Note this is not the global one!! :-)
4832 include("$CFG->themedir/$theme/config.php");
4833 if (!isset($THEME->sheets)) { // Not a valid 1.5 theme
4834 continue;
4836 $themes[$theme] = $theme;
4838 asort($themes);
4840 return $themes;
4845 * Returns a list of picture names in the current or specified language
4847 * @uses $CFG
4848 * @return array
4850 function get_list_of_pixnames($lang = '') {
4851 global $CFG;
4853 if (empty($lang)) {
4854 $lang = current_language();
4857 $string = array();
4859 $path = $CFG->dirroot .'/lang/en_utf8/pix.php'; // always exists
4861 if (file_exists($CFG->dataroot .'/lang/'. $lang .'_local/pix.php')) {
4862 $path = $CFG->dataroot .'/lang/'. $lang .'_local/pix.php';
4864 } else if (file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
4865 $path = $CFG->dirroot .'/lang/'. $lang .'/pix.php';
4867 } else if (file_exists($CFG->dataroot .'/lang/'. $lang .'/pix.php')) {
4868 $path = $CFG->dataroot .'/lang/'. $lang .'/pix.php';
4870 } else if ($parentlang = get_string('parentlanguage') and $parentlang != '[[parentlanguage]]') {
4871 return get_list_of_pixnames($parentlang); //return pixnames from parent language instead
4874 include($path);
4876 return $string;
4880 * Returns a list of timezones in the current language
4882 * @uses $CFG
4883 * @return array
4885 function get_list_of_timezones() {
4886 global $CFG;
4888 static $timezones;
4890 if (!empty($timezones)) { // This function has been called recently
4891 return $timezones;
4894 $timezones = array();
4896 if ($rawtimezones = get_records_sql('SELECT MAX(id), name FROM '.$CFG->prefix.'timezone GROUP BY name')) {
4897 foreach($rawtimezones as $timezone) {
4898 if (!empty($timezone->name)) {
4899 $timezones[$timezone->name] = get_string(strtolower($timezone->name), 'timezones');
4900 if (substr($timezones[$timezone->name], 0, 1) == '[') { // No translation found
4901 $timezones[$timezone->name] = $timezone->name;
4907 asort($timezones);
4909 for ($i = -13; $i <= 13; $i += .5) {
4910 $tzstring = 'GMT';
4911 if ($i < 0) {
4912 $timezones[sprintf("%.1f", $i)] = $tzstring . $i;
4913 } else if ($i > 0) {
4914 $timezones[sprintf("%.1f", $i)] = $tzstring . '+' . $i;
4915 } else {
4916 $timezones[sprintf("%.1f", $i)] = $tzstring;
4920 return $timezones;
4924 * Returns a list of currencies in the current language
4926 * @uses $CFG
4927 * @uses $USER
4928 * @return array
4930 function get_list_of_currencies() {
4931 global $CFG, $USER;
4933 $lang = current_language();
4935 if (!file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
4936 if ($parentlang = get_string('parentlanguage')) {
4937 if (file_exists($CFG->dataroot .'/lang/'. $parentlang .'/currencies.php')) {
4938 $lang = $parentlang;
4939 } else {
4940 $lang = 'en_utf8'; // currencies.php must exist in this pack
4942 } else {
4943 $lang = 'en_utf8'; // currencies.php must exist in this pack
4947 if (file_exists($CFG->dataroot .'/lang/'. $lang .'/currencies.php')) {
4948 include_once($CFG->dataroot .'/lang/'. $lang .'/currencies.php');
4949 } else { //if en_utf8 is not installed in dataroot
4950 include_once($CFG->dirroot .'/lang/'. $lang .'/currencies.php');
4953 if (!empty($string)) {
4954 asort($string);
4957 return $string;
4963 * Can include a given document file (depends on second
4964 * parameter) or just return info about it.
4966 * @uses $CFG
4967 * @param string $file ?
4968 * @param bool $include ?
4969 * @return ?
4970 * @todo Finish documenting this function
4972 function document_file($file, $include=true) {
4973 global $CFG;
4975 $file = clean_filename($file);
4977 if (empty($file)) {
4978 return false;
4981 $langs = array(current_language(), get_string('parentlanguage'), 'en');
4983 foreach ($langs as $lang) {
4984 $info = new object();
4985 $info->filepath = $CFG->dirroot .'/lang/'. $lang .'/docs/'. $file;
4986 $info->urlpath = $CFG->wwwroot .'/lang/'. $lang .'/docs/'. $file;
4988 if (file_exists($info->filepath)) {
4989 if ($include) {
4990 include($info->filepath);
4992 return $info;
4996 return false;
4999 /// ENCRYPTION ////////////////////////////////////////////////
5002 * rc4encrypt
5004 * @param string $data ?
5005 * @return string
5006 * @todo Finish documenting this function
5008 function rc4encrypt($data) {
5009 $password = 'nfgjeingjk';
5010 return endecrypt($password, $data, '');
5014 * rc4decrypt
5016 * @param string $data ?
5017 * @return string
5018 * @todo Finish documenting this function
5020 function rc4decrypt($data) {
5021 $password = 'nfgjeingjk';
5022 return endecrypt($password, $data, 'de');
5026 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
5028 * @param string $pwd ?
5029 * @param string $data ?
5030 * @param string $case ?
5031 * @return string
5032 * @todo Finish documenting this function
5034 function endecrypt ($pwd, $data, $case) {
5036 if ($case == 'de') {
5037 $data = urldecode($data);
5040 $key[] = '';
5041 $box[] = '';
5042 $temp_swap = '';
5043 $pwd_length = 0;
5045 $pwd_length = strlen($pwd);
5047 for ($i = 0; $i <= 255; $i++) {
5048 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
5049 $box[$i] = $i;
5052 $x = 0;
5054 for ($i = 0; $i <= 255; $i++) {
5055 $x = ($x + $box[$i] + $key[$i]) % 256;
5056 $temp_swap = $box[$i];
5057 $box[$i] = $box[$x];
5058 $box[$x] = $temp_swap;
5061 $temp = '';
5062 $k = '';
5064 $cipherby = '';
5065 $cipher = '';
5067 $a = 0;
5068 $j = 0;
5070 for ($i = 0; $i < strlen($data); $i++) {
5071 $a = ($a + 1) % 256;
5072 $j = ($j + $box[$a]) % 256;
5073 $temp = $box[$a];
5074 $box[$a] = $box[$j];
5075 $box[$j] = $temp;
5076 $k = $box[(($box[$a] + $box[$j]) % 256)];
5077 $cipherby = ord(substr($data, $i, 1)) ^ $k;
5078 $cipher .= chr($cipherby);
5081 if ($case == 'de') {
5082 $cipher = urldecode(urlencode($cipher));
5083 } else {
5084 $cipher = urlencode($cipher);
5087 return $cipher;
5091 /// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
5095 * Call this function to add an event to the calendar table
5096 * and to call any calendar plugins
5098 * @uses $CFG
5099 * @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:
5100 * <ul>
5101 * <li><b>$event->name</b> - Name for the event
5102 * <li><b>$event->description</b> - Description of the event (defaults to '')
5103 * <li><b>$event->format</b> - Format for the description (using formatting types defined at the top of weblib.php)
5104 * <li><b>$event->courseid</b> - The id of the course this event belongs to (0 = all courses)
5105 * <li><b>$event->groupid</b> - The id of the group this event belongs to (0 = no group)
5106 * <li><b>$event->userid</b> - The id of the user this event belongs to (0 = no user)
5107 * <li><b>$event->modulename</b> - Name of the module that creates this event
5108 * <li><b>$event->instance</b> - Instance of the module that owns this event
5109 * <li><b>$event->eventtype</b> - The type info together with the module info could
5110 * be used by calendar plugins to decide how to display event
5111 * <li><b>$event->timestart</b>- Timestamp for start of event
5112 * <li><b>$event->timeduration</b> - Duration (defaults to zero)
5113 * <li><b>$event->visible</b> - 0 if the event should be hidden (e.g. because the activity that created it is hidden)
5114 * </ul>
5115 * @return int The id number of the resulting record
5117 function add_event($event) {
5119 global $CFG;
5121 $event->timemodified = time();
5123 if (!$event->id = insert_record('event', $event)) {
5124 return false;
5127 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
5128 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5129 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5130 $calendar_add_event = $CFG->calendar.'_add_event';
5131 if (function_exists($calendar_add_event)) {
5132 $calendar_add_event($event);
5137 return $event->id;
5141 * Call this function to update an event in the calendar table
5142 * the event will be identified by the id field of the $event object.
5144 * @uses $CFG
5145 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5146 * @return bool
5148 function update_event($event) {
5150 global $CFG;
5152 $event->timemodified = time();
5154 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5155 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5156 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5157 $calendar_update_event = $CFG->calendar.'_update_event';
5158 if (function_exists($calendar_update_event)) {
5159 $calendar_update_event($event);
5163 return update_record('event', $event);
5167 * Call this function to delete the event with id $id from calendar table.
5169 * @uses $CFG
5170 * @param int $id The id of an event from the 'calendar' table.
5171 * @return array An associative array with the results from the SQL call.
5172 * @todo Verify return type
5174 function delete_event($id) {
5176 global $CFG;
5178 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
5179 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5180 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5181 $calendar_delete_event = $CFG->calendar.'_delete_event';
5182 if (function_exists($calendar_delete_event)) {
5183 $calendar_delete_event($id);
5187 return delete_records('event', 'id', $id);
5191 * Call this function to hide an event in the calendar table
5192 * the event will be identified by the id field of the $event object.
5194 * @uses $CFG
5195 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5196 * @return array An associative array with the results from the SQL call.
5197 * @todo Verify return type
5199 function hide_event($event) {
5200 global $CFG;
5202 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5203 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5204 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5205 $calendar_hide_event = $CFG->calendar.'_hide_event';
5206 if (function_exists($calendar_hide_event)) {
5207 $calendar_hide_event($event);
5211 return set_field('event', 'visible', 0, 'id', $event->id);
5215 * Call this function to unhide an event in the calendar table
5216 * the event will be identified by the id field of the $event object.
5218 * @uses $CFG
5219 * @param array $event An associative array representing an event from the calendar table. The event will be identified by the id field.
5220 * @return array An associative array with the results from the SQL call.
5221 * @todo Verify return type
5223 function show_event($event) {
5224 global $CFG;
5226 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
5227 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
5228 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5229 $calendar_show_event = $CFG->calendar.'_show_event';
5230 if (function_exists($calendar_show_event)) {
5231 $calendar_show_event($event);
5235 return set_field('event', 'visible', 1, 'id', $event->id);
5239 /// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
5242 * Lists plugin directories within some directory
5244 * @uses $CFG
5245 * @param string $plugin dir under we'll look for plugins (defaults to 'mod')
5246 * @param string $exclude dir name to exclude from the list (defaults to none)
5247 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
5248 * @return array of plugins found under the requested parameters
5250 function get_list_of_plugins($plugin='mod', $exclude='', $basedir='') {
5252 global $CFG;
5254 $plugins = array();
5256 if (empty($basedir)) {
5258 # This switch allows us to use the appropiate theme directory - and potentialy alternatives for other plugins
5259 switch ($plugin) {
5260 case "theme":
5261 $basedir = $CFG->themedir;
5262 break;
5264 default:
5265 $basedir = $CFG->dirroot .'/'. $plugin;
5268 } else {
5269 $basedir = $basedir .'/'. $plugin;
5272 if (file_exists($basedir) && filetype($basedir) == 'dir') {
5273 $dirhandle = opendir($basedir);
5274 while (false !== ($dir = readdir($dirhandle))) {
5275 $firstchar = substr($dir, 0, 1);
5276 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
5277 continue;
5279 if (filetype($basedir .'/'. $dir) != 'dir') {
5280 continue;
5282 $plugins[] = $dir;
5284 closedir($dirhandle);
5286 if ($plugins) {
5287 asort($plugins);
5289 return $plugins;
5293 * Returns true if the current version of PHP is greater that the specified one.
5295 * @param string $version The version of php being tested.
5296 * @return bool
5298 function check_php_version($version='4.1.0') {
5299 return (version_compare(phpversion(), $version) >= 0);
5304 * Checks to see if is a browser matches the specified
5305 * brand and is equal or better version.
5307 * @uses $_SERVER
5308 * @param string $brand The browser identifier being tested
5309 * @param int $version The version of the browser
5310 * @return bool true if the given version is below that of the detected browser
5312 function check_browser_version($brand='MSIE', $version=5.5) {
5313 if (empty($_SERVER['HTTP_USER_AGENT'])) {
5314 return false;
5317 $agent = $_SERVER['HTTP_USER_AGENT'];
5319 switch ($brand) {
5321 case 'Camino': /// Mozilla Firefox browsers
5323 if (preg_match("/Camino\/([0-9\.]+)/i", $agent, $match)) {
5324 if (version_compare($match[1], $version) >= 0) {
5325 return true;
5328 break;
5331 case 'Firefox': /// Mozilla Firefox browsers
5333 if (preg_match("/Firefox\/([0-9\.]+)/i", $agent, $match)) {
5334 if (version_compare($match[1], $version) >= 0) {
5335 return true;
5338 break;
5341 case 'Gecko': /// Gecko based browsers
5343 if (substr_count($agent, 'Camino')) {
5344 // MacOS X Camino support
5345 $version = 20041110;
5348 // the proper string - Gecko/CCYYMMDD Vendor/Version
5349 // Faster version and work-a-round No IDN problem.
5350 if (preg_match("/Gecko\/([0-9]+)/i", $agent, $match)) {
5351 if ($match[1] > $version) {
5352 return true;
5355 break;
5358 case 'MSIE': /// Internet Explorer
5360 if (strpos($agent, 'Opera')) { // Reject Opera
5361 return false;
5363 $string = explode(';', $agent);
5364 if (!isset($string[1])) {
5365 return false;
5367 $string = explode(' ', trim($string[1]));
5368 if (!isset($string[0]) and !isset($string[1])) {
5369 return false;
5371 if ($string[0] == $brand and (float)$string[1] >= $version ) {
5372 return true;
5374 break;
5376 case 'Opera': /// Opera
5378 if (preg_match("/Opera\/([0-9\.]+)/i", $agent, $match)) {
5379 if (version_compare($match[1], $version) >= 0) {
5380 return true;
5383 break;
5385 case 'Safari': /// Safari
5386 // Look for AppleWebKit, excluding strings with OmniWeb, Shiira and SimbianOS
5387 if (strpos($agent, 'OmniWeb')) { // Reject OmniWeb
5388 return false;
5389 } elseif (strpos($agent, 'Shiira')) { // Reject Shiira
5390 return false;
5391 } elseif (strpos($agent, 'SimbianOS')) { // Reject SimbianOS
5392 return false;
5395 if (preg_match("/AppleWebKit\/([0-9]+)/i", $agent, $match)) {
5396 if (version_compare($match[1], $version) >= 0) {
5397 return true;
5401 break;
5405 return false;
5409 * This function makes the return value of ini_get consistent if you are
5410 * setting server directives through the .htaccess file in apache.
5411 * Current behavior for value set from php.ini On = 1, Off = [blank]
5412 * Current behavior for value set from .htaccess On = On, Off = Off
5413 * Contributed by jdell @ unr.edu
5415 * @param string $ini_get_arg ?
5416 * @return bool
5417 * @todo Finish documenting this function
5419 function ini_get_bool($ini_get_arg) {
5420 $temp = ini_get($ini_get_arg);
5422 if ($temp == '1' or strtolower($temp) == 'on') {
5423 return true;
5425 return false;
5429 * Compatibility stub to provide backward compatibility
5431 * Determines if the HTML editor is enabled.
5432 * @deprecated Use {@link can_use_html_editor()} instead.
5434 function can_use_richtext_editor() {
5435 return can_use_html_editor();
5439 * Determines if the HTML editor is enabled.
5441 * This depends on site and user
5442 * settings, as well as the current browser being used.
5444 * @return string|false Returns false if editor is not being used, otherwise
5445 * returns 'MSIE' or 'Gecko'.
5447 function can_use_html_editor() {
5448 global $USER, $CFG;
5450 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
5451 if (check_browser_version('MSIE', 5.5)) {
5452 return 'MSIE';
5453 } else if (check_browser_version('Gecko', 20030516)) {
5454 return 'Gecko';
5457 return false;
5461 * Hack to find out the GD version by parsing phpinfo output
5463 * @return int GD version (1, 2, or 0)
5465 function check_gd_version() {
5466 $gdversion = 0;
5468 if (function_exists('gd_info')){
5469 $gd_info = gd_info();
5470 if (substr_count($gd_info['GD Version'], '2.')) {
5471 $gdversion = 2;
5472 } else if (substr_count($gd_info['GD Version'], '1.')) {
5473 $gdversion = 1;
5476 } else {
5477 ob_start();
5478 phpinfo(8);
5479 $phpinfo = ob_get_contents();
5480 ob_end_clean();
5482 $phpinfo = explode("\n", $phpinfo);
5485 foreach ($phpinfo as $text) {
5486 $parts = explode('</td>', $text);
5487 foreach ($parts as $key => $val) {
5488 $parts[$key] = trim(strip_tags($val));
5490 if ($parts[0] == 'GD Version') {
5491 if (substr_count($parts[1], '2.0')) {
5492 $parts[1] = '2.0';
5494 $gdversion = intval($parts[1]);
5499 return $gdversion; // 1, 2 or 0
5503 * Determine if moodle installation requires update
5505 * Checks version numbers of main code and all modules to see
5506 * if there are any mismatches
5508 * @uses $CFG
5509 * @return bool
5511 function moodle_needs_upgrading() {
5512 global $CFG;
5514 $version = null;
5515 include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
5516 if ($CFG->version) {
5517 if ($version > $CFG->version) {
5518 return true;
5520 if ($mods = get_list_of_plugins('mod')) {
5521 foreach ($mods as $mod) {
5522 $fullmod = $CFG->dirroot .'/mod/'. $mod;
5523 $module = new object();
5524 if (!is_readable($fullmod .'/version.php')) {
5525 notify('Module "'. $mod .'" is not readable - check permissions');
5526 continue;
5528 include_once($fullmod .'/version.php'); # defines $module with version etc
5529 if ($currmodule = get_record('modules', 'name', $mod)) {
5530 if ($module->version > $currmodule->version) {
5531 return true;
5536 } else {
5537 return true;
5539 return false;
5543 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
5546 * Notify admin users or admin user of any failed logins (since last notification).
5548 * @uses $CFG
5549 * @uses $db
5550 * @uses HOURSECS
5552 function notify_login_failures() {
5553 global $CFG, $db;
5555 switch ($CFG->notifyloginfailures) {
5556 case 'mainadmin' :
5557 $recip = array(get_admin());
5558 break;
5559 case 'alladmins':
5560 $recip = get_admins();
5561 break;
5564 if (empty($CFG->lastnotifyfailure)) {
5565 $CFG->lastnotifyfailure=0;
5568 // we need to deal with the threshold stuff first.
5569 if (empty($CFG->notifyloginthreshold)) {
5570 $CFG->notifyloginthreshold = 10; // default to something sensible.
5573 $notifyipsrs = $db->Execute('SELECT ip FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5574 AND module=\'login\' AND action=\'error\' GROUP BY ip HAVING count(*) > '. $CFG->notifyloginthreshold);
5576 $notifyusersrs = $db->Execute('SELECT info FROM '. $CFG->prefix .'log WHERE time > '. $CFG->lastnotifyfailure .'
5577 AND module=\'login\' AND action=\'error\' GROUP BY info HAVING count(*) > '. $CFG->notifyloginthreshold);
5579 if ($notifyipsrs) {
5580 $ipstr = '';
5581 while ($row = rs_fetch_next_record($notifyipsrs)) {
5582 $ipstr .= "'". $row->ip ."',";
5584 rs_close($notifyipsrs);
5585 $ipstr = substr($ipstr,0,strlen($ipstr)-1);
5587 if ($notifyusersrs) {
5588 $userstr = '';
5589 while ($row = rs_fetch_next_record($notifyusersrs)) {
5590 $userstr .= "'". $row->info ."',";
5592 rs_close($notifyusersrs);
5593 $userstr = substr($userstr,0,strlen($userstr)-1);
5596 if (strlen($userstr) > 0 || strlen($ipstr) > 0) {
5597 $count = 0;
5598 $logs = get_logs('time > '. $CFG->lastnotifyfailure .' AND module=\'login\' AND action=\'error\' '
5599 .((strlen($ipstr) > 0 && strlen($userstr) > 0) ? ' AND ( ip IN ('. $ipstr .') OR info IN ('. $userstr .') ) '
5600 : ((strlen($ipstr) != 0) ? ' AND ip IN ('. $ipstr .') ' : ' AND info IN ('. $userstr .') ')), 'l.time DESC', '', '', $count);
5602 // 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
5603 if (is_array($recip) and count($recip) > 0 and ((time() - HOURSECS) > $CFG->lastnotifyfailure)
5604 and is_array($logs) and count($logs) > 0) {
5606 $message = '';
5607 $site = get_site();
5608 $subject = get_string('notifyloginfailuressubject', '', format_string($site->fullname));
5609 $message .= get_string('notifyloginfailuresmessagestart', '', $CFG->wwwroot)
5610 .(($CFG->lastnotifyfailure != 0) ? '('.userdate($CFG->lastnotifyfailure).')' : '')."\n\n";
5611 foreach ($logs as $log) {
5612 $log->time = userdate($log->time);
5613 $message .= get_string('notifyloginfailuresmessage','',$log)."\n";
5615 $message .= "\n\n".get_string('notifyloginfailuresmessageend','',$CFG->wwwroot)."\n\n";
5616 foreach ($recip as $admin) {
5617 mtrace('Emailing '. $admin->username .' about '. count($logs) .' failed login attempts');
5618 email_to_user($admin,get_admin(),$subject,$message);
5620 $conf = new object();
5621 $conf->name = 'lastnotifyfailure';
5622 $conf->value = time();
5623 if ($current = get_record('config', 'name', 'lastnotifyfailure')) {
5624 $conf->id = $current->id;
5625 if (! update_record('config', $conf)) {
5626 mtrace('Could not update last notify time');
5629 } else if (! insert_record('config', $conf)) {
5630 mtrace('Could not set last notify time');
5637 * moodle_setlocale
5639 * @uses $CFG
5640 * @param string $locale ?
5641 * @todo Finish documenting this function
5643 function moodle_setlocale($locale='') {
5645 global $CFG;
5647 static $currentlocale = ''; // last locale caching
5649 $oldlocale = $currentlocale;
5651 /// Fetch the correct locale based on ostype
5652 if($CFG->ostype == 'WINDOWS') {
5653 $stringtofetch = 'localewin';
5654 } else {
5655 $stringtofetch = 'locale';
5658 /// the priority is the same as in get_string() - parameter, config, course, session, user, global language
5659 if (!empty($locale)) {
5660 $currentlocale = $locale;
5661 } else if (!empty($CFG->locale)) { // override locale for all language packs
5662 $currentlocale = $CFG->locale;
5663 } else {
5664 $currentlocale = get_string($stringtofetch);
5667 /// do nothing if locale already set up
5668 if ($oldlocale == $currentlocale) {
5669 return;
5672 /// Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
5673 /// set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
5674 /// Some day, numeric, monetary and other categories should be set too, I think. :-/
5676 /// Get current values
5677 $monetary= setlocale (LC_MONETARY, 0);
5678 $numeric = setlocale (LC_NUMERIC, 0);
5679 $ctype = setlocale (LC_CTYPE, 0);
5680 if ($CFG->ostype != 'WINDOWS') {
5681 $messages= setlocale (LC_MESSAGES, 0);
5683 /// Set locale to all
5684 setlocale (LC_ALL, $currentlocale);
5685 /// Set old values
5686 setlocale (LC_MONETARY, $monetary);
5687 setlocale (LC_NUMERIC, $numeric);
5688 if ($CFG->ostype != 'WINDOWS') {
5689 setlocale (LC_MESSAGES, $messages);
5691 if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') { // To workaround a well-known PHP problem with Turkish letter Ii
5692 setlocale (LC_CTYPE, $ctype);
5697 * Converts string to lowercase using most compatible function available.
5699 * @param string $string The string to convert to all lowercase characters.
5700 * @param string $encoding The encoding on the string.
5701 * @return string
5702 * @todo Add examples of calling this function with/without encoding types
5703 * @deprecated Use textlib->strtolower($text) instead.
5705 function moodle_strtolower ($string, $encoding='') {
5707 //If not specified use utf8
5708 if (empty($encoding)) {
5709 $encoding = 'UTF-8';
5711 //Use text services
5712 $textlib = textlib_get_instance();
5714 return $textlib->strtolower($string, $encoding);
5718 * Count words in a string.
5720 * Words are defined as things between whitespace.
5722 * @param string $string The text to be searched for words.
5723 * @return int The count of words in the specified string
5725 function count_words($string) {
5726 $string = strip_tags($string);
5727 return count(preg_split("/\w\b/", $string)) - 1;
5730 /** Count letters in a string.
5732 * Letters are defined as chars not in tags and different from whitespace.
5734 * @param string $string The text to be searched for letters.
5735 * @return int The count of letters in the specified text.
5737 function count_letters($string) {
5738 /// Loading the textlib singleton instance. We are going to need it.
5739 $textlib = textlib_get_instance();
5741 $string = strip_tags($string); // Tags are out now
5742 $string = ereg_replace('[[:space:]]*','',$string); //Whitespace are out now
5744 return $textlib->strlen($string);
5748 * Generate and return a random string of the specified length.
5750 * @param int $length The length of the string to be created.
5751 * @return string
5753 function random_string ($length=15) {
5754 $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
5755 $pool .= 'abcdefghijklmnopqrstuvwxyz';
5756 $pool .= '0123456789';
5757 $poollen = strlen($pool);
5758 mt_srand ((double) microtime() * 1000000);
5759 $string = '';
5760 for ($i = 0; $i < $length; $i++) {
5761 $string .= substr($pool, (mt_rand()%($poollen)), 1);
5763 return $string;
5767 * Given some text (which may contain HTML) and an ideal length,
5768 * this function truncates the text neatly on a word boundary if possible
5770 function shorten_text($text, $ideal=30) {
5772 global $CFG;
5775 $i = 0;
5776 $tag = false;
5777 $length = strlen($text);
5778 $count = 0;
5779 $stopzone = false;
5780 $truncate = 0;
5782 if ($length <= $ideal) {
5783 return $text;
5786 for ($i=0; $i<$length; $i++) {
5787 $char = $text[$i];
5789 switch ($char) {
5790 case "<":
5791 $tag = true;
5792 break;
5793 case ">":
5794 $tag = false;
5795 break;
5796 default:
5797 if (!$tag) {
5798 if ($stopzone) {
5799 if ($char == '.' or $char == ' ') {
5800 $truncate = $i+1;
5801 break 2;
5802 } else if (ord($char) >= 0xE0) { // Chinese/Japanese/Korean text
5803 $truncate = $i; // can be truncated at any UTF-8
5804 break 2; // character boundary.
5807 $count++;
5809 break;
5811 if (!$stopzone) {
5812 if ($count > $ideal) {
5813 $stopzone = true;
5818 if (!$truncate) {
5819 $truncate = $i;
5822 $ellipse = ($truncate < $length) ? '...' : '';
5824 return substr($text, 0, $truncate).$ellipse;
5829 * Given dates in seconds, how many weeks is the date from startdate
5830 * The first week is 1, the second 2 etc ...
5832 * @uses WEEKSECS
5833 * @param ? $startdate ?
5834 * @param ? $thedate ?
5835 * @return string
5836 * @todo Finish documenting this function
5838 function getweek ($startdate, $thedate) {
5839 if ($thedate < $startdate) { // error
5840 return 0;
5843 return floor(($thedate - $startdate) / WEEKSECS) + 1;
5847 * returns a randomly generated password of length $maxlen. inspired by
5848 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3}
5850 * @param int $maxlength The maximum size of the password being generated.
5851 * @return string
5853 function generate_password($maxlen=10) {
5854 global $CFG;
5856 $fillers = '1234567890!$-+';
5857 $wordlist = file($CFG->wordlist);
5859 srand((double) microtime() * 1000000);
5860 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5861 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
5862 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
5864 return substr($word1 . $filler1 . $word2, 0, $maxlen);
5868 * Given a float, prints it nicely
5870 * @param float $num The float to print
5871 * @param int $places The number of decimal places to print.
5872 * @return string
5874 function format_float($num, $places=1) {
5875 return sprintf("%.$places"."f", $num);
5879 * Given a simple array, this shuffles it up just like shuffle()
5880 * Unlike PHP's shuffle() ihis function works on any machine.
5882 * @param array $array The array to be rearranged
5883 * @return array
5885 function swapshuffle($array) {
5887 srand ((double) microtime() * 10000000);
5888 $last = count($array) - 1;
5889 for ($i=0;$i<=$last;$i++) {
5890 $from = rand(0,$last);
5891 $curr = $array[$i];
5892 $array[$i] = $array[$from];
5893 $array[$from] = $curr;
5895 return $array;
5899 * Like {@link swapshuffle()}, but works on associative arrays
5901 * @param array $array The associative array to be rearranged
5902 * @return array
5904 function swapshuffle_assoc($array) {
5907 $newkeys = swapshuffle(array_keys($array));
5908 foreach ($newkeys as $newkey) {
5909 $newarray[$newkey] = $array[$newkey];
5911 return $newarray;
5915 * Given an arbitrary array, and a number of draws,
5916 * this function returns an array with that amount
5917 * of items. The indexes are retained.
5919 * @param array $array ?
5920 * @param ? $draws ?
5921 * @return ?
5922 * @todo Finish documenting this function
5924 function draw_rand_array($array, $draws) {
5925 srand ((double) microtime() * 10000000);
5927 $return = array();
5929 $last = count($array);
5931 if ($draws > $last) {
5932 $draws = $last;
5935 while ($draws > 0) {
5936 $last--;
5938 $keys = array_keys($array);
5939 $rand = rand(0, $last);
5941 $return[$keys[$rand]] = $array[$keys[$rand]];
5942 unset($array[$keys[$rand]]);
5944 $draws--;
5947 return $return;
5951 * microtime_diff
5953 * @param string $a ?
5954 * @param string $b ?
5955 * @return string
5956 * @todo Finish documenting this function
5958 function microtime_diff($a, $b) {
5959 list($a_dec, $a_sec) = explode(' ', $a);
5960 list($b_dec, $b_sec) = explode(' ', $b);
5961 return $b_sec - $a_sec + $b_dec - $a_dec;
5965 * Given a list (eg a,b,c,d,e) this function returns
5966 * an array of 1->a, 2->b, 3->c etc
5968 * @param array $list ?
5969 * @param string $separator ?
5970 * @todo Finish documenting this function
5972 function make_menu_from_list($list, $separator=',') {
5974 $array = array_reverse(explode($separator, $list), true);
5975 foreach ($array as $key => $item) {
5976 $outarray[$key+1] = trim($item);
5978 return $outarray;
5982 * Creates an array that represents all the current grades that
5983 * can be chosen using the given grading type. Negative numbers
5984 * are scales, zero is no grade, and positive numbers are maximum
5985 * grades.
5987 * @param int $gradingtype ?
5988 * return int
5989 * @todo Finish documenting this function
5991 function make_grades_menu($gradingtype) {
5992 $grades = array();
5993 if ($gradingtype < 0) {
5994 if ($scale = get_record('scale', 'id', - $gradingtype)) {
5995 return make_menu_from_list($scale->scale);
5997 } else if ($gradingtype > 0) {
5998 for ($i=$gradingtype; $i>=0; $i--) {
5999 $grades[$i] = $i .' / '. $gradingtype;
6001 return $grades;
6003 return $grades;
6007 * This function returns the nummber of activities
6008 * using scaleid in a courseid
6010 * @param int $courseid ?
6011 * @param int $scaleid ?
6012 * @return int
6013 * @todo Finish documenting this function
6015 function course_scale_used($courseid, $scaleid) {
6017 global $CFG;
6019 $return = 0;
6021 if (!empty($scaleid)) {
6022 if ($cms = get_course_mods($courseid)) {
6023 foreach ($cms as $cm) {
6024 //Check cm->name/lib.php exists
6025 if (file_exists($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php')) {
6026 include_once($CFG->dirroot.'/mod/'.$cm->modname.'/lib.php');
6027 $function_name = $cm->modname.'_scale_used';
6028 if (function_exists($function_name)) {
6029 if ($function_name($cm->instance,$scaleid)) {
6030 $return++;
6037 return $return;
6041 * This function returns the nummber of activities
6042 * using scaleid in the entire site
6044 * @param int $scaleid ?
6045 * @return int
6046 * @todo Finish documenting this function. Is return type correct?
6048 function site_scale_used($scaleid,&$courses) {
6050 global $CFG;
6052 $return = 0;
6054 if (!is_array($courses) || count($courses) == 0) {
6055 $courses = get_courses("all",false,"c.id,c.shortname");
6058 if (!empty($scaleid)) {
6059 if (is_array($courses) && count($courses) > 0) {
6060 foreach ($courses as $course) {
6061 $return += course_scale_used($course->id,$scaleid);
6065 return $return;
6069 * make_unique_id_code
6071 * @param string $extra ?
6072 * @return string
6073 * @todo Finish documenting this function
6075 function make_unique_id_code($extra='') {
6077 $hostname = 'unknownhost';
6078 if (!empty($_SERVER['HTTP_HOST'])) {
6079 $hostname = $_SERVER['HTTP_HOST'];
6080 } else if (!empty($_ENV['HTTP_HOST'])) {
6081 $hostname = $_ENV['HTTP_HOST'];
6082 } else if (!empty($_SERVER['SERVER_NAME'])) {
6083 $hostname = $_SERVER['SERVER_NAME'];
6084 } else if (!empty($_ENV['SERVER_NAME'])) {
6085 $hostname = $_ENV['SERVER_NAME'];
6088 $date = gmdate("ymdHis");
6090 $random = random_string(6);
6092 if ($extra) {
6093 return $hostname .'+'. $date .'+'. $random .'+'. $extra;
6094 } else {
6095 return $hostname .'+'. $date .'+'. $random;
6101 * Function to check the passed address is within the passed subnet
6103 * The parameter is a comma separated string of subnet definitions.
6104 * Subnet strings can be in one of three formats:
6105 * 1: xxx.xxx.xxx.xxx/xx
6106 * 2: xxx.xxx
6107 * 3: xxx.xxx.xxx.xxx-xxx //a range of IP addresses in the last group.
6108 * Code for type 1 modified from user posted comments by mediator at
6109 * {@link http://au.php.net/manual/en/function.ip2long.php}
6111 * @param string $addr The address you are checking
6112 * @param string $subnetstr The string of subnet addresses
6113 * @return bool
6115 function address_in_subnet($addr, $subnetstr) {
6117 $subnets = explode(',', $subnetstr);
6118 $found = false;
6119 $addr = trim($addr);
6121 foreach ($subnets as $subnet) {
6122 $subnet = trim($subnet);
6123 if (strpos($subnet, '/') !== false) { /// type 1
6124 list($ip, $mask) = explode('/', $subnet);
6125 $mask = 0xffffffff << (32 - $mask);
6126 $found = ((ip2long($addr) & $mask) == (ip2long($ip) & $mask));
6127 } else if (strpos($subnet, '-') !== false) {/// type 3
6128 $subnetparts = explode('.', $subnet);
6129 $addrparts = explode('.', $addr);
6130 $subnetrange = explode('-', array_pop($subnetparts));
6131 if (count($subnetrange) == 2) {
6132 $lastaddrpart = array_pop($addrparts);
6133 $found = ($subnetparts == $addrparts &&
6134 $subnetrange[0] <= $lastaddrpart && $lastaddrpart <= $subnetrange[1]);
6136 } else { /// type 2
6137 $found = (strpos($addr, $subnet) === 0);
6140 if ($found) {
6141 break;
6144 return $found;
6148 * This function sets the $HTTPSPAGEREQUIRED global
6149 * (used in some parts of moodle to change some links)
6150 * and calculate the proper wwwroot to be used
6152 * By using this function properly, we can ensure 100% https-ized pages
6153 * at our entire discretion (login, forgot_password, change_password)
6155 function httpsrequired() {
6157 global $CFG, $HTTPSPAGEREQUIRED;
6159 if (!empty($CFG->loginhttps)) {
6160 $HTTPSPAGEREQUIRED = true;
6161 $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
6162 $CFG->httpsthemewww = str_replace('http:', 'https:', $CFG->themewww);
6164 // change theme URLs to https
6165 theme_setup();
6167 } else {
6168 $CFG->httpswwwroot = $CFG->wwwroot;
6169 $CFG->httpsthemewww = $CFG->themewww;
6174 * For outputting debugging info
6176 * @uses STDOUT
6177 * @param string $string ?
6178 * @param string $eol ?
6179 * @todo Finish documenting this function
6181 function mtrace($string, $eol="\n", $sleep=0) {
6183 if (defined('STDOUT')) {
6184 fwrite(STDOUT, $string.$eol);
6185 } else {
6186 echo $string . $eol;
6189 flush();
6191 //delay to keep message on user's screen in case of subsequent redirect
6192 if ($sleep) {
6193 sleep($sleep);
6197 //Replace 1 or more slashes or backslashes to 1 slash
6198 function cleardoubleslashes ($path) {
6199 return preg_replace('/(\/|\\\){1,}/','/',$path);
6202 function zip_files ($originalfiles, $destination) {
6203 //Zip an array of files/dirs to a destination zip file
6204 //Both parameters must be FULL paths to the files/dirs
6206 global $CFG;
6208 //Extract everything from destination
6209 $path_parts = pathinfo(cleardoubleslashes($destination));
6210 $destpath = $path_parts["dirname"]; //The path of the zip file
6211 $destfilename = $path_parts["basename"]; //The name of the zip file
6212 $extension = $path_parts["extension"]; //The extension of the file
6214 //If no file, error
6215 if (empty($destfilename)) {
6216 return false;
6219 //If no extension, add it
6220 if (empty($extension)) {
6221 $extension = 'zip';
6222 $destfilename = $destfilename.'.'.$extension;
6225 //Check destination path exists
6226 if (!is_dir($destpath)) {
6227 return false;
6230 //Check destination path is writable. TODO!!
6232 //Clean destination filename
6233 $destfilename = clean_filename($destfilename);
6235 //Now check and prepare every file
6236 $files = array();
6237 $origpath = NULL;
6239 foreach ($originalfiles as $file) { //Iterate over each file
6240 //Check for every file
6241 $tempfile = cleardoubleslashes($file); // no doubleslashes!
6242 //Calculate the base path for all files if it isn't set
6243 if ($origpath === NULL) {
6244 $origpath = rtrim(cleardoubleslashes(dirname($tempfile)), "/");
6246 //See if the file is readable
6247 if (!is_readable($tempfile)) { //Is readable
6248 continue;
6250 //See if the file/dir is in the same directory than the rest
6251 if (rtrim(cleardoubleslashes(dirname($tempfile)), "/") != $origpath) {
6252 continue;
6254 //Add the file to the array
6255 $files[] = $tempfile;
6258 //Everything is ready:
6259 // -$origpath is the path where ALL the files to be compressed reside (dir).
6260 // -$destpath is the destination path where the zip file will go (dir).
6261 // -$files is an array of files/dirs to compress (fullpath)
6262 // -$destfilename is the name of the zip file (without path)
6264 //print_object($files); //Debug
6266 if (empty($CFG->zip)) { // Use built-in php-based zip function
6268 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6269 //rewrite filenames because the old method with PCLZIP_OPT_REMOVE_PATH does not work under win32
6270 $zipfiles = array();
6271 $start = strlen($origpath)+1;
6272 foreach($files as $file) {
6273 $tf = array();
6274 $tf[PCLZIP_ATT_FILE_NAME] = $file;
6275 $tf[PCLZIP_ATT_FILE_NEW_FULL_NAME] = substr($file, $start);
6276 $zipfiles[] = $tf;
6278 //create the archive
6279 $archive = new PclZip(cleardoubleslashes("$destpath/$destfilename"));
6280 if (($list = $archive->create($zipfiles) == 0)) {
6281 notice($archive->errorInfo(true));
6282 return false;
6285 } else { // Use external zip program
6287 $filestozip = "";
6288 foreach ($files as $filetozip) {
6289 $filestozip .= escapeshellarg(basename($filetozip));
6290 $filestozip .= " ";
6292 //Construct the command
6293 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6294 $command = 'cd '.escapeshellarg($origpath).$separator.
6295 escapeshellarg($CFG->zip).' -r '.
6296 escapeshellarg(cleardoubleslashes("$destpath/$destfilename")).' '.$filestozip;
6297 //All converted to backslashes in WIN
6298 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6299 $command = str_replace('/','\\',$command);
6301 Exec($command);
6303 return true;
6306 function unzip_file ($zipfile, $destination = '', $showstatus = true) {
6307 //Unzip one zip file to a destination dir
6308 //Both parameters must be FULL paths
6309 //If destination isn't specified, it will be the
6310 //SAME directory where the zip file resides.
6312 global $CFG;
6314 //Extract everything from zipfile
6315 $path_parts = pathinfo(cleardoubleslashes($zipfile));
6316 $zippath = $path_parts["dirname"]; //The path of the zip file
6317 $zipfilename = $path_parts["basename"]; //The name of the zip file
6318 $extension = $path_parts["extension"]; //The extension of the file
6320 //If no file, error
6321 if (empty($zipfilename)) {
6322 return false;
6325 //If no extension, error
6326 if (empty($extension)) {
6327 return false;
6330 //Clear $zipfile
6331 $zipfile = cleardoubleslashes($zipfile);
6333 //Check zipfile exists
6334 if (!file_exists($zipfile)) {
6335 return false;
6338 //If no destination, passed let's go with the same directory
6339 if (empty($destination)) {
6340 $destination = $zippath;
6343 //Clear $destination
6344 $destpath = rtrim(cleardoubleslashes($destination), "/");
6346 //Check destination path exists
6347 if (!is_dir($destpath)) {
6348 return false;
6351 //Check destination path is writable. TODO!!
6353 //Everything is ready:
6354 // -$zippath is the path where the zip file resides (dir)
6355 // -$zipfilename is the name of the zip file (without path)
6356 // -$destpath is the destination path where the zip file will uncompressed (dir)
6358 $list = null;
6360 if (empty($CFG->unzip)) { // Use built-in php-based unzip function
6362 include_once("$CFG->libdir/pclzip/pclzip.lib.php");
6363 $archive = new PclZip(cleardoubleslashes("$zippath/$zipfilename"));
6364 if (!$list = $archive->extract(PCLZIP_OPT_PATH, $destpath,
6365 PCLZIP_CB_PRE_EXTRACT, 'unzip_cleanfilename',
6366 PCLZIP_OPT_EXTRACT_DIR_RESTRICTION, $destpath)) {
6367 notice($archive->errorInfo(true));
6368 return false;
6371 } else { // Use external unzip program
6373 $separator = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? ' &' : ' ;';
6374 $redirection = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' ? '' : ' 2>&1';
6376 $command = 'cd '.escapeshellarg($zippath).$separator.
6377 escapeshellarg($CFG->unzip).' -o '.
6378 escapeshellarg(cleardoubleslashes("$zippath/$zipfilename")).' -d '.
6379 escapeshellarg($destpath).$redirection;
6380 //All converted to backslashes in WIN
6381 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6382 $command = str_replace('/','\\',$command);
6384 Exec($command,$list);
6387 //Display some info about the unzip execution
6388 if ($showstatus) {
6389 unzip_show_status($list,$destpath);
6392 return true;
6395 function unzip_cleanfilename ($p_event, &$p_header) {
6396 //This function is used as callback in unzip_file() function
6397 //to clean illegal characters for given platform and to prevent directory traversal.
6398 //Produces the same result as info-zip unzip.
6399 $p_header['filename'] = ereg_replace('[[:cntrl:]]', '', $p_header['filename']); //strip control chars first!
6400 $p_header['filename'] = ereg_replace('\.\.+', '', $p_header['filename']); //directory traversal protection
6401 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
6402 $p_header['filename'] = ereg_replace('[:*"?<>|]', '_', $p_header['filename']); //replace illegal chars
6403 $p_header['filename'] = ereg_replace('^([a-zA-Z])_', '\1:', $p_header['filename']); //repair drive letter
6404 } else {
6405 //Add filtering for other systems here
6406 // BSD: none (tested)
6407 // Linux: ??
6408 // MacosX: ??
6410 $p_header['filename'] = cleardoubleslashes($p_header['filename']); //normalize the slashes/backslashes
6411 return 1;
6414 function unzip_show_status ($list,$removepath) {
6415 //This function shows the results of the unzip execution
6416 //depending of the value of the $CFG->zip, results will be
6417 //text or an array of files.
6419 global $CFG;
6421 if (empty($CFG->unzip)) { // Use built-in php-based zip function
6422 $strname = get_string("name");
6423 $strsize = get_string("size");
6424 $strmodified = get_string("modified");
6425 $strstatus = get_string("status");
6426 echo "<table width=\"640\">";
6427 echo "<tr><th class=\"header\" scope=\"col\">$strname</th>";
6428 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strsize</th>";
6429 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strmodified</th>";
6430 echo "<th class=\"header\" align=\"right\" scope=\"col\">$strstatus</th></tr>";
6431 foreach ($list as $item) {
6432 echo "<tr>";
6433 $item['filename'] = str_replace(cleardoubleslashes($removepath).'/', "", $item['filename']);
6434 print_cell("left", s($item['filename']));
6435 if (! $item['folder']) {
6436 print_cell("right", display_size($item['size']));
6437 } else {
6438 echo "<td>&nbsp;</td>";
6440 $filedate = userdate($item['mtime'], get_string("strftimedatetime"));
6441 print_cell("right", $filedate);
6442 print_cell("right", $item['status']);
6443 echo "</tr>";
6445 echo "</table>";
6447 } else { // Use external zip program
6448 print_simple_box_start("center");
6449 echo "<pre>";
6450 foreach ($list as $item) {
6451 echo s(str_replace(cleardoubleslashes($removepath.'/'), '', $item)).'<br />';
6453 echo "</pre>";
6454 print_simple_box_end();
6459 * Returns most reliable client address
6461 * @return string The remote IP address
6463 function getremoteaddr() {
6464 if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
6465 return cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
6467 if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
6468 return cleanremoteaddr($_SERVER['HTTP_X_FORWARDED_FOR']);
6470 if (!empty($_SERVER['REMOTE_ADDR'])) {
6471 return cleanremoteaddr($_SERVER['REMOTE_ADDR']);
6473 return '';
6477 * Cleans a remote address ready to put into the log table
6479 function cleanremoteaddr($addr) {
6480 $originaladdr = $addr;
6481 $matches = array();
6482 // first get all things that look like IP addresses.
6483 if (!preg_match_all('/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/',$addr,$matches,PREG_SET_ORDER)) {
6484 return '';
6486 $goodmatches = array();
6487 $lanmatches = array();
6488 foreach ($matches as $match) {
6489 // print_r($match);
6490 // check to make sure it's not an internal address.
6491 // the following are reserved for private lans...
6492 // 10.0.0.0 - 10.255.255.255
6493 // 172.16.0.0 - 172.31.255.255
6494 // 192.168.0.0 - 192.168.255.255
6495 // 169.254.0.0 -169.254.255.255
6496 $bits = explode('.',$match[0]);
6497 if (count($bits) != 4) {
6498 // weird, preg match shouldn't give us it.
6499 continue;
6501 if (($bits[0] == 10)
6502 || ($bits[0] == 172 && $bits[1] >= 16 && $bits[1] <= 31)
6503 || ($bits[0] == 192 && $bits[1] == 168)
6504 || ($bits[0] == 169 && $bits[1] == 254)) {
6505 $lanmatches[] = $match[0];
6506 continue;
6508 // finally, it's ok
6509 $goodmatches[] = $match[0];
6511 if (!count($goodmatches)) {
6512 // perhaps we have a lan match, it's probably better to return that.
6513 if (!count($lanmatches)) {
6514 return '';
6515 } else {
6516 return array_pop($lanmatches);
6519 if (count($goodmatches) == 1) {
6520 return $goodmatches[0];
6522 error_log("NOTICE: cleanremoteaddr gives us something funny: $originaladdr had ".count($goodmatches)." matches");
6523 // we need to return something, so
6524 return array_pop($goodmatches);
6528 * file_put_contents is only supported by php 5.0 and higher
6529 * so if it is not predefined, define it here
6531 * @param $file full path of the file to write
6532 * @param $contents contents to be sent
6533 * @return number of bytes written (false on error)
6535 if(!function_exists('file_put_contents')) {
6536 function file_put_contents($file, $contents) {
6537 $result = false;
6538 if ($f = fopen($file, 'w')) {
6539 $result = fwrite($f, $contents);
6540 fclose($f);
6542 return $result;
6547 * The clone keyword is only supported from PHP 5 onwards.
6548 * The behaviour of $obj2 = $obj1 differs fundamentally
6549 * between PHP 4 and PHP 5. In PHP 4 a copy of $obj1 was
6550 * created, in PHP 5 $obj1 is referenced. To create a copy
6551 * in PHP 5 the clone keyword was introduced. This function
6552 * simulates this behaviour for PHP < 5.0.0.
6553 * See also: http://mjtsai.com/blog/2004/07/15/php-5-object-references/
6555 * Modified 2005-09-29 by Eloy (from Julian Sedding proposal)
6556 * Found a better implementation (more checks and possibilities) from PEAR:
6557 * http://cvs.php.net/co.php/pear/PHP_Compat/Compat/Function/clone.php
6559 * @param object $obj
6560 * @return object
6562 if(!check_php_version('5.0.0')) {
6563 // the eval is needed to prevent PHP 5 from getting a parse error!
6564 eval('
6565 function clone($obj) {
6566 /// Sanity check
6567 if (!is_object($obj)) {
6568 user_error(\'clone() __clone method called on non-object\', E_USER_WARNING);
6569 return;
6572 /// Use serialize/unserialize trick to deep copy the object
6573 $obj = unserialize(serialize($obj));
6575 /// If there is a __clone method call it on the "new" class
6576 if (method_exists($obj, \'__clone\')) {
6577 $obj->__clone();
6580 return $obj;
6583 // Supply the PHP5 function scandir() to older versions.
6584 function scandir($directory) {
6585 $files = array();
6586 if ($dh = opendir($directory)) {
6587 while (($file = readdir($dh)) !== false) {
6588 $files[] = $file;
6590 closedir($dh);
6592 return $files;
6595 // Supply the PHP5 function array_combine() to older versions.
6596 function array_combine($keys, $values) {
6597 if (!is_array($keys) || !is_array($values) || count($keys) != count($values)) {
6598 return false;
6600 reset($values);
6601 $result = array();
6602 foreach ($keys as $key) {
6603 $result[$key] = current($values);
6604 next($values);
6606 return $result;
6612 * This function will make a complete copy of anything it's given,
6613 * regardless of whether it's an object or not.
6614 * @param mixed $thing
6615 * @return mixed
6617 function fullclone($thing) {
6618 return unserialize(serialize($thing));
6623 * This function expects to called during shutdown
6624 * should be set via register_shutdown_function()
6625 * in lib/setup.php .
6627 * Right now we do it only if we are under apache, to
6628 * make sure apache children that hog too much mem are
6629 * killed.
6632 function moodle_request_shutdown() {
6634 global $CFG;
6636 // initially, we are only ever called under apache
6637 // but check just in case
6638 if (function_exists('apache_child_terminate')
6639 && function_exists('memory_get_usage')
6640 && ini_get_bool('child_terminate')) {
6641 if (empty($CFG->apachemaxmem)) {
6642 $CFG->apachemaxmem = 25000000; // default 25MiB
6644 if (memory_get_usage() > (int)$CFG->apachemaxmem) {
6645 trigger_error('Mem usage over $CFG->apachemaxmem: marking child for reaping.');
6646 @apache_child_terminate();
6652 * If new messages are waiting for the current user, then return
6653 * Javascript code to create a popup window
6655 * @return string Javascript code
6657 function message_popup_window() {
6658 global $USER;
6660 $popuplimit = 30; // Minimum seconds between popups
6662 if (!defined('MESSAGE_WINDOW')) {
6663 if (isset($USER->id)) {
6664 if (!isset($USER->message_lastpopup)) {
6665 $USER->message_lastpopup = 0;
6667 if ((time() - $USER->message_lastpopup) > $popuplimit) { /// It's been long enough
6668 if (get_user_preferences('message_showmessagewindow', 1) == 1) {
6669 if (count_records_select('message', 'useridto = \''.$USER->id.'\' AND timecreated > \''.$USER->message_lastpopup.'\'')) {
6670 $USER->message_lastpopup = time();
6671 return '<script type="text/javascript">'."\n//<![CDATA[\n openpopup('/message/index.php', 'message',
6672 'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500', 0);\n//]]>\n</script>";
6679 return '';
6682 // Used to make sure that $min <= $value <= $max
6683 function bounded_number($min, $value, $max) {
6684 if($value < $min) {
6685 return $min;
6687 if($value > $max) {
6688 return $max;
6690 return $value;
6693 function array_is_nested($array) {
6694 foreach ($array as $value) {
6695 if (is_array($value)) {
6696 return true;
6699 return false;
6703 *** get_performance_info() pairs up with init_performance_info()
6704 *** loaded in setup.php. Returns an array with 'html' and 'txt'
6705 *** values ready for use, and each of the individual stats provided
6706 *** separately as well.
6709 function get_performance_info() {
6710 global $CFG, $PERF, $rcache;
6712 $info = array();
6713 $info['html'] = ''; // holds userfriendly HTML representation
6714 $info['txt'] = me() . ' '; // holds log-friendly representation
6716 $info['realtime'] = microtime_diff($PERF->starttime, microtime());
6718 $info['html'] .= '<span class="timeused">'.$info['realtime'].' secs</span> ';
6719 $info['txt'] .= 'time: '.$info['realtime'].'s ';
6721 if (function_exists('memory_get_usage')) {
6722 $info['memory_total'] = memory_get_usage();
6723 $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
6724 $info['html'] .= '<span class="memoryused">RAM: '.display_size($info['memory_total']).'</span> ';
6725 $info['txt'] .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.$info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
6728 $inc = get_included_files();
6729 //error_log(print_r($inc,1));
6730 $info['includecount'] = count($inc);
6731 $info['html'] .= '<span class="included">Included '.$info['includecount'].' files</span> ';
6732 $info['txt'] .= 'includecount: '.$info['includecount'].' ';
6734 if (!empty($PERF->dbqueries)) {
6735 $info['dbqueries'] = $PERF->dbqueries;
6736 $info['html'] .= '<span class="dbqueries">DB queries '.$info['dbqueries'].'</span> ';
6737 $info['txt'] .= 'dbqueries: '.$info['dbqueries'].' ';
6740 if (!empty($PERF->logwrites)) {
6741 $info['logwrites'] = $PERF->logwrites;
6742 $info['html'] .= '<span class="logwrites">Log writes '.$info['logwrites'].'</span> ';
6743 $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
6746 if (!empty($PERF->profiling) && $PERF->profiling) {
6747 require_once($CFG->dirroot .'/lib/profilerlib.php');
6748 $info['html'] .= '<span class="profilinginfo">'.Profiler::get_profiling(array('-R')).'</span>';
6751 if (function_exists('posix_times')) {
6752 $ptimes = posix_times();
6753 if (is_array($ptimes)) {
6754 foreach ($ptimes as $key => $val) {
6755 $info[$key] = $ptimes[$key] - $PERF->startposixtimes[$key];
6757 $info['html'] .= "<span class=\"posixtimes\">ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</span> ";
6758 $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
6762 // Grab the load average for the last minute
6763 // /proc will only work under some linux configurations
6764 // while uptime is there under MacOSX/Darwin and other unices
6765 if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
6766 list($server_load) = explode(' ', $loadavg[0]);
6767 unset($loadavg);
6768 } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
6769 if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
6770 $server_load = $matches[1];
6771 } else {
6772 trigger_error('Could not parse uptime output!');
6775 if (!empty($server_load)) {
6776 $info['serverload'] = $server_load;
6777 $info['html'] .= '<span class="serverload">Load average: '.$info['serverload'].'</span> ';
6778 $info['txt'] .= "serverload: {$info['serverload']} ";
6781 if (isset($rcache->hits) && isset($rcache->misses)) {
6782 $info['rcachehits'] = $rcache->hits;
6783 $info['rcachemisses'] = $rcache->misses;
6784 $info['html'] .= '<span class="rcache">Record cache hit/miss ratio : '.
6785 "{$rcache->hits}/{$rcache->misses}</span> ";
6786 $info['txt'] .= 'rcache: '.
6787 "{$rcache->hits}/{$rcache->misses} ";
6789 $info['html'] = '<div class="performanceinfo">'.$info['html'].'</div>';
6790 return $info;
6793 function apd_get_profiling() {
6794 return shell_exec('pprofp -u ' . ini_get('apd.dumpdir') . '/pprof.' . getmypid() . '.*');
6797 function remove_dir($dir, $content_only=false) {
6798 // if content_only=true then delete all but
6799 // the directory itself
6801 $handle = opendir($dir);
6802 while (false!==($item = readdir($handle))) {
6803 if($item != '.' && $item != '..') {
6804 if(is_dir($dir.'/'.$item)) {
6805 remove_dir($dir.'/'.$item);
6806 }else{
6807 unlink($dir.'/'.$item);
6811 closedir($handle);
6812 if ($content_only) {
6813 return true;
6815 return rmdir($dir);
6819 * Function to check if a directory exists and optionally create it.
6821 * @param string absolute directory path
6822 * @param boolean create directory if does not exist
6823 * @param boolean create directory recursively
6825 * @return boolean true if directory exists or created
6827 function check_dir_exists($dir, $create=false, $recursive=false) {
6829 global $CFG;
6831 $status = true;
6833 if(!is_dir($dir)) {
6834 if (!$create) {
6835 $status = false;
6836 } else {
6837 umask(0000);
6838 if ($recursive) {
6839 // PHP 5.0 has recursive mkdir parameter, but 4.x does not :-(
6840 $dir = str_replace('\\', '/', $dir); //windows compatibility
6841 $dirs = explode('/', $dir);
6842 $dir = array_shift($dirs).'/'; //skip root or drive letter
6843 foreach ($dirs as $part) {
6844 if ($part == '') {
6845 continue;
6847 $dir .= $part.'/';
6848 if (!is_dir($dir)) {
6849 if (!mkdir($dir, $CFG->directorypermissions)) {
6850 $status = false;
6851 break;
6855 } else {
6856 $status = mkdir($dir, $CFG->directorypermissions);
6860 return $status;
6863 function report_session_error() {
6864 global $CFG, $FULLME;
6866 if (empty($CFG->lang)) {
6867 $CFG->lang = "en";
6869 // Set up default theme and locale
6870 theme_setup();
6871 moodle_setlocale();
6873 //clear session cookies
6874 setcookie('MoodleSession'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
6875 setcookie('MoodleSessionTest'.$CFG->sessioncookie, '', time() - 3600, $CFG->sessioncookiepath);
6876 //increment database error counters
6877 if (isset($CFG->session_error_counter)) {
6878 set_config('session_error_counter', 1 + $CFG->session_error_counter);
6879 } else {
6880 set_config('session_error_counter', 1);
6882 redirect($FULLME, get_string('sessionerroruser2', 'error'), 5);
6887 * Detect if an object or a class contains a given property
6888 * will take an actual object or the name of a class
6889 * @param mix $obj Name of class or real object to test
6890 * @param string $property name of property to find
6891 * @return bool true if property exists
6893 function object_property_exists( $obj, $property ) {
6894 if (is_string( $obj )) {
6895 $properties = get_class_vars( $obj );
6897 else {
6898 $properties = get_object_vars( $obj );
6900 return array_key_exists( $property, $properties );
6905 * Detect a custom script replacement in the data directory that will
6906 * replace an existing moodle script
6907 * @param string $urlpath path to the original script
6908 * @return string full path name if a custom script exists
6909 * @return bool false if no custom script exists
6911 function custom_script_path($urlpath='') {
6912 global $CFG;
6914 // set default $urlpath, if necessary
6915 if (empty($urlpath)) {
6916 $urlpath = qualified_me(); // e.g. http://www.this-server.com/moodle/this-script.php
6919 // $urlpath is invalid if it is empty or does not start with the Moodle wwwroot
6920 if (empty($urlpath) or (strpos($urlpath, $CFG->wwwroot) === false )) {
6921 return false;
6924 // replace wwwroot with the path to the customscripts folder and clean path
6925 $scriptpath = $CFG->customscripts . clean_param(substr($urlpath, strlen($CFG->wwwroot)), PARAM_PATH);
6927 // remove the query string, if any
6928 if (($strpos = strpos($scriptpath, '?')) !== false) {
6929 $scriptpath = substr($scriptpath, 0, $strpos);
6932 // remove trailing slashes, if any
6933 $scriptpath = rtrim($scriptpath, '/\\');
6935 // append index.php, if necessary
6936 if (is_dir($scriptpath)) {
6937 $scriptpath .= '/index.php';
6940 // check the custom script exists
6941 if (file_exists($scriptpath)) {
6942 return $scriptpath;
6943 } else {
6944 return false;
6949 * Wrapper function to load necessary editor scripts
6950 * to $CFG->editorsrc array. Params can be coursei id
6951 * or associative array('courseid' => value, 'name' => 'editorname').
6952 * @uses $CFG
6953 * @param mixed $args Courseid or associative array.
6955 function loadeditor($args) {
6956 global $CFG;
6957 include($CFG->libdir .'/editorlib.php');
6958 return editorObject::loadeditor($args);
6962 * Returns whether or not the user object is a remote MNET user. This function
6963 * is in moodlelib because it does not rely on loading any of the MNET code.
6965 * @param object $user A valid user object
6966 * @return bool True if the user is from a remote Moodle.
6968 function is_mnet_remote_user($user) {
6969 global $CFG;
6971 if (!isset($CFG->mnet_localhost_id)) {
6972 include_once $CFG->dirroot . '/mnet/lib.php';
6973 $env = new mnet_environment();
6974 $env->init();
6975 unset($env);
6978 return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
6982 * Checks if a given plugin is in the list of enabled enrolment plugins.
6984 * @param string $auth Enrolment plugin.
6985 * @return boolean Whether the plugin is enabled.
6987 function is_enabled_enrol($enrol='') {
6988 global $CFG;
6990 // use the global default if not specified
6991 if ($enrol == '') {
6992 $enrol = $CFG->enrol;
6994 return in_array($enrol, explode(',', $CFG->enrol_plugins_enabled));
6998 * This function will search for browser prefereed languages, setting Moodle
6999 * to use the best one available if $SESSION->lang is undefined
7001 function setup_lang_from_browser() {
7003 global $CFG, $SESSION, $USER;
7005 if (!empty($SESSION->lang) or !empty($USER->lang)) {
7006 // Lang is defined in session or user profile, nothing to do
7007 return;
7010 if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do
7011 return;
7014 /// Extract and clean langs from headers
7015 $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
7016 $rawlangs = str_replace('-', '_', $rawlangs); // we are using underscores
7017 $rawlangs = explode(',', $rawlangs); // Convert to array
7018 $langs = array();
7020 $order = 1.0;
7021 foreach ($rawlangs as $lang) {
7022 if (strpos($lang, ';') === false) {
7023 $langs[(string)$order] = $lang;
7024 $order = $order-0.01;
7025 } else {
7026 $parts = explode(';', $lang);
7027 $pos = strpos($parts[1], '=');
7028 $langs[substr($parts[1], $pos+1)] = $parts[0];
7031 krsort($langs, SORT_NUMERIC);
7033 $langlist = get_list_of_languages();
7035 /// Look for such langs under standard locations
7036 foreach ($langs as $lang) {
7037 $lang = strtolower(clean_param($lang.'_utf8', PARAM_SAFEDIR)); // clean it properly for include
7038 if (!array_key_exists($lang, $langlist)) {
7039 continue; // language not allowed, try next one
7041 if (file_exists($CFG->dataroot .'/lang/'. $lang) or file_exists($CFG->dirroot .'/lang/'. $lang)) {
7042 $SESSION->lang = $lang; /// Lang exists, set it in session
7043 break; /// We have finished. Go out
7046 return;
7050 ////////////////////////////////////////////////////////////////////////////////
7052 * This function will build the navigation string to be used by print_header
7053 * and others
7054 * @uses $CFG
7055 * @uses $THEME
7056 * @param $extranavlinks - array of associative arrays, keys: name, link, type
7057 * @return $navigation as an object so it can be differentiated from old style
7058 * navigation strings.
7060 function build_navigation($extranavlinks) {
7061 global $CFG, $COURSE;
7063 $navigation = '';
7064 $navlinks = array();
7066 //Site name
7067 if ($site = get_site()) {
7068 $navlinks[] = array('name' => format_string($site->shortname), 'link' => "$CFG->wwwroot/", 'type' => 'home');
7072 if ($COURSE) {
7073 if ($COURSE->id != SITEID) {
7074 //Course
7075 $navlinks[] = array('name' => format_string($COURSE->shortname), 'link' => "$CFG->wwwroot/course/view.php?id=$COURSE->id",'type' => 'course');
7079 //Merge in extra navigation links
7080 $navlinks = array_merge($navlinks, $extranavlinks);
7082 //Construct an unordered list from $navlinks
7083 //Accessibility: heading hidden from visual browsers by default.
7084 $navigation = '<h2 class="accesshide">'.get_string('youarehere','access')."</h2> <ul>\n";
7085 $countlinks = count($navlinks);
7087 for($i=0;$i<$countlinks;$i++) {
7089 // Check the link type to see if this link should appear in the trail
7090 if ($navlinks[$i]['type'] == 'activity' && $i+1 < $countlinks && ($CFG->hideactivitytypenavlink == 2 || ($CFG->hideactivitytypenavlink == 1 && !has_capability('moodle/course:manageactivities', get_context_instance(CONTEXT_COURSE, $course->id))))) {
7091 continue;
7093 $navigation .= '<li class="first">';
7094 if ($i > 0) {
7095 $navigation .= get_separator();
7097 if ($navlinks[$i]['link'] && $i+1 < $countlinks) {
7098 $navigation .= "<a onclick=\"this.target='$CFG->framename'\" href=\"{$navlinks[$i]['link']}\">";
7100 $navigation .= "{$navlinks[$i]['name']}";
7101 if ($navlinks[$i]['link'] && $i+1 < $countlinks) {
7102 $navigation .= "</a>";
7105 $navigation .= "</li>";
7108 $navigation .= "</ul>";
7110 return(array('newnav' => true, 'navlinks' => $navigation));
7113 function is_newnav($navigation) {
7114 if (is_array($navigation) && $navigation['newnav']) {
7115 return(true);
7116 } else {
7117 return(false);
7122 * Checks whether the given variable name is defined as a variable within the given object.
7123 * @note This will NOT work with stdClass objects, which have no class variables.
7124 * @param string $var The variable name
7125 * @param object $object The object to check
7126 * @return boolean
7128 function in_object_vars($var, $object)
7130 $class_vars = get_class_vars(get_class($object));
7131 $class_vars = array_keys($class_vars);
7132 return in_array($var, $class_vars);
7135 // vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140: