Double quote strings converted to single quote literals - inspired by missing escape...
[moodle.git] / lib / moodlelib.php
CommitLineData
7cf1c7bd 1<?php
f9903ed0 2
9fa49e22 3///////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Modular Object-Oriented Dynamic Learning Environment //
abc3b857 8// http://moodle.org //
9fa49e22 9// //
abc3b857 10// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
9fa49e22 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///////////////////////////////////////////////////////////////////////////
65ccdd8c 25
7cf1c7bd 26/**
27 * Moodle main library
28 *
29 * Main library file of miscellaneous general-purpose Moodle functions.
30 * Other main libraries:
8c3dba73 31 * - weblib.php - functions that produce web output
32 * - datalib.php - functions that access the database
7cf1c7bd 33 * @author Martin Dougiamas
34 * @version $Id$
35 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
36 * @package moodlecore
37 */
f374fb10 38/// CONSTANTS /////////////////////////////////////////////////////////////
39
7cf1c7bd 40/**
41 * No groups used?
42 */
d8ba183c 43define('NOGROUPS', 0);
7cf1c7bd 44
45/**
46 * Groups used?
47 */
f374fb10 48define('SEPARATEGROUPS', 1);
7cf1c7bd 49
50/**
51 * Groups visible?
52 */
f374fb10 53define('VISIBLEGROUPS', 2);
54
f9903ed0 55
9fa49e22 56/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 57
7cf1c7bd 58/**
59 * Ensure that a variable is set or display error
60 *
61 * If $var is undefined display an error message using the {@link error()} function.
62 *
63 * @param mixed $var the variable which may not be set
64 */
9fa49e22 65function require_variable($var) {
66/// Variable must be present
67 if (! isset($var)) {
b0ccd3fb 68 error('A required parameter was missing');
6b174680 69 }
70}
71
7cf1c7bd 72
73/**
74 * Ensure that a variable is set
75 *
76 * If $var is undefined set it (by reference), otherwise return $var.
77 * This function is very similar to {@link nvl()}
78 *
79 * @param mixed $var the variable which may be unset
80 * @param mixed $default the value to return if $var is unset
81 */
9fa49e22 82function optional_variable(&$var, $default=0) {
83/// Variable may be present, if not then set a default
84 if (! isset($var)) {
85 $var = $default;
6b174680 86 }
87}
88
7cf1c7bd 89/**
90 * Set a key in global configuration
91 *
92 * Set a key/value pair in both this session's $CFG global variable
93 * and in the 'config' database table for future sessions.
94 *
95 * @param string $name the key to set
96 * @param string $value the value to set
97 * @uses $CFG
98 * @return bool
99 */
9fa49e22 100function set_config($name, $value) {
101/// No need for get_config because they are usually always available in $CFG
70812e39 102
42282810 103 global $CFG;
104
7cf1c7bd 105
42282810 106 $CFG->$name = $value; // So it's defined for this invocation at least
dfc9ba9b 107
b0ccd3fb 108 if (get_field('config', 'name', 'name', $name)) {
109 return set_field('config', 'value', $value, 'name', $name);
d897cae4 110 } else {
9fa49e22 111 $config->name = $name;
112 $config->value = $value;
b0ccd3fb 113 return insert_record('config', $config);
39917a09 114 }
39917a09 115}
116
7cf1c7bd 117/**
118 * Refresh current $USER session global variable with all their current preferences.
119 * @uses $USER
120 */
70812e39 121function reload_user_preferences() {
70812e39 122
123 global $USER;
124
d8ba183c 125 unset($USER->preference);
70812e39 126
127 if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
128 foreach ($preferences as $preference) {
129 $USER->preference[$preference->name] = $preference->value;
130 }
4586d60c 131 } else {
132 //return empty preference array to hold new values
133 $USER->preference = array();
134 }
70812e39 135}
136
7cf1c7bd 137/**
138 * Sets a preference for the current user
139 * Optionally, can set a preference for a different user object
140 * @uses $USER
141 * @todo Add a better description and include usage examples.
142 * @param string $name The key to set as preference for the specified user
143 * @param string $value The value to set forthe $name key in the specified user's record
6eb3e776 144 * @param integer $userid A moodle user ID
7cf1c7bd 145 * @todo Add inline links to $USER and user functions in above line.
146 * @return boolean
147 */
a3f1f815 148function set_user_preference($name, $value, $userid=NULL) {
70812e39 149
150 global $USER;
151
a3f1f815 152 if (empty($userid)){
153 $userid = $USER->id;
d35757eb 154 }
155
70812e39 156 if (empty($name)) {
157 return false;
158 }
159
a3f1f815 160 if ($preference = get_record('user_preferences', 'userid', $userid, 'name', $name)) {
b0ccd3fb 161 if (set_field('user_preferences', 'value', $value, 'id', $preference->id)) {
d35757eb 162 $user->preference[$name] = $value;
066af654 163 return true;
164 } else {
165 return false;
166 }
70812e39 167
168 } else {
a3f1f815 169 $preference->userid = $userid;
70812e39 170 $preference->name = $name;
171 $preference->value = (string)$value;
066af654 172 if (insert_record('user_preferences', $preference)) {
d35757eb 173 $user->preference[$name] = $value;
70812e39 174 return true;
175 } else {
176 return false;
177 }
178 }
179}
180
6eb3e776 181/**
182 * Unsets a preference completely by deleting it from the database
183 * Optionally, can set a preference for a different user id
184 * @uses $USER
185 * @param string $name The key to unset as preference for the specified user
186 * @param integer $userid A moodle user ID
187 * @return boolean
188 */
189function unset_user_preference($name, $userid=NULL) {
190
191 global $USER;
192
193 if (empty($userid)){
194 $userid = $USER->id;
195 }
196
197 return delete_records('user_preferences', 'userid', $userid, 'name', $name);
198}
199
200
7cf1c7bd 201/**
202 * Sets a whole array of preferences for the current user
203 * @param array $prefarray An array of key/value pairs to be set
6eb3e776 204 * @param integer $userid A moodle user ID
7cf1c7bd 205 * @return boolean
206 */
a3f1f815 207function set_user_preferences($prefarray, $userid=NULL) {
208
209 global $USER;
70812e39 210
211 if (!is_array($prefarray) or empty($prefarray)) {
212 return false;
213 }
214
a3f1f815 215 if (empty($userid)){
216 $userid = $USER->id;
217 }
218
70812e39 219 $return = true;
220 foreach ($prefarray as $name => $value) {
221 // The order is important; if the test for return is done first,
222 // then if one function call fails all the remaining ones will
223 // be "optimized away"
a3f1f815 224 $return = set_user_preference($name, $value, $userid) and $return;
70812e39 225 }
226 return $return;
227}
228
7cf1c7bd 229/**
230 * If no arguments are supplied this function will return
231 * all of the current user preferences as an array.
232 * If a name is specified then this function
233 * attempts to return that particular preference value. If
234 * none is found, then the optional value $default is returned,
235 * otherwise NULL.
236 * @param string $name Name of the key to use in finding a preference value
237 * @param string $default Value to be returned if the $name key is not set in the user preferences
6eb3e776 238 * @param integer $userid A moodle user ID
7cf1c7bd 239 * @uses $USER
240 * @return string
241 */
a3f1f815 242function get_user_preferences($name=NULL, $default=NULL, $userid=NULL) {
70812e39 243
244 global $USER;
245
a3f1f815 246 if (empty($userid)) { // assume current user
247 if (empty($USER->preference)) {
248 return $default; // Default value (or NULL)
249 }
250 if (empty($name)) {
251 return $USER->preference; // Whole array
252 }
253 if (!isset($USER->preference[$name])) {
254 return $default; // Default value (or NULL)
255 }
256 return $USER->preference[$name]; // The single value
257
258 } else {
259 $preference = get_records_menu('user_preferences', 'userid', $userid, 'name', 'name,value');
260
261 if (empty($name)) {
262 return $preference;
263 }
264 if (!isset($preference[$name])) {
265 return $default; // Default value (or NULL)
266 }
267 return $preference[$name]; // The single value
70812e39 268 }
70812e39 269}
270
271
9fa49e22 272/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 273
7cf1c7bd 274/**
275 * Given date parts in user time, produce a GMT timestamp.
276 *
277 * @param type description
278 * @todo Finish documenting this function
279 */
3db75c62 280function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99) {
39917a09 281
f30fe8d0 282 $timezone = get_user_timezone($timezone);
94e34118 283
284 if (abs($timezone) > 13) {
03c17ddf 285 return mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
286 } else {
287 $time = gmmktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
288 return usertime($time, $timezone); // This is GMT
289 }
39917a09 290}
291
7cf1c7bd 292/**
293 * Given an amount of time in seconds, returns string
294 * formatted nicely as months, days, hours etc as needed
295 *
296 * @param type description
297 * @todo Finish documenting this function
298 */
299 function format_time($totalsecs, $str=NULL) {
c7e3ac2a 300
6b174680 301 $totalsecs = abs($totalsecs);
c7e3ac2a 302
8dbed6be 303 if (!$str) { // Create the str structure the slow way
b0ccd3fb 304 $str->day = get_string('day');
305 $str->days = get_string('days');
306 $str->hour = get_string('hour');
307 $str->hours = get_string('hours');
308 $str->min = get_string('min');
309 $str->mins = get_string('mins');
310 $str->sec = get_string('sec');
311 $str->secs = get_string('secs');
8dbed6be 312 }
313
314 $days = floor($totalsecs/86400);
6b174680 315 $remainder = $totalsecs - ($days*86400);
8dbed6be 316 $hours = floor($remainder/3600);
6b174680 317 $remainder = $remainder - ($hours*3600);
8dbed6be 318 $mins = floor($remainder/60);
319 $secs = $remainder - ($mins*60);
320
321 $ss = ($secs == 1) ? $str->sec : $str->secs;
322 $sm = ($mins == 1) ? $str->min : $str->mins;
323 $sh = ($hours == 1) ? $str->hour : $str->hours;
324 $sd = ($days == 1) ? $str->day : $str->days;
325
b0ccd3fb 326 $odays = '';
327 $ohours = '';
328 $omins = '';
329 $osecs = '';
9c9f7d77 330
b0ccd3fb 331 if ($days) $odays = $days .' '. $sd;
332 if ($hours) $ohours = $hours .' '. $sh;
333 if ($mins) $omins = $mins .' '. $sm;
334 if ($secs) $osecs = $secs .' '. $ss;
6b174680 335
b0ccd3fb 336 if ($days) return $odays .' '. $ohours;
337 if ($hours) return $ohours .' '. $omins;
338 if ($mins) return $omins .' '. $osecs;
339 if ($secs) return $osecs;
340 return get_string('now');
6b174680 341}
f9903ed0 342
7cf1c7bd 343/**
344 * Returns a formatted string that represents a date in user time
345 * <b>WARNING: note that the format is for strftime(), not date().</b>
346 * Because of a bug in most Windows time libraries, we can't use
347 * the nicer %e, so we have to use %d which has leading zeroes.
348 * A lot of the fuss in the function is just getting rid of these leading
349 * zeroes as efficiently as possible.
350 *
8c3dba73 351 * If parameter fixday = true (default), then take off leading
7cf1c7bd 352 * zero from %d, else mantain it.
353 *
354 * @param type description
355 * @todo Finish documenting this function
356 */
b0ccd3fb 357function userdate($date, $format='', $timezone=99, $fixday = true) {
7a302afc 358
b0ccd3fb 359 if ($format == '') {
360 $format = get_string('strftimedaydatetime');
5fa51a39 361 }
035cdbff 362
b0ccd3fb 363 $formatnoday = str_replace('%d', 'DD', $format);
61ae5d36 364 if ($fixday) {
365 $fixday = ($formatnoday != $format);
366 }
dcde9f02 367
f30fe8d0 368 $timezone = get_user_timezone($timezone);
90207a06 369
0431bd7c 370 if (abs($timezone) > 13) {
035cdbff 371 if ($fixday) {
372 $datestring = strftime($formatnoday, $date);
b0ccd3fb 373 $daystring = str_replace(' 0', '', strftime(" %d", $date));
374 $datestring = str_replace('DD', $daystring, $datestring);
035cdbff 375 } else {
376 $datestring = strftime($format, $date);
377 }
bea7a51e 378 } else {
70d4cf82 379 $date = $date + (int)($timezone * 3600);
035cdbff 380 if ($fixday) {
70d4cf82 381 $datestring = gmstrftime($formatnoday, $date);
b0ccd3fb 382 $daystring = str_replace(' 0', '', gmstrftime(" %d", $date));
383 $datestring = str_replace('DD', $daystring, $datestring);
035cdbff 384 } else {
70d4cf82 385 $datestring = gmstrftime($format, $date);
035cdbff 386 }
873960de 387 }
bea7a51e 388
035cdbff 389 return $datestring;
873960de 390}
391
7cf1c7bd 392/**
393 * Given a $date timestamp in GMT, returns an array
394 * that represents the date in user time
395 *
396 * @param type description
397 * @todo Finish documenting this function
398 */
5fa51a39 399function usergetdate($date, $timezone=99) {
6b174680 400
f30fe8d0 401 $timezone = get_user_timezone($timezone);
a36166d3 402
0431bd7c 403 if (abs($timezone) > 13) {
873960de 404 return getdate($date);
405 }
d2d6171f 406 //There is no gmgetdate so I have to fake it...
407 $date = $date + (int)($timezone * 3600);
b0ccd3fb 408 $getdate['seconds'] = gmstrftime("%S", $date);
409 $getdate['minutes'] = gmstrftime("%M", $date);
410 $getdate['hours'] = gmstrftime("%H", $date);
411 $getdate['mday'] = gmstrftime("%d", $date);
412 $getdate['wday'] = gmstrftime("%u", $date);
413 $getdate['mon'] = gmstrftime("%m", $date);
414 $getdate['year'] = gmstrftime("%Y", $date);
415 $getdate['yday'] = gmstrftime("%j", $date);
416 $getdate['weekday'] = gmstrftime("%A", $date);
417 $getdate['month'] = gmstrftime("%B", $date);
d2d6171f 418 return $getdate;
d552ead0 419}
420
7cf1c7bd 421/**
422 * Given a GMT timestamp (seconds since epoch), offsets it by
423 * the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
424 *
425 * @param type description
426 * @todo Finish documenting this function
427 */
d552ead0 428function usertime($date, $timezone=99) {
a36166d3 429
f30fe8d0 430 $timezone = get_user_timezone($timezone);
0431bd7c 431 if (abs($timezone) > 13) {
d552ead0 432 return $date;
433 }
434 return $date - (int)($timezone * 3600);
435}
436
8c3dba73 437/**
438 * Given a time, return the GMT timestamp of the most recent midnight
439 * for the current user.
440 *
441 * @param type description
442 * @todo Finish documenting this function
443 */
edf7fe8c 444function usergetmidnight($date, $timezone=99) {
edf7fe8c 445
f30fe8d0 446 $timezone = get_user_timezone($timezone);
edf7fe8c 447 $userdate = usergetdate($date, $timezone);
4606d9bb 448
0431bd7c 449 if (abs($timezone) > 13) {
b0ccd3fb 450 return mktime(0, 0, 0, $userdate['mon'], $userdate['mday'], $userdate['year']);
4606d9bb 451 }
452
b0ccd3fb 453 $timemidnight = gmmktime (0, 0, 0, $userdate['mon'], $userdate['mday'], $userdate['year']);
edf7fe8c 454 return usertime($timemidnight, $timezone); // Time of midnight of this user's day, in GMT
455
456}
457
7cf1c7bd 458/**
459 * Returns a string that prints the user's timezone
460 *
461 * @param float $timezone The user's timezone
462 * @return string
463 */
d552ead0 464function usertimezone($timezone=99) {
d552ead0 465
f30fe8d0 466 $timezone = get_user_timezone($timezone);
467
0431bd7c 468 if (abs($timezone) > 13) {
b0ccd3fb 469 return 'server time';
d552ead0 470 }
471 if (abs($timezone) < 0.5) {
b0ccd3fb 472 return 'GMT';
d552ead0 473 }
474 if ($timezone > 0) {
b0ccd3fb 475 return 'GMT+'. $timezone;
d552ead0 476 } else {
b0ccd3fb 477 return 'GMT'. $timezone;
d552ead0 478 }
f9903ed0 479}
480
7cf1c7bd 481/**
482 * Returns a float which represents the user's timezone difference from GMT in hours
483 * Checks various settings and picks the most dominant of those which have a value
484 *
485 * @param float $tz The user's timezone
486 * @return float
487 * @uses $CFG
488 * @uses $USER
489 */
f30fe8d0 490function get_user_timezone($tz = 99) {
f30fe8d0 491
492 // Variables declared explicitly global here so that if we add
493 // something later we won't forget to global it...
494 $timezones = array(
495 isset($GLOBALS['USER']->timezone) ? $GLOBALS['USER']->timezone : 99,
496 isset($GLOBALS['CFG']->timezone) ? $GLOBALS['CFG']->timezone : 99,
497 );
498 while($tz == 99 && $next = each($timezones)) {
499 $tz = (float)$next['value'];
500 }
501
502 return $tz;
503}
f9903ed0 504
9fa49e22 505/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 506
7cf1c7bd 507/**
508 * This function checks that the current user is logged in, and optionally
509 * whether they are "logged in" or allowed to be in a particular course.
510 * If not, then it redirects them to the site login or course enrolment.
511 * $autologinguest determines whether visitors should automatically be
512 * logged in as guests provide $CFG->autologinguests is set to 1
513 *
514 * @param type description
515 * @uses $CFG
516 * @uses $SESSION
517 * @uses $USER
518 * @uses $FULLME
519 * @uses $MoodleSession
520 * @todo Finish documenting this function
521 */
8e8d0524 522function require_login($courseid=0, $autologinguest=true) {
f9903ed0 523
73047f2f 524 global $CFG, $SESSION, $USER, $FULLME, $MoodleSession;
d8ba183c 525
da5c172a 526 // First check that the user is logged in to the site.
c21c671d 527 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
f9903ed0 528 $SESSION->wantsurl = $FULLME;
b0ccd3fb 529 if (!empty($_SERVER['HTTP_REFERER'])) {
530 $SESSION->fromurl = $_SERVER['HTTP_REFERER'];
9f44d972 531 }
c21c671d 532 $USER = NULL;
8e8d0524 533 if ($autologinguest and $CFG->autologinguests and $courseid and get_field('course','guest','id',$courseid)) {
534 $loginguest = '?loginguest=true';
535 } else {
536 $loginguest = '';
a2ebe6a5 537 }
8a33e371 538 if (empty($CFG->loginhttps)) {
b0ccd3fb 539 redirect($CFG->wwwroot .'/login/index.php'. $loginguest);
8a33e371 540 } else {
b0ccd3fb 541 $wwwroot = str_replace('http','https', $CFG->wwwroot);
542 redirect($wwwroot .'/login/index.php'. $loginguest);
8a33e371 543 }
f9903ed0 544 die;
f9903ed0 545 }
808a3baa 546
d35757eb 547 // check whether the user should be changing password
548 reload_user_preferences();
a3f1f815 549 if (!empty($USER->preference['auth_forcepasswordchange'])){
d35757eb 550 if (is_internal_auth() || $CFG->{'auth_'.$USER->auth.'_stdchangepassword'}){
b0ccd3fb 551 redirect($CFG->wwwroot .'/login/change_password.php');
d35757eb 552 } elseif($CFG->changepassword) {
553 redirect($CFG->changepassword);
554 } else {
b0ccd3fb 555 error('You cannot proceed without changing your password.
d35757eb 556 However there is no available page for changing it.
b0ccd3fb 557 Please contact your Moodle Administrator.');
d35757eb 558 }
559 }
560
808a3baa 561 // Check that the user account is properly set up
562 if (user_not_fully_set_up($USER)) {
b0ccd3fb 563 redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
808a3baa 564 die;
565 }
d8ba183c 566
da5c172a 567 // Next, check if the user can be in a particular course
568 if ($courseid) {
9c9f7d77 569 if (!empty($USER->student[$courseid]) or !empty($USER->teacher[$courseid]) or !empty($USER->admin)) {
cb909d74 570 if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
571 if (!isteacher($courseid, $USER->realuser)) {
572 print_header();
b0ccd3fb 573 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
cb909d74 574 }
3ce2f1e0 575 }
da5c172a 576 return; // user is a member of this course.
577 }
b0ccd3fb 578 if (! $course = get_record('course', 'id', $courseid)) {
579 error('That course doesn\'t exist');
da5c172a 580 }
1efa27fd 581 if (!$course->visible) {
582 print_header();
b0ccd3fb 583 notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
1efa27fd 584 }
b0ccd3fb 585 if ($USER->username == 'guest') {
7363ff91 586 switch ($course->guest) {
587 case 0: // Guests not allowed
588 print_header();
b0ccd3fb 589 notice(get_string('guestsnotallowed', '', $course->fullname));
7363ff91 590 break;
591 case 1: // Guests allowed
7363ff91 592 return;
593 case 2: // Guests allowed with key (drop through)
594 break;
595 }
da5c172a 596 }
f9903ed0 597
7363ff91 598 // Currently not enrolled in the course, so see if they want to enrol
da5c172a 599 $SESSION->wantsurl = $FULLME;
b0ccd3fb 600 redirect($CFG->wwwroot .'/course/enrol.php?id='. $courseid);
da5c172a 601 die;
602 }
f9903ed0 603}
604
7cf1c7bd 605/**
606 * This is a weaker version of {@link require_login()} which only requires login
607 * when called from within a course rather than the site page, unless
608 * the forcelogin option is turned on.
609 *
610 * @uses $CFG
611 * @param type description
612 * @todo Finish documenting this function
613 */
f950af3c 614function require_course_login($course, $autologinguest=true) {
f950af3c 615 global $CFG;
616 if ($CFG->forcelogin) {
617 require_login();
618 }
619 if ($course->category) {
620 require_login($course->id, $autologinguest);
621 }
622}
623
7cf1c7bd 624/**
625 * Modify the user table by setting the currently logged in user's
626 * last login to now.
627 *
628 * @uses $USER
629 * @return boolean
630 */
1d881d92 631function update_user_login_times() {
632 global $USER;
633
634 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2a2f5f11 635 $USER->currentlogin = $user->lastaccess = $user->currentlogin = time();
1d881d92 636
637 $user->id = $USER->id;
638
b0ccd3fb 639 return update_record('user', $user);
1d881d92 640}
641
7cf1c7bd 642/**
643 * Determines if a user has completed setting up their account.
644 *
645 * @param object $user A user object to test for the existance of a valid name and email
646 * @return boolean
647 */
808a3baa 648function user_not_fully_set_up($user) {
b0ccd3fb 649 return ($user->username != 'guest' and (empty($user->firstname) or empty($user->lastname) or empty($user->email)));
808a3baa 650}
f9903ed0 651
7cf1c7bd 652/**
653 * Keeps track of login attempts
654 *
655 * @uses $SESSION
656 */
f9903ed0 657function update_login_count() {
9fa49e22 658
f9903ed0 659 global $SESSION;
660
661 $max_logins = 10;
662
663 if (empty($SESSION->logincount)) {
664 $SESSION->logincount = 1;
665 } else {
666 $SESSION->logincount++;
667 }
668
669 if ($SESSION->logincount > $max_logins) {
9fa49e22 670 unset($SESSION->wantsurl);
b0ccd3fb 671 error(get_string('errortoomanylogins'));
d578afc8 672 }
673}
674
7cf1c7bd 675/**
676 * Resets login attempts
677 *
678 * @uses $SESSION
679 */
9fa49e22 680function reset_login_count() {
9fa49e22 681 global $SESSION;
d578afc8 682
9fa49e22 683 $SESSION->logincount = 0;
d578afc8 684}
685
7cf1c7bd 686/**
687 * check_for_restricted_user
688 *
689 * @param type description
690 * @todo Finish documenting this function
691 */
b0ccd3fb 692function check_for_restricted_user($username=NULL, $redirect='') {
cb98d312 693 global $CFG, $USER;
694
695 if (!$username) {
696 if (!empty($USER->username)) {
697 $username = $USER->username;
698 } else {
699 return false;
700 }
701 }
702
703 if (!empty($CFG->restrictusers)) {
704 $names = explode(',', $CFG->restrictusers);
705 if (in_array($username, $names)) {
b0ccd3fb 706 error(get_string('restricteduser', 'error', fullname($USER)), $redirect);
cb98d312 707 }
708 }
709}
710
7cf1c7bd 711/**
712 * Determines if a user an admin
713 *
714 * @uses $USER
715 * @param integer $userid The id of the user as is found in the 'user' table
716 * @return boolean
717 */
581d7b49 718function isadmin($userid=0) {
f9903ed0 719 global $USER;
aa095969 720 static $admins = array();
721 static $nonadmins = array();
f9903ed0 722
581d7b49 723 if (!$userid){
724 if (empty($USER->id)) {
725 return false;
726 }
727 $userid = $USER->id;
9bd2c874 728 }
729
581d7b49 730 if (in_array($userid, $admins)) {
aa095969 731 return true;
581d7b49 732 } else if (in_array($userid, $nonadmins)) {
aa095969 733 return false;
b0ccd3fb 734 } else if (record_exists('user_admins', 'userid', $userid)){
581d7b49 735 $admins[] = $userid;
aa095969 736 return true;
737 } else {
581d7b49 738 $nonadmins[] = $userid;
aa095969 739 return false;
f9903ed0 740 }
f9903ed0 741}
742
7cf1c7bd 743/**
744 * Determines if a user is a teacher or an admin
745 *
746 * @uses $USER
747 * @param integer $courseid The id of the course that is being viewed, if any
748 * @param integer $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
749 * @param boolean $includeadmin If true this function will return true when it encounters an admin user.
750 * @return boolean
751 * @todo Finish documenting this function
752 */
9d3c795c 753function isteacher($courseid=0, $userid=0, $includeadmin=true) {
f9903ed0 754 global $USER;
755
9788367b 756 if ($includeadmin and isadmin($userid)) { // admins can do anything the teacher can
d115a57f 757 return true;
758 }
759
f9903ed0 760 if (!$userid) {
71f9abf9 761 if ($courseid) {
762 return !empty($USER->teacher[$courseid]);
763 }
764 if (!isset($USER->id)) {
765 return false;
766 }
767 $userid = $USER->id;
f9903ed0 768 }
769
9d3c795c 770 if (!$courseid) {
b0ccd3fb 771 return record_exists('user_teachers', 'userid', $userid);
9d3c795c 772 }
773
b0ccd3fb 774 return record_exists('user_teachers', 'userid', $userid, 'course', $courseid);
f9903ed0 775}
776
7cf1c7bd 777/**
778 * Determines if a user is allowed to edit a given course
779 *
780 * @uses $USER
781 * @param integer $courseid The id of the course that is being edited
782 * @param integer $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
783 * @return boolean
784 */
73047f2f 785function isteacheredit($courseid, $userid=0) {
73047f2f 786 global $USER;
787
d8ba183c 788 if (isadmin($userid)) { // admins can do anything
73047f2f 789 return true;
790 }
791
792 if (!$userid) {
793 return !empty($USER->teacheredit[$courseid]);
794 }
795
b0ccd3fb 796 return get_field('user_teachers', 'editall', 'userid', $userid, 'course', $courseid);
73047f2f 797}
798
7cf1c7bd 799/**
800 * Determines if a user can create new courses
801 *
802 * @uses $USER
803 * @param integer $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
804 * @return boolean
805 */
1924074c 806function iscreator ($userid=0) {
1924074c 807 global $USER;
8a205861 808 if (empty($USER->id)) {
809 return false;
810 }
1924074c 811 if (isadmin($userid)) { // admins can do anything
812 return true;
813 }
8a205861 814 if (empty($userid)) {
b0ccd3fb 815 return record_exists('user_coursecreators', 'userid', $USER->id);
1924074c 816 }
817
b0ccd3fb 818 return record_exists('user_coursecreators', 'userid', $userid);
1924074c 819}
820
7cf1c7bd 821/**
822 * Determines if a user is a student in the specified course
823 *
824 * If the course id specifies the site then the function determines
825 * if the user is a confirmed and valid user of this site.
826 *
827 * @uses $USER
828 * @uses $CFG
829 * @param integer $courseid The id of the course being tested
830 * @param integer $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
831 * @return boolean
832 */
8a9e3fd7 833function isstudent($courseid, $userid=0) {
71f9abf9 834 global $USER, $CFG;
f9903ed0 835
2700d113 836 if (empty($USER->id) and !$userid) {
7064e18f 837 return false;
838 }
839
222ac91b 840 if ($courseid == SITEID) {
2cc72e84 841 if (!$userid) {
842 $userid = $USER->id;
843 }
844 if (isguest($userid)) {
845 return false;
846 }
71f9abf9 847 // a site teacher can never be a site student
848 if (isteacher($courseid, $userid)) {
849 return false;
850 }
2700d113 851 if ($CFG->allusersaresitestudents) {
852 return record_exists('user', 'id', $userid);
853 } else {
854 return (record_exists('user_students', 'userid', $userid)
71f9abf9 855 or record_exists('user_teachers', 'userid', $userid));
2700d113 856 }
8f0cd6ef 857 }
2cc72e84 858
f9903ed0 859 if (!$userid) {
346b1a24 860 return !empty($USER->student[$courseid]);
f9903ed0 861 }
862
ebc3bd2b 863 // $timenow = time(); // todo: add time check below
f9903ed0 864
b0ccd3fb 865 return record_exists('user_students', 'userid', $userid, 'course', $courseid);
f9903ed0 866}
867
7cf1c7bd 868/**
869 * Determines if the specified user is logged in as guest.
870 *
871 * @uses $USER
872 * @param integer $userid The user being tested. You can set this to 0 or leave it blank to test the currently logged in user.
873 * @return boolean
874 */
da5c172a 875function isguest($userid=0) {
876 global $USER;
877
878 if (!$userid) {
b35e8568 879 if (empty($USER->username)) {
880 return false;
881 }
b0ccd3fb 882 return ($USER->username == 'guest');
da5c172a 883 }
884
b0ccd3fb 885 return record_exists('user', 'id', $userid, 'username', 'guest');
da5c172a 886}
887
7cf1c7bd 888/**
889 * Determines if the currently logged in user is in editing mode
890 *
891 * @uses $USER
892 * @param integer $courseid The id of the course being tested
893 * @param object $user A user object. If null then the currently logged in user is used.
894 * @return boolean
895 */
2c309dc2 896function isediting($courseid, $user=NULL) {
897 global $USER;
898 if (!$user){
899 $user = $USER;
900 }
9c9f7d77 901 if (empty($user->editing)) {
902 return false;
903 }
2c309dc2 904 return ($user->editing and isteacher($courseid, $user->id));
905}
906
7cf1c7bd 907/**
908 * Determines if the logged in user is currently moving an activity
909 *
910 * @uses $USER
911 * @param integer $courseid The id of the course being tested
912 * @return boolean
913 */
7977cffd 914function ismoving($courseid) {
7977cffd 915 global $USER;
916
917 if (!empty($USER->activitycopy)) {
918 return ($USER->activitycopycourse == $courseid);
919 }
920 return false;
921}
922
7cf1c7bd 923/**
924 * Given an object containing firstname and lastname
925 * values, this function returns a string with the
926 * full name of the person.
927 * The result may depend on system settings
928 * or language. 'override' will force both names
929 * to be used even if system settings specify one.
930 * @uses $CFG
931 * @uses $SESSION
932 * @param type description
933 * @todo Finish documenting this function
934 */
e2cd5065 935function fullname($user, $override=false) {
b5cbb64d 936
f374fb10 937 global $CFG, $SESSION;
938
6527c077 939 if (!isset($user->firstname) and !isset($user->lastname)) {
940 return '';
941 }
942
f374fb10 943 if (!empty($SESSION->fullnamedisplay)) {
944 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
945 }
e2cd5065 946
b5cbb64d 947 if ($CFG->fullnamedisplay == 'firstname lastname') {
b0ccd3fb 948 return $user->firstname .' '. $user->lastname;
b5cbb64d 949
950 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
b0ccd3fb 951 return $user->lastname .' '. $user->firstname;
e2cd5065 952
b5cbb64d 953 } else if ($CFG->fullnamedisplay == 'firstname') {
954 if ($override) {
955 return get_string('fullnamedisplay', '', $user);
956 } else {
957 return $user->firstname;
958 }
959 }
e2cd5065 960
b5cbb64d 961 return get_string('fullnamedisplay', '', $user);
e2cd5065 962}
963
7cf1c7bd 964/**
965 * Sets a moodle cookie with an encrypted string
966 *
967 * @uses $CFG
968 * @param string $thing The string to encrypt and place in a cookie
969 */
f9903ed0 970function set_moodle_cookie($thing) {
7185e073 971 global $CFG;
482b6e6e 972
973 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 974
975 $days = 60;
976 $seconds = 60*60*24*$days;
977
b0ccd3fb 978 setCookie($cookiename, '', time() - 3600, '/');
979 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, '/');
f9903ed0 980}
981
7cf1c7bd 982/**
983 * Gets a moodle cookie with an encrypted string
984 *
985 * @uses $CFG
986 * @return string
987 */
f9903ed0 988function get_moodle_cookie() {
7185e073 989 global $CFG;
990
482b6e6e 991 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 992
1079c8a8 993 if (empty($_COOKIE[$cookiename])) {
b0ccd3fb 994 return '';
1079c8a8 995 } else {
996 return rc4decrypt($_COOKIE[$cookiename]);
997 }
f9903ed0 998}
999
7cf1c7bd 1000/**
1001 * Returns true if an internal authentication method is being used.
1002 * if method not specified then, global default is assumed
1003 *
1004 * @uses $CFG
1005 * @param string $auth Form of authentication required
1006 * @return boolean
1007 * @todo Outline auth types and provide code example
1008 */
39a5a35d 1009function is_internal_auth($auth='') {
ba7166c3 1010/// Returns true if an internal authentication method is being used.
a3f1f815 1011/// If auth not specified then global default is assumed
ba7166c3 1012
1013 global $CFG;
1014
a3f1f815 1015 if (empty($auth)) {
1016 $auth = $CFG->auth;
39a5a35d 1017 }
1018
a3f1f815 1019 return ($auth == "email" || $auth == "none" || $auth == "manual");
1020}
1021
8c3dba73 1022/**
1023 * Returns an array of user fields
1024 *
1025 * @param type description
1026 * @todo Finish documenting this function
1027 */
a3f1f815 1028function get_user_fieldnames() {
a3f1f815 1029
1030 global $CFG, $db;
1031
1032 $fieldarray = $db->MetaColumnNames($CFG->prefix.'user');
1033 unset($fieldarray['ID']);
1034
1035 return $fieldarray;
ba7166c3 1036}
f9903ed0 1037
7cf1c7bd 1038/**
1039 * Creates a bare-bones user record
1040 *
1041 * @uses $CFG
1042 * @uses $REMOTE_ADDR
1043 * @param string $username New user's username to add to record
1044 * @param string $password New user's password to add to record
1045 * @param string $auth Form of authentication required
1046 * @return object
1047 * @todo Outline auth types and provide code example
1048 */
71f9abf9 1049function create_user_record($username, $password, $auth='') {
e858f9da 1050 global $REMOTE_ADDR, $CFG;
71f9abf9 1051
1e22bc9c 1052 //just in case check text case
1053 $username = trim(moodle_strtolower($username));
71f9abf9 1054
3271b70f 1055 if (function_exists('auth_get_userinfo')) {
e858f9da 1056 if ($newinfo = auth_get_userinfo($username)) {
34daec9b 1057 foreach ($newinfo as $key => $value){
9f44d972 1058 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 1059 }
1060 }
1061 }
f9903ed0 1062
85a1d4c9 1063 if (!empty($newuser->email)) {
1064 if (email_is_not_allowed($newuser->email)) {
1065 unset($newuser->email);
1066 }
1067 }
1068
71f9abf9 1069 $newuser->auth = (empty($auth)) ? $CFG->auth : $auth;
faebaf0f 1070 $newuser->username = $username;
1071 $newuser->password = md5($password);
a0bac19d 1072 $newuser->lang = $CFG->lang;
faebaf0f 1073 $newuser->confirmed = 1;
59619427 1074 $newuser->lastIP = getremoteaddr();
faebaf0f 1075 $newuser->timemodified = time();
f9903ed0 1076
b0ccd3fb 1077 if (insert_record('user', $newuser)) {
1078 $user = get_user_info_from_db('username', $newuser->username);
d35757eb 1079 if($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'}){
1080 set_user_preference('auth_forcepasswordchange', 1, $user);
1081 }
1082 return $user;
faebaf0f 1083 }
1084 return false;
1085}
1086
7cf1c7bd 1087/**
1088 * Will update a local user record from an external source
1089 *
1090 * @uses $CFG
1091 * @param string $username New user's username to add to record
1092 * @return object
1093 */
d35757eb 1094function update_user_record($username) {
d35757eb 1095 global $CFG;
1096
1097 if (function_exists('auth_get_userinfo')) {
1098 $username = trim(moodle_strtolower($username)); /// just in case check text case
1099
1100 if ($newinfo = auth_get_userinfo($username)) {
1101 foreach ($newinfo as $key => $value){
1102 if (!empty($CFG->{'auth_user_' . $key. '_updatelocal'})) {
1103 $value = addslashes(stripslashes($value)); // Just in case
1104 set_field('user', $key, $value, 'username', $username);
1105 }
1106 }
1107 }
1108 }
b0ccd3fb 1109 return get_user_info_from_db('username', $username);
d35757eb 1110}
0609562b 1111
7cf1c7bd 1112/**
1113 * Retrieve the guest user object
1114 *
1115 * @uses $CFG
1116 * @return object
1117 */
0609562b 1118function guest_user() {
1119 global $CFG;
1120
b0ccd3fb 1121 if ($newuser = get_record('user', 'username', 'guest')) {
0609562b 1122 $newuser->loggedin = true;
1123 $newuser->confirmed = 1;
1124 $newuser->site = $CFG->wwwroot;
1125 $newuser->lang = $CFG->lang;
1126 }
1127
1128 return $newuser;
1129}
1130
7cf1c7bd 1131/**
1132 * Given a username and password, this function looks them
1133 * up using the currently selected authentication mechanism,
1134 * and if the authentication is successful, it returns a
1135 * valid $user object from the 'user' table.
1136 *
1137 * Uses auth_ functions from the currently active auth module
1138 *
1139 * @uses $CFG
1140 * @param string $username user's username
1141 * @param string $password user's password
1142 * @return object
1143 */
faebaf0f 1144function authenticate_user_login($username, $password) {
faebaf0f 1145
1146 global $CFG;
1147
466558e3 1148 $md5password = md5($password);
1149
27286aeb 1150 // First try to find the user in the database
466558e3 1151
b0ccd3fb 1152 $user = get_user_info_from_db('username', $username);
39a5a35d 1153
27286aeb 1154 // Sort out the authentication method we are using.
39a5a35d 1155
27286aeb 1156 if (empty($CFG->auth)) {
b0ccd3fb 1157 $CFG->auth = 'manual'; // Default authentication module
27286aeb 1158 }
39a5a35d 1159
27286aeb 1160 if (empty($user->auth)) { // For some reason it isn't set yet
1161 if (isadmin($user->id) or isguest($user->id)) {
71f9abf9 1162 $auth = 'manual'; // Always assume these guys are internal
27286aeb 1163 } else {
71f9abf9 1164 $auth = $CFG->auth; // Normal users default to site method
27286aeb 1165 }
d35757eb 1166 // update user record from external DB
1167 if ($user->auth != 'manual' && $user->auth != 'email') {
1168 $user = update_user_record($username);
1169 }
71f9abf9 1170 } else {
1171 $auth = $user->auth;
27286aeb 1172 }
8f0cd6ef 1173
b0ccd3fb 1174 if (!file_exists($CFG->dirroot .'/auth/'. $auth .'/lib.php')) {
1175 $auth = 'manual'; // Can't find auth module, default to internal
466558e3 1176 }
1177
b0ccd3fb 1178 require_once($CFG->dirroot .'/auth/'. $auth .'/lib.php');
faebaf0f 1179
1180 if (auth_user_login($username, $password)) { // Successful authentication
71f9abf9 1181 if ($user) { // User already exists in database
1182 if (empty($user->auth)) { // For some reason auth isn't set yet
1183 set_field('user', 'auth', $auth, 'username', $username);
1184 }
92710226 1185 if ($md5password <> $user->password) { // Update local copy of password for reference
71f9abf9 1186 set_field('user', 'password', $md5password, 'username', $username);
faebaf0f 1187 }
d35757eb 1188 // update user record from external DB
1189 if ($user->auth != 'manual' && $user->auth != 'email'){
1190 $user = update_user_record($username);
1191 }
faebaf0f 1192 } else {
71f9abf9 1193 $user = create_user_record($username, $password, $auth);
faebaf0f 1194 }
89b54325 1195
e582b65e 1196 if (function_exists('auth_iscreator')) { // Check if the user is a creator
1197 if (auth_iscreator($username)) {
b0ccd3fb 1198 if (! record_exists('user_coursecreators', 'userid', $user->id)) {
39a5a35d 1199 $cdata->userid = $user->id;
b0ccd3fb 1200 if (! insert_record('user_coursecreators', $cdata)) {
1201 error('Cannot add user to course creators.');
39a5a35d 1202 }
1203 }
e582b65e 1204 } else {
b0ccd3fb 1205 if ( record_exists('user_coursecreators', 'userid', $user->id)) {
1206 if (! delete_records('user_coursecreators', 'userid', $user->id)) {
1207 error('Cannot remove user from course creators.');
39a5a35d 1208 }
1209 }
e582b65e 1210 }
39a5a35d 1211 }
e582b65e 1212 return $user;
9d3c795c 1213
e582b65e 1214 } else {
b0ccd3fb 1215 add_to_log(0, 'login', 'error', $_SERVER['HTTP_REFERER'], $username);
9d3c795c 1216 $date = date('Y-m-d H:i:s');
b0ccd3fb 1217 error_log($date ."\tfailed login\t". getremoteaddr() ."\t". $_SERVER['HTTP_USER_AGENT'] ."\t". $username);
e582b65e 1218 return false;
1219 }
f9903ed0 1220}
1221
7cf1c7bd 1222/**
1223 * Enrols (or re-enrols) a student in a given course
1224 *
1225 * @param integer $courseid The id of the course that is being viewed
1226 * @param integer $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
1227 * @param integer $timestart ?
1228 * @param integer $timeend ?
1229 * @return boolean
1230 * @todo Finish documenting this function
1231 */
b40bc478 1232function enrol_student($userid, $courseid, $timestart=0, $timeend=0) {
b40bc478 1233
b0ccd3fb 1234 if (!$course = get_record('course', 'id', $courseid)) { // Check course
3041b0f8 1235 return false;
4d312bbe 1236 }
b0ccd3fb 1237 if (!$user = get_record('user', 'id', $userid)) { // Check user
631cf796 1238 return false;
1239 }
b0ccd3fb 1240 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
631cf796 1241 $student->timestart = $timestart;
1242 $student->timeend = $timeend;
1243 $student->time = time();
b0ccd3fb 1244 return update_record('user_students', $student);
8f0cd6ef 1245
631cf796 1246 } else {
1247 $student->userid = $userid;
1248 $student->course = $courseid;
1249 $student->timestart = $timestart;
1250 $student->timeend = $timeend;
1251 $student->time = time();
b0ccd3fb 1252 return insert_record('user_students', $student);
631cf796 1253 }
d7facad8 1254}
1255
7cf1c7bd 1256/**
1257 * Unenrols a student from a given course
1258 *
1259 * @param integer $courseid The id of the course that is being viewed, if any
1260 * @param integer $userid The id of the user that is being tested against.
1261 * @return boolean
1262 */
9fa62805 1263function unenrol_student($userid, $courseid=0) {
d7facad8 1264
9fa62805 1265 if ($courseid) {
9fa49e22 1266 /// First delete any crucial stuff that might still send mail
b0ccd3fb 1267 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 1268 foreach ($forums as $forum) {
b0ccd3fb 1269 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa62805 1270 }
1271 }
1272 if ($groups = get_groups($courseid, $userid)) {
1273 foreach ($groups as $group) {
b0ccd3fb 1274 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
bb09fb11 1275 }
f9903ed0 1276 }
b0ccd3fb 1277 return delete_records('user_students', 'userid', $userid, 'course', $courseid);
9fa49e22 1278
f9903ed0 1279 } else {
b0ccd3fb 1280 delete_records('forum_subscriptions', 'userid', $userid);
1281 delete_records('groups_members', 'userid', $userid);
1282 return delete_records('user_students', 'userid', $userid);
f9903ed0 1283 }
1284}
1285
7cf1c7bd 1286/**
1287 * Add a teacher to a given course
1288 *
1289 * @uses $USER
1290 * @param integer $courseid The id of the course that is being viewed, if any
1291 * @param integer $userid The id of the user that is being tested against. Set this to 0 if you would just like to test against the currently logged in user.
1292 * @param integer $editall ?
1293 * @param string $role ?
1294 * @param integer $timestart ?
1295 * @param integer $timeend ?
1296 * @return boolean
1297 * @todo Finish documenting this function
1298 */
b0ccd3fb 1299function add_teacher($userid, $courseid, $editall=1, $role='', $timestart=0, $timeend=0) {
7b5944cd 1300 global $CFG;
3041b0f8 1301
61451a36 1302 if ($teacher = get_record('user_teachers', 'userid', $userid, 'course', $courseid)) {
b40bc478 1303 $newteacher = NULL;
1304 $newteacher->id = $teacher->id;
1305 $newteacher->editall = $editall;
1306 if ($role) {
1307 $newteacher->role = $role;
1308 }
1309 if ($timestart) {
1310 $newteacher->timestart = $timestart;
3041b0f8 1311 }
b40bc478 1312 if ($timeend) {
1313 $newteacher->timeend = $timeend;
1314 }
1315 return update_record('user_teachers', $newteacher);
3041b0f8 1316 }
61451a36 1317
b0ccd3fb 1318 if (!record_exists('user', 'id', $userid)) {
61451a36 1319 return false; // no such user
1320 }
1321
b0ccd3fb 1322 if (!record_exists('course', 'id', $courseid)) {
61451a36 1323 return false; // no such course
1324 }
1325
1326 $teacher = NULL;
1327 $teacher->userid = $userid;
1328 $teacher->course = $courseid;
1329 $teacher->editall = $editall;
1330 $teacher->role = $role;
5a2dea02 1331 $teacher->timemodified = time();
1332 $newteacher->timestart = $timestart;
1333 $newteacher->timeend = $timeend;
b0ccd3fb 1334 if ($student = get_record('user_students', 'userid', $userid, 'course', $courseid)) {
5a2dea02 1335 $teacher->timestart = $student->timestart;
1336 $teacher->timeend = $student->timeend;
1337 $teacher->timeaccess = $student->timeaccess;
1338 }
61451a36 1339
b0ccd3fb 1340 if (record_exists('user_teachers', 'course', $courseid)) {
61451a36 1341 $teacher->authority = 2;
1342 } else {
1343 $teacher->authority = 1;
1344 }
b0ccd3fb 1345 delete_records('user_students', 'userid', $userid, 'course', $courseid); // Unenrol as student
8f0cd6ef 1346
709f0ec8 1347 /// Add forum subscriptions for new users
7b5944cd 1348 require_once('../mod/forum/lib.php');
1349 forum_add_user($userid, $courseid);
61451a36 1350
b0ccd3fb 1351 return insert_record('user_teachers', $teacher);
61451a36 1352
3041b0f8 1353}
1354
7cf1c7bd 1355/**
1356 * Removes a teacher from a given course (or ALL courses)
1357 * Does not delete the user account
1358 *
1359 * @param integer $courseid The id of the course that is being viewed, if any
1360 * @param integer $userid The id of the user that is being tested against.
1361 * @return boolean
1362 */
3041b0f8 1363function remove_teacher($userid, $courseid=0) {
3041b0f8 1364 if ($courseid) {
9fa49e22 1365 /// First delete any crucial stuff that might still send mail
b0ccd3fb 1366 if ($forums = get_records('forum', 'course', $courseid)) {
9fa49e22 1367 foreach ($forums as $forum) {
b0ccd3fb 1368 delete_records('forum_subscriptions', 'forum', $forum->id, 'userid', $userid);
9fa49e22 1369 }
1370 }
b02193e6 1371
1372 /// Next if the teacher is not registered as a student, but is
1373 /// a member of a group, remove them from the group.
1374 if (!isstudent($courseid, $userid)) {
1375 if ($groups = get_groups($courseid, $userid)) {
1376 foreach ($groups as $group) {
b0ccd3fb 1377 delete_records('groups_members', 'groupid', $group->id, 'userid', $userid);
b02193e6 1378 }
1379 }
1380 }
1381
b0ccd3fb 1382 return delete_records('user_teachers', 'userid', $userid, 'course', $courseid);
57507290 1383 } else {
b0ccd3fb 1384 delete_records('forum_subscriptions', 'userid', $userid);
1385 return delete_records('user_teachers', 'userid', $userid);
57507290 1386 }
f9903ed0 1387}
1388
7cf1c7bd 1389/**
1390 * Add a creator to the site
1391 *
1392 * @param integer $userid The id of the user that is being tested against.
1393 * @return boolean
1394 */
3041b0f8 1395function add_creator($userid) {
3041b0f8 1396
b0ccd3fb 1397 if (!record_exists('user_admins', 'userid', $userid)) {
1398 if (record_exists('user', 'id', $userid)) {
3041b0f8 1399 $creator->userid = $userid;
b0ccd3fb 1400 return insert_record('user_coursecreators', $creator);
3041b0f8 1401 }
1402 return false;
1403 }
1404 return true;
1405}
1406
7cf1c7bd 1407/**
1408 * Remove a creator from a site
1409 *
1410 * @uses $db
1411 * @param integer $userid The id of the user that is being tested against.
1412 * @return boolean
1413 */
3041b0f8 1414function remove_creator($userid) {
3041b0f8 1415 global $db;
1416
b0ccd3fb 1417 return delete_records('user_coursecreators', 'userid', $userid);
3041b0f8 1418}
1419
7cf1c7bd 1420/**
1421 * Add an admin to a site
1422 *
1423 * @uses SITEID
1424 * @param integer $userid The id of the user that is being tested against.
1425 * @return boolean
1426 */
3041b0f8 1427function add_admin($userid) {
3041b0f8 1428
b0ccd3fb 1429 if (!record_exists('user_admins', 'userid', $userid)) {
1430 if (record_exists('user', 'id', $userid)) {
3041b0f8 1431 $admin->userid = $userid;
8f0cd6ef 1432
f950af3c 1433 // any admin is also a teacher on the site course
222ac91b 1434 if (!record_exists('user_teachers', 'course', SITEID, 'userid', $userid)) {
1435 if (!add_teacher($userid, SITEID)) {
f950af3c 1436 return false;
1437 }
1438 }
8f0cd6ef 1439
b0ccd3fb 1440 return insert_record('user_admins', $admin);
3041b0f8 1441 }
1442 return false;
1443 }
1444 return true;
1445}
1446
7cf1c7bd 1447/**
1448 * Removes an admin from a site
1449 *
1450 * @uses $db
1451 * @uses SITEID
1452 * @param integer $userid The id of the user that is being tested against.
1453 * @return boolean
1454 */
3041b0f8 1455function remove_admin($userid) {
9fa49e22 1456 global $db;
f9903ed0 1457
f950af3c 1458 // remove also from the list of site teachers
222ac91b 1459 remove_teacher($userid, SITEID);
f950af3c 1460
b0ccd3fb 1461 return delete_records('user_admins', 'userid', $userid);
f9903ed0 1462}
1463
7cf1c7bd 1464/**
1465 * Clear a course out completely, deleting all content
1466 * but don't delete the course itself
1467 *
1468 * @uses $USER
1469 * @uses $SESSION
1470 * @uses $CFG
1471 * @param integer $courseid The id of the course that is being viewed
1472 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
1473 * @return boolean
1474 */
07aeb7b0 1475function remove_course_contents($courseid, $showfeedback=true) {
07aeb7b0 1476
ee23f384 1477 global $CFG, $THEME, $USER, $SESSION;
07aeb7b0 1478
1479 $result = true;
1480
b0ccd3fb 1481 if (! $course = get_record('course', 'id', $courseid)) {
1482 error('Course ID was incorrect (can\'t find it)');
07aeb7b0 1483 }
1484
b0ccd3fb 1485 $strdeleted = get_string('deleted');
07aeb7b0 1486
1487 // First delete every instance of every module
d8ba183c 1488
b0ccd3fb 1489 if ($allmods = get_records('modules') ) {
07aeb7b0 1490 foreach ($allmods as $mod) {
1491 $modname = $mod->name;
b0ccd3fb 1492 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
1493 $moddelete = $modname .'_delete_instance'; // Delete everything connected to an instance
1494 $moddeletecourse = $modname .'_delete_course'; // Delete other stray stuff (uncommon)
07aeb7b0 1495 $count=0;
1496 if (file_exists($modfile)) {
1497 include_once($modfile);
1498 if (function_exists($moddelete)) {
b0ccd3fb 1499 if ($instances = get_records($modname, 'course', $course->id)) {
07aeb7b0 1500 foreach ($instances as $instance) {
1501 if ($moddelete($instance->id)) {
1502 $count++;
1503 } else {
b0ccd3fb 1504 notify('Could not delete '. $modname .' instance '. $instance->id .' ('. $instance->name .')');
07aeb7b0 1505 $result = false;
1506 }
1507 }
1508 }
1509 } else {
b0ccd3fb 1510 notify('Function '. $moddelete() .'doesn\'t exist!');
07aeb7b0 1511 $result = false;
1512 }
1513
ca952b03 1514 if (function_exists($moddeletecourse)) {
1515 $moddeletecourse($course);
1516 }
07aeb7b0 1517 }
1518 if ($showfeedback) {
b0ccd3fb 1519 notify($strdeleted .' '. $count .' x '. $modname);
07aeb7b0 1520 }
1521 }
1522 } else {
b0ccd3fb 1523 error('No modules are installed!');
07aeb7b0 1524 }
1525
1526 // Delete any user stuff
1527
b0ccd3fb 1528 if (delete_records('user_students', 'course', $course->id)) {
07aeb7b0 1529 if ($showfeedback) {
b0ccd3fb 1530 notify($strdeleted .' user_students');
07aeb7b0 1531 }
1532 } else {
1533 $result = false;
1534 }
1535
b0ccd3fb 1536 if (delete_records('user_teachers', 'course', $course->id)) {
07aeb7b0 1537 if ($showfeedback) {
b0ccd3fb 1538 notify($strdeleted .' user_teachers');
07aeb7b0 1539 }
1540 } else {
1541 $result = false;
1542 }
1543
082e3ebc 1544 // Delete any groups
1545
b0ccd3fb 1546 if ($groups = get_records('groups', 'courseid', $course->id)) {
082e3ebc 1547 foreach ($groups as $group) {
b0ccd3fb 1548 if (delete_records('groups_members', 'groupid', $group->id)) {
082e3ebc 1549 if ($showfeedback) {
b0ccd3fb 1550 notify($strdeleted .' groups_members');
082e3ebc 1551 }
1552 } else {
1553 $result = false;
1554 }
b0ccd3fb 1555 if (delete_records('groups', 'id', $group->id)) {
082e3ebc 1556 if ($showfeedback) {
b0ccd3fb 1557 notify($strdeleted .' groups');
082e3ebc 1558 }
1559 } else {
1560 $result = false;
1561 }
1562 }
1563 }
1564
1565 // Delete events
1566
b0ccd3fb 1567 if (delete_records('event', 'courseid', $course->id)) {
082e3ebc 1568 if ($showfeedback) {
b0ccd3fb 1569 notify($strdeleted .' event');
082e3ebc 1570 }
1571 } else {
1572 $result = false;
1573 }
1574
07aeb7b0 1575 // Delete logs
1576
b0ccd3fb 1577 if (delete_records('log', 'course', $course->id)) {
07aeb7b0 1578 if ($showfeedback) {
b0ccd3fb 1579 notify($strdeleted .' log');
07aeb7b0 1580 }
1581 } else {
1582 $result = false;
1583 }
1584
1585 // Delete any course stuff
1586
b0ccd3fb 1587 if (delete_records('course_sections', 'course', $course->id)) {
07aeb7b0 1588 if ($showfeedback) {
b0ccd3fb 1589 notify($strdeleted .' course_sections');
07aeb7b0 1590 }
1591 } else {
1592 $result = false;
1593 }
1594
b0ccd3fb 1595 if (delete_records('course_modules', 'course', $course->id)) {
07aeb7b0 1596 if ($showfeedback) {
b0ccd3fb 1597 notify($strdeleted .' course_modules');
07aeb7b0 1598 }
1599 } else {
1600 $result = false;
1601 }
1602
1603 return $result;
1604
1605}
1606
7cf1c7bd 1607/**
1608 * This function will empty a course of USER data as much as
1609/// possible. It will retain the activities and the structure
1610/// of the course.
1611 *
1612 * @uses $USER
1613 * @uses $THEME
1614 * @uses $SESSION
1615 * @uses $CFG
1616 * @param integer $courseid The id of the course that is being viewed
1617 * @param boolean $showfeedback Set this to false to suppress notifications from being printed as the functions performs its steps.
1618 * @param boolean $removestudents ?
1619 * @param boolean $removeteachers ?
1620 * @param boolean $removegroups ?
1621 * @param boolean $removeevents ?
1622 * @param boolean $removelogs ?
1623 * @return boolean
1624 * @todo Finish documenting this function
1625 */
3831de52 1626function remove_course_userdata($courseid, $showfeedback=true,
1627 $removestudents=true, $removeteachers=false, $removegroups=true,
1628 $removeevents=true, $removelogs=false) {
3831de52 1629
1630 global $CFG, $THEME, $USER, $SESSION;
1631
1632 $result = true;
1633
b0ccd3fb 1634 if (! $course = get_record('course', 'id', $courseid)) {
1635 error('Course ID was incorrect (can\'t find it)');
3831de52 1636 }
1637
b0ccd3fb 1638 $strdeleted = get_string('deleted');
3831de52 1639
1640 // Look in every instance of every module for data to delete
1641
b0ccd3fb 1642 if ($allmods = get_records('modules') ) {
3831de52 1643 foreach ($allmods as $mod) {
1644 $modname = $mod->name;
b0ccd3fb 1645 $modfile = $CFG->dirroot .'/mod/'. $modname .'/lib.php';
1646 $moddeleteuserdata = $modname .'_delete_userdata'; // Function to delete user data
3831de52 1647 $count=0;
1648 if (file_exists($modfile)) {
1649 @include_once($modfile);
1650 if (function_exists($moddeleteuserdata)) {
1651 $moddeleteuserdata($course, $showfeedback);
1652 }
1653 }
1654 }
1655 } else {
b0ccd3fb 1656 error('No modules are installed!');
3831de52 1657 }
1658
1659 // Delete other stuff
1660
1661 if ($removestudents) {
1662 /// Delete student enrolments
b0ccd3fb 1663 if (delete_records('user_students', 'course', $course->id)) {
3831de52 1664 if ($showfeedback) {
b0ccd3fb 1665 notify($strdeleted .' user_students');
3831de52 1666 }
1667 } else {
1668 $result = false;
1669 }
1670 /// Delete group members (but keep the groups)
b0ccd3fb 1671 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 1672 foreach ($groups as $group) {
b0ccd3fb 1673 if (delete_records('groups_members', 'groupid', $group->id)) {
3831de52 1674 if ($showfeedback) {
b0ccd3fb 1675 notify($strdeleted .' groups_members');
3831de52 1676 }
1677 } else {
1678 $result = false;
1679 }
1680 }
1681 }
1682 }
1683
1684 if ($removeteachers) {
b0ccd3fb 1685 if (delete_records('user_teachers', 'course', $course->id)) {
3831de52 1686 if ($showfeedback) {
b0ccd3fb 1687 notify($strdeleted .' user_teachers');
3831de52 1688 }
1689 } else {
1690 $result = false;
1691 }
1692 }
1693
1694 if ($removegroups) {
b0ccd3fb 1695 if ($groups = get_records('groups', 'courseid', $course->id)) {
3831de52 1696 foreach ($groups as $group) {
b0ccd3fb 1697 if (delete_records('groups', 'id', $group->id)) {
3831de52 1698 if ($showfeedback) {
b0ccd3fb 1699 notify($strdeleted .' groups');
3831de52 1700 }
1701 } else {
1702 $result = false;
1703 }
1704 }
1705 }
1706 }
1707
1708 if ($removeevents) {
b0ccd3fb 1709 if (delete_records('event', 'courseid', $course->id)) {
3831de52 1710 if ($showfeedback) {
b0ccd3fb 1711 notify($strdeleted .' event');
3831de52 1712 }
1713 } else {
1714 $result = false;
1715 }
1716 }
1717
1718 if ($removelogs) {
b0ccd3fb 1719 if (delete_records('log', 'course', $course->id)) {
3831de52 1720 if ($showfeedback) {
b0ccd3fb 1721 notify($strdeleted .' log');
3831de52 1722 }
1723 } else {
1724 $result = false;
1725 }
1726 }
1727
1728 return $result;
1729
1730}
1731
1732
f9903ed0 1733
f374fb10 1734/// GROUPS /////////////////////////////////////////////////////////
d8ba183c 1735
f374fb10 1736
1737/**
1738* Returns a boolean: is the user a member of the given group?
d8ba183c 1739*
dcd338ff 1740* @param type description
7cf1c7bd 1741 * @todo Finish documenting this function
f374fb10 1742*/
1743function ismember($groupid, $userid=0) {
1744 global $USER;
1745
8a2c9076 1746 if (!$groupid) { // No point doing further checks
1747 return false;
1748 }
1749
f374fb10 1750 if (!$userid) {
0d67c514 1751 if (empty($USER->groupmember)) {
1752 return false;
1753 }
1754 foreach ($USER->groupmember as $courseid => $mgroupid) {
1755 if ($mgroupid == $groupid) {
1756 return true;
1757 }
1758 }
1759 return false;
f374fb10 1760 }
1761
b0ccd3fb 1762 return record_exists('groups_members', 'groupid', $groupid, 'userid', $userid);
f374fb10 1763}
1764
0d67c514 1765/**
1766* Returns the group ID of the current user in the given course
d8ba183c 1767*
dcd338ff 1768* @param type description
7cf1c7bd 1769 * @todo Finish documenting this function
0d67c514 1770*/
1771function mygroupid($courseid) {
1772 global $USER;
1773
1774 if (empty($USER->groupmember[$courseid])) {
1775 return 0;
1776 } else {
1777 return $USER->groupmember[$courseid];
1778 }
1779}
1780
f374fb10 1781/**
d8ba183c 1782* For a given course, and possibly course module, determine
f374fb10 1783* what the current default groupmode is:
1784* NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
d8ba183c 1785*
dcd338ff 1786* @param type description
7cf1c7bd 1787 * @todo Finish documenting this function
f374fb10 1788*/
1789function groupmode($course, $cm=null) {
1790
1791 if ($cm and !$course->groupmodeforce) {
1792 return $cm->groupmode;
1793 }
1794 return $course->groupmode;
1795}
1796
1797
1798/**
1799* Sets the current group in the session variable
d8ba183c 1800*
dcd338ff 1801* @param type description
7cf1c7bd 1802 * @todo Finish documenting this function
f374fb10 1803*/
1804function set_current_group($courseid, $groupid) {
1805 global $SESSION;
1806
1807 return $SESSION->currentgroup[$courseid] = $groupid;
1808}
1809
1810
1811/**
1812* Gets the current group for the current user as an id or an object
d8ba183c 1813*
dcd338ff 1814* @param type description
7cf1c7bd 1815 * @todo Finish documenting this function
f374fb10 1816*/
1817function get_current_group($courseid, $full=false) {
1818 global $SESSION, $USER;
1819
ce04df6b 1820 if (!isset($SESSION->currentgroup[$courseid])) {
f374fb10 1821 if (empty($USER->groupmember[$courseid])) {
8a2c9076 1822 return 0;
f374fb10 1823 } else {
1824 $SESSION->currentgroup[$courseid] = $USER->groupmember[$courseid];
1825 }
1826 }
1827
1828 if ($full) {
0da33e07 1829 return get_record('groups', 'id', $SESSION->currentgroup[$courseid]);
f374fb10 1830 } else {
1831 return $SESSION->currentgroup[$courseid];
1832 }
1833}
1834
0d67c514 1835/**
1836* A combination function to make it easier for modules
1837* to set up groups.
1838*
1839* It will use a given "groupid" parameter and try to use
1840* that to reset the current group for the user.
1841*
dcd338ff 1842* @param type description
7cf1c7bd 1843 * @todo Finish documenting this function
0d67c514 1844*/
eb6147a8 1845function get_and_set_current_group($course, $groupmode, $groupid=-1) {
0d67c514 1846
1847 if (!$groupmode) { // Groups don't even apply
d8ba183c 1848 return false;
0d67c514 1849 }
1850
1851 $currentgroupid = get_current_group($course->id);
1852
eb6147a8 1853 if ($groupid < 0) { // No change was specified
1854 return $currentgroupid;
1855 }
1856
1857 if ($groupid) { // Try to change the current group to this groupid
0d67c514 1858 if ($group = get_record('groups', 'id', $groupid, 'courseid', $course->id)) { // Exists
1859 if (isteacheredit($course->id)) { // Sets current default group
1860 $currentgroupid = set_current_group($course->id, $group->id);
1861
1862 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
1863 $currentgroupid = $group->id;
1864 }
1865 }
eb6147a8 1866 } else { // When groupid = 0 it means show ALL groups
1867 if (isteacheredit($course->id)) { // Sets current default group
1868 $currentgroupid = set_current_group($course->id, 0);
1869
1870 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
1871 $currentgroupid = 0;
1872 }
0d67c514 1873 }
1874
1875 return $currentgroupid;
1876}
1877
1878
c3cbfe7f 1879/**
1880* A big combination function to make it easier for modules
1881* to set up groups.
1882*
1883* Terminates if the current user shouldn't be looking at this group
1884* Otherwise returns the current group if there is one
1885* Otherwise returns false if groups aren't relevant
1886*
dcd338ff 1887* @param type description
7cf1c7bd 1888 * @todo Finish documenting this function
c3cbfe7f 1889*/
1890function setup_and_print_groups($course, $groupmode, $urlroot) {
1891
eb6147a8 1892 if (isset($_GET['group'])) {
1893 $changegroup = $_GET['group']; /// 0 or higher
1894 } else {
1895 $changegroup = -1; /// This means no group change was specified
1896 }
1897
1898 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
c3cbfe7f 1899
eb6147a8 1900 if ($currentgroup === false) {
c3cbfe7f 1901 return false;
1902 }
1903
4b6d8dd5 1904 if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id) and !$currentgroup) {
1905 print_heading(get_string('notingroup'));
c3cbfe7f 1906 print_footer($course);
1907 exit;
1908 }
1909
1910 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
b0ccd3fb 1911 if ($groups = get_records_menu('groups', 'courseid', $course->id, 'name ASC', 'id,name')) {
eb6147a8 1912 echo '<div align="center">';
c3cbfe7f 1913 print_group_menu($groups, $groupmode, $currentgroup, $urlroot);
eb6147a8 1914 echo '</div>';
c3cbfe7f 1915 }
1916 }
1917
1918 return $currentgroup;
1919}
0d67c514 1920
f374fb10 1921
1922
f9903ed0 1923/// CORRESPONDENCE ////////////////////////////////////////////////
1924
7cf1c7bd 1925/**
1926 * Send an email to a specified user
1927 *
1928 * Returns "true" if mail was sent OK, "emailstop" if email was blocked by user
1929 * and "false" if there was another sort of error.
1930 *
1931 * @uses $CFG
1932 * @uses $_SERVER
1933 * @param object $user a user record as an object
1934 * @param object $from a user record as an object
1935 * @param string $subject plain text subject line of the email
1936 * @param string $messagetext plain text version of the message
1937 * @param string $messagehtml complete html version of the message (optional)
1938 * @param string $attachment a file on the filesystem, relative to $CFG->dataroot
1939 * @param string $attachname the name of the file (extension indicates MIME)
1940 * @param boolean $usetrueaddress determines whether $from email address should be sent out. Will be overruled by user profile setting for maildisplay
1941 * @return boolean
1942 */
b0ccd3fb 1943function email_to_user($user, $from, $subject, $messagetext, $messagehtml='', $attachment='', $attachname='', $usetrueaddress=true) {
f9903ed0 1944
4216daa6 1945 global $CFG, $_SERVER;
f9903ed0 1946
0cc6fa6a 1947 global $course; // This is a bit of an ugly hack to be gotten rid of later
1948 if (!empty($course->lang)) { // Course language is defined
1949 $CFG->courselang = $course->lang;
1950 }
1951
b0ccd3fb 1952 include_once($CFG->libdir .'/phpmailer/class.phpmailer.php');
f9903ed0 1953
cadb96f2 1954 if (empty($user)) {
1955 return false;
1956 }
1957
1958 if (!empty($user->emailstop)) {
579dcca4 1959 return 'emailstop';
f9903ed0 1960 }
d8ba183c 1961
f9903ed0 1962 $mail = new phpmailer;
1963
b0ccd3fb 1964 $mail->Version = 'Moodle '. $CFG->version; // mailer version
1965 $mail->PluginDir = $CFG->libdir .'/phpmailer/'; // plugin directory (eg smtp plugin)
562bbe90 1966
98c4eae3 1967
b0ccd3fb 1968 if (current_language() != 'en') {
1969 $mail->CharSet = get_string('thischarset');
98c4eae3 1970 }
1971
b0ccd3fb 1972 if ($CFG->smtphosts == 'qmail') {
62740736 1973 $mail->IsQmail(); // use Qmail system
1974
1975 } else if (empty($CFG->smtphosts)) {
1976 $mail->IsMail(); // use PHP mail() = sendmail
1977
1978 } else {
1e411ffc 1979 $mail->IsSMTP(); // use SMTP directly
57ef3480 1980 if ($CFG->debug > 7) {
b0ccd3fb 1981 echo '<pre>' . "\n";
57ef3480 1982 $mail->SMTPDebug = true;
1983 }
b0ccd3fb 1984 $mail->Host = $CFG->smtphosts; // specify main and backup servers
9f58537a 1985
1986 if ($CFG->smtpuser) { // Use SMTP authentication
1987 $mail->SMTPAuth = true;
1988 $mail->Username = $CFG->smtpuser;
1989 $mail->Password = $CFG->smtppass;
1990 }
7f86ce17 1991 }
f9903ed0 1992
2b97bd71 1993 $adminuser = get_admin();
1994
b0ccd3fb 1995 $mail->Sender = $adminuser->email;
2b97bd71 1996
a402bdcb 1997 if (is_string($from)) { // So we can pass whatever we want if there is need
1998 $mail->From = $CFG->noreplyaddress;
0d8a590a 1999 $mail->FromName = $from;
a402bdcb 2000 } else if ($usetrueaddress and $from->maildisplay) {
b0ccd3fb 2001 $mail->From = $from->email;
6e506bf9 2002 $mail->FromName = fullname($from);
2003 } else {
b0ccd3fb 2004 $mail->From = $CFG->noreplyaddress;
0d8a590a 2005 $mail->FromName = fullname($from);
6e506bf9 2006 }
136dabd8 2007 $mail->Subject = stripslashes($subject);
f9903ed0 2008
b0ccd3fb 2009 $mail->AddAddress($user->email, fullname($user) );
f9903ed0 2010
58d24720 2011 $mail->WordWrap = 79; // set word wrap
f9903ed0 2012
857b798b 2013 if (!empty($from->customheaders)) { // Add custom headers
2014 if (is_array($from->customheaders)) {
2015 foreach ($from->customheaders as $customheader) {
2016 $mail->AddCustomHeader($customheader);
2017 }
2018 } else {
2019 $mail->AddCustomHeader($from->customheaders);
2020 }
b68dca19 2021 }
8f0cd6ef 2022
136dabd8 2023 if ($messagehtml) {
2024 $mail->IsHTML(true);
b0ccd3fb 2025 $mail->Encoding = 'quoted-printable'; // Encoding to use
136dabd8 2026 $mail->Body = $messagehtml;
78681899 2027 $mail->AltBody = "\n$messagetext\n";
136dabd8 2028 } else {
2029 $mail->IsHTML(false);
78681899 2030 $mail->Body = "\n$messagetext\n";
f9903ed0 2031 }
2032
136dabd8 2033 if ($attachment && $attachname) {
2034 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
b0ccd3fb 2035 $mail->AddAddress($adminuser->email, fullname($adminuser) );
2036 $mail->AddStringAttachment('Error in attachment. User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
136dabd8 2037 } else {
b0ccd3fb 2038 include_once($CFG->dirroot .'/files/mimetypes.php');
2039 $mimetype = mimeinfo('type', $attachname);
2040 $mail->AddAttachment($CFG->dataroot .'/'. $attachment, $attachname, 'base64', $mimetype);
136dabd8 2041 }
f9903ed0 2042 }
2043
136dabd8 2044 if ($mail->Send()) {
2045 return true;
2046 } else {
b0ccd3fb 2047 mtrace('ERROR: '. $mail->ErrorInfo);
2048 add_to_log(SITEID, 'library', 'mailer', $_SERVER['REQUEST_URI'], 'ERROR: '. $mail->ErrorInfo);
f9903ed0 2049 return false;
2050 }
f9903ed0 2051}
2052
7cf1c7bd 2053/**
2054 * Resets specified user's password and send the new password to the user via email.
2055 *
2056 * @uses $CFG
2057 * @param object $user
2058 * @return boolean
2059 */
1d881d92 2060function reset_password_and_mail($user) {
2061
2062 global $CFG;
2063
2064 $site = get_site();
2065 $from = get_admin();
2066
2067 $newpassword = generate_password();
2068
b0ccd3fb 2069 if (! set_field('user', 'password', md5($newpassword), 'id', $user->id) ) {
2070 error('Could not set user password!');
1d881d92 2071 }
2072
2073 $a->firstname = $user->firstname;
2074 $a->sitename = $site->fullname;
2075 $a->username = $user->username;
2076 $a->newpassword = $newpassword;
b0ccd3fb 2077 $a->link = $CFG->wwwroot .'/login/change_password.php';
2078 $a->signoff = fullname($from, true).' ('. $from->email .')';
1d881d92 2079
b0ccd3fb 2080 $message = get_string('newpasswordtext', '', $a);
1d881d92 2081
b0ccd3fb 2082 $subject = $site->fullname .': '. get_string('changedpassword');
1d881d92 2083
2084 return email_to_user($user, $from, $subject, $message);
2085
2086}
2087
7cf1c7bd 2088/**
2089 * Send email to specified user with confirmation text and activation link.
2090 *
2091 * @uses $CFG
2092 * @param object $user
2093 * @return boolean
2094 */
2095 function send_confirmation_email($user) {
1d881d92 2096
2097 global $CFG;
2098
2099 $site = get_site();
2100 $from = get_admin();
2101
2102 $data->firstname = $user->firstname;
2103 $data->sitename = $site->fullname;
b0ccd3fb 2104 $data->link = $CFG->wwwroot .'/login/confirm.php?p='. $user->secret .'&amp;s='. $user->username;
2105 $data->admin = fullname($from) .' ('. $from->email .')';
1d881d92 2106
b0ccd3fb 2107 $message = get_string('emailconfirmation', '', $data);
2108 $subject = get_string('emailconfirmationsubject', '', $site->fullname);
1d881d92 2109
58d24720 2110 $messagehtml = text_to_html($message, false, false, true);
2111
2112 return email_to_user($user, $from, $subject, $message, $messagehtml);
1d881d92 2113
2114}
2115
7cf1c7bd 2116/**
2117 * send_password_change_confirmation_email.
2118 *
2119 * @param type description
2120 * @todo Finish documenting this function
2121 */
eb347b6b 2122function send_password_change_confirmation_email($user) {
2123
2124 global $CFG;
2125
2126 $site = get_site();
2127 $from = get_admin();
2128
2129 $data->firstname = $user->firstname;
2130 $data->sitename = $site->fullname;
b0ccd3fb 2131 $data->link = $CFG->wwwroot .'/login/forgot_password.php?p='. $user->secret .'&amp;s='. $user->username;
2132 $data->admin = fullname($from).' ('. $from->email .')';
eb347b6b 2133
b0ccd3fb 2134 $message = get_string('emailpasswordconfirmation', '', $data);
2135 $subject = get_string('emailpasswordconfirmationsubject', '', $site->fullname);
eb347b6b 2136
2137 return email_to_user($user, $from, $subject, $message);
2138
2139}
2140
7cf1c7bd 2141/**
2142 * Check that an email is allowed. It returns an error message if there
2143 * was a problem.
2144 *
2145 * @param type description
2146 * @todo Finish documenting this function
2147 */
85a1d4c9 2148function email_is_not_allowed($email) {
85a1d4c9 2149
2150 global $CFG;
2151
2152 if (!empty($CFG->allowemailaddresses)) {
2153 $allowed = explode(' ', $CFG->allowemailaddresses);
2154 foreach ($allowed as $allowedpattern) {
2155 $allowedpattern = trim($allowedpattern);
2156 if (!$allowedpattern) {
2157 continue;
2158 }
2159 if (strpos($email, $allowedpattern) !== false) { // Match!
2160 return false;
2161 }
2162 }
b0ccd3fb 2163 return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
85a1d4c9 2164
2165 } else if (!empty($CFG->denyemailaddresses)) {
2166 $denied = explode(' ', $CFG->denyemailaddresses);
2167 foreach ($denied as $deniedpattern) {
2168 $deniedpattern = trim($deniedpattern);
2169 if (!$deniedpattern) {
2170 continue;
2171 }
2172 if (strpos($email, $deniedpattern) !== false) { // Match!
b0ccd3fb 2173 return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
85a1d4c9 2174 }
2175 }
2176 }
2177
2178 return false;
2179}
1d881d92 2180
136dabd8 2181
f9903ed0 2182/// FILE HANDLING /////////////////////////////////////////////
2183
7cf1c7bd 2184/**
8c3dba73 2185 * Create a directory. Returns full directory if successful, false if not.
7cf1c7bd 2186 *
2187 * @uses $CFG
8c3dba73 2188 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
7cf1c7bd 2189 * @return object
2190 * @todo Finish documenting this function
2191 */
66f9a82c 2192function make_upload_directory($directory, $shownotices=true) {
6b174680 2193
2194 global $CFG;
2195
2196 $currdir = $CFG->dataroot;
fe287429 2197
2e6d4273 2198 umask(0000);
2199
6b174680 2200 if (!file_exists($currdir)) {
2e6d4273 2201 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2202 if ($shownotices) {
b0ccd3fb 2203 notify('ERROR: You need to create the directory '. $currdir .' with web server write access');
66f9a82c 2204 }
6b174680 2205 return false;
2206 }
2207 }
2208
b0ccd3fb 2209 $dirarray = explode('/', $directory);
6b174680 2210
2211 foreach ($dirarray as $dir) {
b0ccd3fb 2212 $currdir = $currdir .'/'. $dir;
6b174680 2213 if (! file_exists($currdir)) {
2e6d4273 2214 if (! mkdir($currdir, $CFG->directorypermissions)) {
66f9a82c 2215 if ($shownotices) {
b0ccd3fb 2216 notify('ERROR: Could not find or create a directory ('. $currdir .')');
66f9a82c 2217 }
6b174680 2218 return false;
2219 }
feffa4e6 2220 @chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
6b174680 2221 }
2222 }
2223
2224 return $currdir;
2225}
1e03c552 2226
7cf1c7bd 2227/**
2228 * Makes an upload directory for a particular module.
2229 *
2230 * @uses $CFG
2231 * @param integer $courseid ?
2232 * @todo Finish documenting this function
2233 */
ca4f8eb8 2234function make_mod_upload_directory($courseid) {
2235 global $CFG;
2236
b0ccd3fb 2237 if (! $moddata = make_upload_directory($courseid .'/'. $CFG->moddata)) {
ca4f8eb8 2238 return false;
2239 }
2240
b0ccd3fb 2241 $strreadme = get_string('readme');
ca4f8eb8 2242
b0ccd3fb 2243 if (file_exists($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt')) {
2244 copy($CFG->dirroot .'/lang/'. $CFG->lang .'/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2245 } else {
b0ccd3fb 2246 copy($CFG->dirroot .'/lang/en/docs/module_files.txt', $moddata .'/'. $strreadme .'.txt');
ca4f8eb8 2247 }
2248 return $moddata;
2249}
2250
7cf1c7bd 2251/**
2252 * Returns current name of file on disk if true.
2253 *
2254 * @param string $newfile ?
2255 * @todo Finish documenting this function
2256 */
44e2d2bb 2257function valid_uploaded_file($newfile) {
9c9f7d77 2258 if (empty($newfile)) {
b0ccd3fb 2259 return '';
9c9f7d77 2260 }
44e2d2bb 2261 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
2262 return $newfile['tmp_name'];
2263 } else {
b0ccd3fb 2264 return '';
44e2d2bb 2265 }
2266}
2267
7cf1c7bd 2268/**
2269 * Returns the maximum size for uploading files.
2270 *
2271 * There are seven possible upload limits:
2272 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
2273 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
2274 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
2275 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
2276 * 5. by the Moodle admin in $CFG->maxbytes
2277 * 6. by the teacher in the current course $course->maxbytes
2278 * 7. by the teacher for the current module, eg $assignment->maxbytes
2279 *
2280 * These last two are passed to this function as arguments (in bytes).
2281 * Anything defined as 0 is ignored.
2282 * The smallest of all the non-zero numbers is returned.
2283 *
2284 * @param type description
2285 * @todo Finish documenting this function
2286 */
4909e176 2287function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 2288
b0ccd3fb 2289 if (! $filesize = ini_get('upload_max_filesize')) {
2290 $filesize = '5M';
44e2d2bb 2291 }
4909e176 2292 $minimumsize = get_real_size($filesize);
2293
b0ccd3fb 2294 if ($postsize = ini_get('post_max_size')) {
316ebf78 2295 $postsize = get_real_size($postsize);
2296 if ($postsize < $minimumsize) {
2297 $minimumsize = $postsize;
2298 }
2299 }
2300
4909e176 2301 if ($sitebytes and $sitebytes < $minimumsize) {
2302 $minimumsize = $sitebytes;
2303 }
2304
2305 if ($coursebytes and $coursebytes < $minimumsize) {
2306 $minimumsize = $coursebytes;
2307 }
2308
2309 if ($modulebytes and $modulebytes < $minimumsize) {
2310 $minimumsize = $modulebytes;
2311 }
2312
2313 return $minimumsize;
2314}
2315
7cf1c7bd 2316/**
2317 * Related to the above function - this function returns an
2318 * array of possible sizes in an array, translated to the
2319 * local language.
2320 *
2321 * @param integer $sizebytes ?
2322 * @param integer $coursebytes ?
2323 * @param integer $modulebytes
2324 * @return integer
2325 * @todo Finish documenting this function
2326 */
4909e176 2327function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
4909e176 2328
2329 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
2330 return array();
2331 }
2332
2333 $filesize[$maxsize] = display_size($maxsize);
2334
d8ba183c 2335 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4909e176 2336 5242880, 10485760, 20971520, 52428800, 104857600);
2337
2338 foreach ($sizelist as $sizebytes) {
2339 if ($sizebytes < $maxsize) {
2340 $filesize[$sizebytes] = display_size($sizebytes);
2341 }
2342 }
2343
2344 krsort($filesize, SORT_NUMERIC);
2345
2346 return $filesize;
44e2d2bb 2347}
2348
7cf1c7bd 2349/**
2350 * If there has been an error uploading a file, print the appropriate error message
2351 * Numerical constants used as constant definitions not added until PHP version 4.2.0
2352 *
2353 * filearray is a 1-dimensional sub-array of the $_FILES array
2354 * eg $filearray = $_FILES['userfile1']
8c3dba73 2355 * If left empty then the first element of the $_FILES array will be used
2356 *
7cf1c7bd 2357 * @param array $filearray ?
2358 * @param boolean $returnerror
2359 * @return boolean
2360 * @todo Finish documenting this function
2361 */
ebd52396 2362function print_file_upload_error($filearray = '', $returnerror = false) {
ebd52396 2363
2364 if ($filearray == '' or !isset($filearray['error'])) {
2365
2366 if (empty($_FILES)) return false;
2367
2368 $files = $_FILES; /// so we don't mess up the _FILES array for subsequent code
2369 $filearray = array_shift($files); /// use first element of array
2370 }
2371
2372 switch ($filearray['error']) {
2373
2374 case 0: // UPLOAD_ERR_OK
2375 if ($filearray['size'] > 0) {
2376 $errmessage = get_string('uploadproblem', $filearray['name']);
2377 } else {
2378 $errmessage = get_string('uploadnofilefound'); /// probably a dud file name
2379 }
2380 break;
2381
2382 case 1: // UPLOAD_ERR_INI_SIZE
2383 $errmessage = get_string('uploadserverlimit');
2384 break;
2385
2386 case 2: // UPLOAD_ERR_FORM_SIZE
2387 $errmessage = get_string('uploadformlimit');
2388 break;
2389
2390 case 3: // UPLOAD_ERR_PARTIAL
2391 $errmessage = get_string('uploadpartialfile');
2392 break;
2393
2394 case 4: // UPLOAD_ERR_NO_FILE
2395 $errmessage = get_string('uploadnofilefound');
2396 break;
2397
2398 default:
2399 $errmessage = get_string('uploadproblem', $filearray['name']);
2400 }
2401
2402 if ($returnerror) {
2403 return $errmessage;
2404 } else {
2405 notify($errmessage);
2406 return true;
2407 }
2408
2409}
2410
7cf1c7bd 2411/**
2412 * Returns an array with all the filenames in
2413 * all subdirectories, relative to the given rootdir.
2414 * If excludefile is defined, then that file/directory is ignored
2415 * If getdirs is true, then (sub)directories are included in the output
2416 * If getfiles is true, then files are included in the output
2417 * (at least one of these must be true!)
2418 *
2419 * @param type name definition
2420 * @return array
2421 * @todo Finish documenting this function
2422 */
b0ccd3fb 2423function get_directory_list($rootdir, $excludefile='', $descend=true, $getdirs=false, $getfiles=true) {
f9903ed0 2424
2425 $dirs = array();
f9903ed0 2426
16a5602c 2427 if (!$getdirs and !$getfiles) { // Nothing to show
12407705 2428 return $dirs;
2429 }
2430
16a5602c 2431 if (!is_dir($rootdir)) { // Must be a directory
2432 return $dirs;
2433 }
2434
2435 if (!$dir = opendir($rootdir)) { // Can't open it for some reason
d897cae4 2436 return $dirs;
2437 }
2438
81fcd0f0 2439 while (false !== ($file = readdir($dir))) {
b35e8568 2440 $firstchar = substr($file, 0, 1);
b0ccd3fb 2441 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
b35e8568 2442 continue;
2443 }
b0ccd3fb 2444 $fullfile = $rootdir .'/'. $file;
2445 if (filetype($fullfile) == 'dir') {
16a5602c 2446 if ($getdirs) {
55fd8177 2447 $dirs[] = $file;
2448 }
bf5c2e84 2449 if ($descend) {
16a5602c 2450 $subdirs = get_directory_list($fullfile, $excludefile, $descend, $getdirs, $getfiles);
bf5c2e84 2451 foreach ($subdirs as $subdir) {
b0ccd3fb 2452 $dirs[] = $file .'/'. $subdir;
bf5c2e84 2453 }
f9903ed0 2454 }
16a5602c 2455 } else if ($getfiles) {
b35e8568 2456 $dirs[] = $file;
f9903ed0 2457 }
2458 }
44e2d2bb 2459 closedir($dir);
f9903ed0 2460
774ab660 2461 asort($dirs);
2462
f9903ed0 2463 return $dirs;
2464}
2465
7cf1c7bd 2466/**
2467 * Adds up all the files in a directory and works out the size.
2468 *
2469 * @param string $rootdir ?
2470 * @param string $excludefile ?
2471 * @return object
2472 * @todo Finish documenting this function
2473 */
b0ccd3fb 2474function get_directory_size($rootdir, $excludefile='') {
16a5602c 2475
2476 $size = 0;
2477
2478 if (!is_dir($rootdir)) { // Must be a directory
2479 return $dirs;
2480 }
2481
b5b90f26 2482 if (!$dir = @opendir($rootdir)) { // Can't open it for some reason
16a5602c 2483 return $dirs;
2484 }
2485
2486 while (false !== ($file = readdir($dir))) {
2487 $firstchar = substr($file, 0, 1);
b0ccd3fb 2488 if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
16a5602c 2489 continue;
2490 }
b0ccd3fb 2491 $fullfile = $rootdir .'/'. $file;
2492 if (filetype($fullfile) == 'dir') {
16a5602c 2493 $size += get_directory_size($fullfile, $excludefile);
2494 } else {
2495 $size += filesize($fullfile);
2496 }
2497 }
2498 closedir($dir);
2499
2500 return $size;
2501}
2502
7cf1c7bd 2503/**
2504 * Converts numbers like 10M into bytes.
2505 *
2506 * @uses $CFG
2507 * @param mixed $size The size to be converted
2508 * @return mixed
2509 */
989bfa9d 2510function get_real_size($size=0) {
989bfa9d 2511 if (!$size) {
d8ba183c 2512 return 0;
989bfa9d 2513 }
2514 $scan['MB'] = 1048576;
64efda84 2515 $scan['Mb'] = 1048576;
989bfa9d 2516 $scan['M'] = 1048576;
266a416e 2517 $scan['m'] = 1048576;
989bfa9d 2518 $scan['KB'] = 1024;
64efda84 2519 $scan['Kb'] = 1024;
989bfa9d 2520 $scan['K'] = 1024;
266a416e 2521 $scan['k'] = 1024;
989bfa9d 2522
2523 while (list($key) = each($scan)) {
2524 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
2525 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
2526 break;
2527 }
2528 }
2529 return $size;
2530}
2531
7cf1c7bd 2532/**
2533 * Converts bytes into display form
2534 *
2535 * @uses $CFG
2536 * @param string $directory a string of directory names under $CFG->dataroot
2537 * @return object
2538 * @todo Finish documenting this function
2539 */
44e2d2bb 2540function display_size($size) {
4909e176 2541
7cf1c7bd 2542 static $gb, $mb, $kb, $b;
4909e176 2543
2544 if (empty($gb)) {
2545 $gb = get_string('sizegb');
2546 $mb = get_string('sizemb');
2547 $kb = get_string('sizekb');
2548 $b = get_string('sizeb');
2549 }
2550
44e2d2bb 2551 if ($size >= 1073741824) {
4909e176 2552 $size = round($size / 1073741824 * 10) / 10 . $gb;
44e2d2bb 2553 } else if ($size >= 1048576) {
4909e176 2554 $size = round($size / 1048576 * 10) / 10 . $mb;
44e2d2bb 2555 } else if ($size >= 1024) {
4909e176 2556 $size = round($size / 1024 * 10) / 10 . $kb;
d8ba183c 2557 } else {
b0ccd3fb 2558 $size = $size .' '. $b;
44e2d2bb 2559 }
2560 return $size;
2561}
2562
7cf1c7bd 2563/**
8c3dba73 2564 * Cleans a given filename by removing suspicious or troublesome characters
2565 * Only these are allowed:
2566 * alphanumeric _ - .
7cf1c7bd 2567 *
2568 * @uses $CFG
2569 * @param string $directory a string of directory names under $CFG->dataroot
2570 * @return object
2571 * @todo Finish documenting this function
2572 */
6b174680 2573function clean_filename($string) {
b0ccd3fb 2574 $string = eregi_replace("\.\.+", '', $string);
8644437d 2575 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
b0ccd3fb 2576 $string = eregi_replace("_+", '_', $string);
bbf4d8e6 2577 return $string;
6b174680 2578}
2579
2580
1180c6dc 2581/// STRING TRANSLATION ////////////////////////////////////////
2582
8c3dba73 2583/**
2584 * Returns the code for the current language
2585 *
2586 * @uses $CFG
2587 * @param $USER
2588 * @param $SESSION
2589 * @return string
2590 */
4bfa92e7 2591function current_language() {
3db3acfb 2592 global $CFG, $USER, $SESSION;
4bfa92e7 2593
e5415d58 2594 if (!empty($CFG->courselang)) { // Course language can override all other settings for this page
b3153e4b 2595 return $CFG->courselang;
2596
e5415d58 2597 } else if (!empty($SESSION->lang)) { // Session language can override other settings
3db3acfb 2598 return $SESSION->lang;
2599
e5415d58 2600 } else if (!empty($USER->lang)) { // User language can override site language
4bfa92e7 2601 return $USER->lang;
3db3acfb 2602
4bfa92e7 2603 } else {
2604 return $CFG->lang;
2605 }
2606}
bcc83c41 2607
8c3dba73 2608/**
2609 * Given a string to translate - prints it out.
2610 *
2611 * @param type description
2612 * @todo Finish documenting this function
2613 */
b0ccd3fb 2614function print_string($identifier, $module='', $a=NULL) {
9fa49e22 2615 echo get_string($identifier, $module, $a);
2616}
2617
8c3dba73 2618/**
2619 * Return the translated string specified by $identifier as
2620 * for $module. Uses the same format files as STphp.
2621 * $a is an object, string or number that can be used
2622 * within translation strings
2623 *
2624 * eg "hello \$a->firstname \$a->lastname"
2625 * or "hello \$a"
2626 *
2627 * @uses $CFG
2628 * @param type description
2629 * @todo Finish documenting this function
2630 */
2631function get_string($identifier, $module='', $a=NULL) {
1180c6dc 2632
4bfa92e7 2633 global $CFG;
1180c6dc 2634
e11dc9b6 2635 global $course; /// Not a nice hack, but quick
ac8abb5f 2636 if (empty($CFG->courselang)) {
2637 if (!empty($course->lang)) {
2638 $CFG->courselang = $course->lang;
2639 }
e11dc9b6 2640 }
2641
4bfa92e7 2642 $lang = current_language();
1180c6dc 2643
b0ccd3fb 2644 if ($module == '') {
2645 $module = 'moodle';
1180c6dc 2646 }
2647
b0ccd3fb 2648 $langpath = $CFG->dirroot .'/lang';
7cf1c7bd 2649 $langfile = $langpath .'/'. $lang .'/'. $module .'.php';
1180c6dc 2650
b947c69a 2651 // Look for the string - if found then return it
2652
2653 if (file_exists($langfile)) {
2654 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
2655 eval($result);
2656 return $resultstring;
1180c6dc 2657 }
2658 }
2659
cdac797c 2660 // If it's a module, then look within the module pack itself mod/xxxx/lang/en/module.php
2661
b0ccd3fb 2662 if ($module != 'moodle') {
2663 $modlangpath = $CFG->dirroot .'/mod/'. $module .'/lang';
2664 $langfile = $modlangpath .'/'. $lang .'/'. $module .'.php';
cdac797c 2665 if (file_exists($langfile)) {
2666 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
2667 eval($result);
2668 return $resultstring;
2669 }
2670 }
2671 }
1180c6dc 2672
cdac797c 2673 // If the preferred language was English we can abort now
b0ccd3fb 2674 if ($lang == 'en') {
2675 return '[['. $identifier .']]';
b947c69a 2676 }
1180c6dc 2677
b947c69a 2678 // Is a parent language defined? If so, try it.
d8ba183c 2679
b0ccd3fb 2680 if ($result = get_string_from_file('parentlanguage', $langpath .'/'. $lang .'/moodle.php', "\$parentlang")) {
b947c69a 2681 eval($result);
2682 if (!empty($parentlang)) {
b0ccd3fb 2683 $langfile = $langpath .'/'. $parentlang .'/'. $module .'.php';
b947c69a 2684 if (file_exists($langfile)) {
2685 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
2686 eval($result);
2687 return $resultstring;
2688 }
1180c6dc 2689 }
2690 }
2691 }
b947c69a 2692
2693 // Our only remaining option is to try English
2694
b0ccd3fb 2695 $langfile = $langpath .'/en/'. $module .'.php';
b947c69a 2696 if (!file_exists($langfile)) {
b0ccd3fb 2697 return 'ERROR: No lang file ('. $langpath .'/en/'. $module .'.php)!';
b947c69a 2698 }
2699 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
2700 eval($result);
2701 return $resultstring;
2702 }
2703
cdac797c 2704 // If it's a module, then look within the module pack itself mod/xxxx/lang/en/module.php
2705
b0ccd3fb 2706 if ($module != 'moodle') {
2707 $langfile = $modlangpath .'/en/'. $module .'.php';
cdac797c 2708 if (file_exists($langfile)) {
2709 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
2710 eval($result);
2711 return $resultstring;
2712 }
2713 }
2714 }
2715
b0ccd3fb 2716 return '[['. $identifier .']]'; // Last resort
1180c6dc 2717}
2718
8c3dba73 2719/**
2720 * This function is only used from get_string().
2721 *
2722 * @param type description
2723 * @todo Finish documenting this function. Should be marked as private.
2724 */
1180c6dc 2725function get_string_from_file($identifier, $langfile, $destination) {
2b32bddd 2726
2727 static $strings; // Keep the strings cached in memory.
2728
2729 if (empty($strings[$langfile])) {
a32c99e2 2730 $string = array();
2b32bddd 2731 include ($langfile);
2732 $strings[$langfile] = $string;
2733 } else {
2734 $string = &$strings[$langfile];
2735 }
1180c6dc 2736
2737 if (!isset ($string[$identifier])) {
2738 return false;
2739 }
2740
b0ccd3fb 2741 return $destination .'= sprintf("'. $string[$identifier] .'");';
1180c6dc 2742}
f9903ed0 2743
8c3dba73 2744/**
2745 * Converts an array of strings to their localized value.
2746 *
2747 * @param array $array An array of strings
2748 * @param string $module The language module that these strings can be found in.
2749 * @return string
2750 */
9d3c795c 2751function get_strings($array, $module='') {
9d3c795c 2752
2753 $string = NULL;
2754 foreach ($array as $item) {
2755 $string->$item = get_string($item, $module);
2756 }
2757 return $string;
2758}
f9903ed0 2759
8c3dba73 2760/**
2761 * Returns a list of language codes and their full names
2762 *
2763 * @param type description
2764 * @todo Finish documenting this function
2765 */
1a72314d 2766function get_list_of_languages() {
1a72314d 2767 global $CFG;
2768
984a8bf3 2769 $languages = array();
2770
2771 if (!empty($CFG->langlist)) { // use admin's list of languages
2772 $langlist = explode(',', $CFG->langlist);
2773 foreach ($langlist as $lang) {
b0ccd3fb 2774 if (file_exists($CFG->dirroot .'/lang/'. $lang .'/moodle.php')) {
2775 include($CFG->dirroot .'/lang/'. $lang .'/moodle.php');
2776 $languages[$lang] = $string['thislanguage'].' ('. $lang .')';
984a8bf3 2777 unset($string);
2778 }
2779 }
2780 } else {
b0ccd3fb 2781 if (!$langdirs = get_list_of_plugins('lang')) {
984a8bf3 2782 return false;
2783 }
2784 foreach ($langdirs as $lang) {
b0ccd3fb 2785 include($CFG->dirroot .'/lang/'. $lang .'/moodle.php');
2786 $languages[$lang] = $string['thislanguage'] .' ('. $lang .')';
984a8bf3 2787 unset($string);
2788 }
1a72314d 2789 }
2790
1a72314d 2791 return $languages;
2792}
2793
8c3dba73 2794/**
2795 * Returns a list of country names in the current language
2796 *
2797 * @param type description
2798 * @todo Finish documenting this function
2799 */
5833a6c8 2800function get_list_of_countries() {
5833a6c8 2801 global $CFG, $USER;
2802
2803 $lang = current_language();
2804
b0ccd3fb 2805 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/countries.php')) {
2806 if ($parentlang = get_string('parentlanguage')) {
2807 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/countries.php')) {
aa3eb050 2808 $lang = $parentlang;
2809 } else {
b0ccd3fb 2810 $lang = 'en'; // countries.php must exist in this pack
aa3eb050 2811 }
2812 } else {
b0ccd3fb 2813 $lang = 'en'; // countries.php must exist in this pack
aa3eb050 2814 }
5833a6c8 2815 }
2816
b0ccd3fb 2817 include($CFG->dirroot .'/lang/'. $lang .'/countries.php');
5833a6c8 2818
f8dbffb1 2819 if (!empty($string)) {
2820 asort($string);
2821 }
5833a6c8 2822
2823 return $string;
2824}
2825
8c3dba73 2826/**
2827 * Returns a list of picture names in the current language
2828 *
2829 * @param type description
2830 * @todo Finish documenting this function
2831 */
2832function get_list_of_pixnames() {
82196932 2833 global $CFG;
2834
2835 $lang = current_language();
2836
b0ccd3fb 2837 if (!file_exists($CFG->dirroot .'/lang/'. $lang .'/pix.php')) {
2838 if ($parentlang = get_string('parentlanguage')) {
2839 if (file_exists($CFG->dirroot .'/lang/'. $parentlang .'/pix.php')) {
82196932 2840 $lang = $parentlang;
2841 } else {
b0ccd3fb 2842 $lang = 'en'; // countries.php must exist in this pack
82196932 2843 }
2844 } else {
b0ccd3fb 2845 $lang = 'en'; // countries.php must exist in this pack
82196932 2846 }
2847 }
2848
b0ccd3fb 2849 include_once($CFG->dirroot .'/lang/'. $lang .'/pix.php');
82196932 2850
2851 return $string;
2852}
2853
8c3dba73 2854/**
2855 * Can include a given document file (depends on second
2856 * parameter) or just return info about it.
2857 *
2858 * @param type description
2859 * @todo Finish documenting this function
2860 */
2861function document_file($file, $include=true) {
c9d4e6da 2862 global $CFG;
9bd2c874 2863
db356340 2864 $file = clean_filename($file);
2865
9bd2c874 2866 if (empty($file)) {
9bd2c874 2867 return false;
2868 }
2869
b0ccd3fb 2870 $langs = array(current_language(), get_string('parentlanguage'), 'en');
9bd2c874 2871
db356340 2872 foreach ($langs as $lang) {
b0ccd3fb 2873 $info->filepath = $CFG->dirroot .'/lang/'. $lang .'/docs/'. $file;
2874 $info->urlpath = $CFG->wwwroot .'/lang/'. $lang .'/docs/'. $file;
9bd2c874 2875
db356340 2876 if (file_exists($info->filepath)) {
2877 if ($include) {
2878 include($info->filepath);
2879 }
2880 return $info;
0c106cd3 2881 }
9bd2c874 2882 }
2883
db356340 2884 return false;
9bd2c874 2885}
2886
1a72314d 2887
f9903ed0 2888/// ENCRYPTION ////////////////////////////////////////////////
2889
8c3dba73 2890/**
2891 * rc4encrypt
2892 *
2893 * @param string $data ?
2894 * @todo Finish documenting this function
2895 */
f9903ed0 2896function rc4encrypt($data) {
b0ccd3fb 2897 $password = 'nfgjeingjk';
2898 return endecrypt($password, $data, '');
f9903ed0 2899}
2900
8c3dba73 2901/**
2902 * rc4decrypt
2903 *
2904 * @param string $data ?
2905 * @todo Finish documenting this function
2906 */
f9903ed0 2907function rc4decrypt($data) {
b0ccd3fb 2908 $password = 'nfgjeingjk';
2909 return endecrypt($password, $data, 'de');
f9903ed0 2910}
2911
8c3dba73 2912/**
2913 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
2914 *
2915 * @param type description
2916 * @todo Finish documenting this function
2917 */
2918function endecrypt ($pwd, $data, $case) {
f9903ed0 2919
2920 if ($case == 'de') {
2921 $data = urldecode($data);
2922 }
2923
b0ccd3fb 2924 $key[] = '';
2925 $box[] = '';
2926 $temp_swap = '';
f9903ed0 2927 $pwd_length = 0;
2928
2929 $pwd_length = strlen($pwd);
2930
2931 for ($i = 0; $i <= 255; $i++) {
2932 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
2933 $box[$i] = $i;
2934 }
2935
2936 $x = 0;
2937
2938 for ($i = 0; $i <= 255; $i++) {
2939 $x = ($x + $box[$i] + $key[$i]) % 256;
2940 $temp_swap = $box[$i];
2941 $box[$i] = $box[$x];
2942 $box[$x] = $temp_swap;
2943 }
2944
b0ccd3fb 2945 $temp = '';
2946 $k = '';
f9903ed0 2947
b0ccd3fb 2948 $cipherby = '';
2949 $cipher = '';
f9903ed0 2950
2951 $a = 0;
2952 $j = 0;
2953
2954 for ($i = 0; $i < strlen($data); $i++) {
2955 $a = ($a + 1) % 256;
2956 $j = ($j + $box[$a]) % 256;
2957 $temp = $box[$a];
2958 $box[$a] = $box[$j];
2959 $box[$j] = $temp;
2960 $k = $box[(($box[$a] + $box[$j]) % 256)];
2961 $cipherby = ord(substr($data, $i, 1)) ^ $k;
2962 $cipher .= chr($cipherby);
2963 }
2964
2965 if ($case == 'de') {
2966 $cipher = urldecode(urlencode($cipher));
2967 } else {
2968 $cipher = urlencode($cipher);
2969 }
2970
2971 return $cipher;
2972}
2973
2974
5fba04fb 2975/// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
2976
2977
8c3dba73 2978/**
2979 * call this function to add an event to the calendar table
2980 * and to call any calendar plugins
2981 * The function returns the id number of the resulting record
2982 *
2983 * @param type description
2984 * @todo Finish documenting this function
2985 */
2986 function add_event($event) {
5fba04fb 2987/// The object event should include the following:
2988/// $event->name Name for the event
2989/// $event->description Description of the event (defaults to '')
2990/// $event->courseid The id of the course this event belongs to (0 = all courses)
2991/// $event->groupid The id of the group this event belongs to (0 = no group)
2992/// $event->userid The id of the user this event belongs to (0 = no user)
2993/// $event->modulename Name of the module that creates this event
2994/// $event->instance Instance of the module that owns this event
2995/// $event->eventtype The type info together with the module info could
2996/// be used by calendar plugins to decide how to display event
2997/// $event->timestart Timestamp for start of event
2998/// $event->timeduration Duration (defaults to zero)
2999
3000 global $CFG;
3001
3002 $event->timemodified = time();
d8ba183c 3003
b0ccd3fb 3004 if (!$event->id = insert_record('event', $event)) {
5fba04fb 3005 return false;
3006 }
d8ba183c 3007
5fba04fb 3008 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
b0ccd3fb 3009 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
3010 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5fba04fb 3011 $calendar_add_event = $CFG->calendar.'_add_event';
3012 if (function_exists($calendar_add_event)) {
3013 $calendar_add_event($event);
3014 }
3015 }
3016 }
d8ba183c 3017
5fba04fb 3018 return $event->id;
3019}
3020
8c3dba73 3021/**
3022 * call this function to update an event in the calendar table
3023 * the event will be identified by the id field of the $event object.
3024 *
3025 * @param type description
3026 * @todo Finish documenting this function
3027 */
5fba04fb 3028function update_event($event) {
5fba04fb 3029
3030 global $CFG;
3031
3032 $event->timemodified = time();
d8ba183c 3033
5fba04fb 3034 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
b0ccd3fb 3035 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
3036 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5fba04fb 3037 $calendar_update_event = $CFG->calendar.'_update_event';
3038 if (function_exists($calendar_update_event)) {
3039 $calendar_update_event($event);
3040 }
3041 }
3042 }
b0ccd3fb 3043 return update_record('event', $event);
5fba04fb 3044}
3045
8c3dba73 3046/**
3047 * Call this function to delete the event with id $id from calendar table.
3048 *
3049 * @param type description
3050 * @todo Finish documenting this function
3051 */
5fba04fb 3052function delete_event($id) {
5fba04fb 3053
3054 global $CFG;
3055
3056 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
b0ccd3fb 3057 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
3058 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
5fba04fb 3059 $calendar_delete_event = $CFG->calendar.'_delete_event';
3060 if (function_exists($calendar_delete_event)) {
3061 $calendar_delete_event($id);
3062 }
3063 }
3064 }
b0ccd3fb 3065 return delete_records('event', 'id', $id);
5fba04fb 3066}
3067
8c3dba73 3068/**
3069 * call this function to hide an event in the calendar table
3070 * the event will be identified by the id field of the $event object.
3071 *
3072 * @param type description
3073 * @todo Finish documenting this function
3074 */
dcd338ff 3075function hide_event($event) {
dcd338ff 3076 global $CFG;
3077
3078 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
b0ccd3fb 3079 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
3080 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
dcd338ff 3081 $calendar_hide_event = $CFG->calendar.'_hide_event';
3082 if (function_exists($calendar_hide_event)) {
3083 $calendar_hide_event($event);
3084 }
3085 }
3086 }
3087 return set_field('event', 'visible', 0, 'id', $event->id);
3088}
3089
8c3dba73 3090/**
3091 * Call this function to unhide an event in the calendar table
3092 * the event will be identified by the id field of the $event object.
3093 *
3094 * @param type description
3095 * @todo Finish documenting this function
3096 */
dcd338ff 3097function show_event($event) {
dcd338ff 3098 global $CFG;
3099
3100 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
b0ccd3fb 3101 if (file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
3102 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
dcd338ff 3103 $calendar_show_event = $CFG->calendar.'_show_event';
3104 if (function_exists($calendar_show_event)) {
3105 $calendar_show_event($event);
3106 }
3107 }
3108 }
3109 return set_field('event', 'visible', 1, 'id', $event->id);
3110}
5fba04fb 3111
3112
9fa49e22 3113/// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
1e3e716f 3114
8c3dba73 3115/**
3116 * Lists plugin directories within some directory
3117 *
3118 * @param type description
3119 * @todo Finish documenting this function
3120 */
b0ccd3fb 3121function get_list_of_plugins($plugin='mod', $exclude='') {
1d881d92 3122
3123 global $CFG;
3124
b0ccd3fb 3125 $basedir = opendir($CFG->dirroot .'/'. $plugin);
1d881d92 3126 while ($dir = readdir($basedir)) {
b35e8568 3127 $firstchar = substr($dir, 0, 1);
b0ccd3fb 3128 if ($firstchar == '.' or $dir == 'CVS' or $dir == '_vti_cnf' or $dir == $exclude) {
1d881d92 3129 continue;
3130 }
b0ccd3fb 3131 if (filetype($CFG->dirroot .'/'. $plugin .'/'. $dir) != 'dir') {
1d881d92 3132 continue;
3133 }
3134 $plugins[] = $dir;
3135 }
3136 if ($plugins) {
3137 asort($plugins);
3138 }
3139 return $plugins;
3140}
3141
8c3dba73 3142/**
3143 * Returns true is the current version of PHP is greater that the specified one.
3144 *
3145 * @param type description
3146 * @todo Finish documenting this function
3147 */
b0ccd3fb 3148function check_php_version($version='4.1.0') {
8c3dba73 3149 $minversion = intval(str_replace('.', '', $version));
b0ccd3fb 3150 $curversion = intval(str_replace('.', '', phpversion()));
b0cb5e22 3151 return ($curversion >= $minversion);
3152}
3153
0095d5cd 3154
8c3dba73 3155/**
3156 * Checks to see if is a browser matches the specified
3157 * brand and is equal or better version.
3158 *
3159 * @param type description
3160 * @todo Finish documenting this function
3161 */
3162 function check_browser_version($brand='MSIE', $version=5.5) {
b0ccd3fb 3163 $agent = $_SERVER['HTTP_USER_AGENT'];
4c46c425 3164
3165 if (empty($agent)) {
0095d5cd 3166 return false;
3167 }
4c46c425 3168
3169 switch ($brand) {
3170
b0ccd3fb 3171 case 'Gecko': /// Gecko based browsers
4c46c425 3172
b0ccd3fb 3173 if (substr_count($agent, 'Camino')) { // MacOS X Camino not supported.
4c46c425 3174 return false;
3175 }
3176
3177 // the proper string - Gecko/CCYYMMDD Vendor/Version
3178 if (ereg("^([a-zA-Z]+)/([0-9]+\.[0-9]+) \((.*)\) (.*)$", $agent, $match)) {
3179 if (ereg("^([Gecko]+)/([0-9]+)",$match[4], $reldate)) {
3180 if ($reldate[2] > $version) {
3181 return true;
3182 }
3183 }
3184 }
3185 break;
3186
3187
b0ccd3fb 3188 case 'MSIE': /// Internet Explorer
4c46c425 3189
0e2585ac 3190 if (strpos($agent, 'Opera')) { // Reject Opera
3191 return false;
3192 }
b0ccd3fb 3193 $string = explode(';', $agent);
4c46c425 3194 if (!isset($string[1])) {
3195 return false;
3196 }
b0ccd3fb 3197 $string = explode(' ', trim($string[1]));
4c46c425 3198 if (!isset($string[0]) and !isset($string[1])) {
3199 return false;
3200 }
3201 if ($string[0] == $brand and (float)$string[1] >= $version ) {
3202 return true;
3203 }
3204 break;
3205
0095d5cd 3206 }
4c46c425 3207
0095d5cd 3208 return false;
3209}
3210
8c3dba73 3211/**
3212 * This function makes the return value of ini_get consistent if you are
3213 * setting server directives through the .htaccess file in apache.
3214 * Current behavior for value set from php.ini On = 1, Off = [blank]
3215 * Current behavior for value set from .htaccess On = On, Off = Off
3216 * Contributed by jdell @ unr.edu
3217 *
3218 * @param type description
3219 * @todo Finish documenting this function
3220 */
3221function ini_get_bool($ini_get_arg) {
c39c66a5 3222 $temp = ini_get($ini_get_arg);
3223
b0ccd3fb 3224 if ($temp == '1' or strtolower($temp) == 'on') {
c39c66a5 3225 return true;
3226 }
3227 return false;
3228}
3229
8c3dba73 3230/**
3231 * Compatibility stub to provide backward compatibility
3232 *
3233 * @param type description
3234 * @todo Finish documenting this function. Mark as deprecated.
3235 */
3236 function can_use_richtext_editor() {
47037513 3237 return can_use_html_editor();
3238}
3239
4c46c425 3240
8c3dba73 3241/**
3242 * Is the HTML editor enabled? This depends on site and user
3243 * settings, as well as the current browser being used.
3244 * Returns false is editor is not being used, otherwise
3245 * returns "MSIE" or "Gecko"
3246 *
3247 * @param type description
3248 * @todo Finish documenting this function
3249 */
3250 function can_use_html_editor() {
0095d5cd 3251 global $USER, $CFG;
4c46c425 3252
ce78926d 3253 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
b0ccd3fb 3254 if (check_browser_version('MSIE', 5.5)) {
3255 return 'MSIE';
3256 } else if (check_browser_version('Gecko', 20030516)) {
3257 return 'Gecko';
4c46c425 3258 }
7ce20f09 3259 }
3260 return false;
0095d5cd 3261}
3262
8c3dba73 3263/**
3264 * Hack to find out the GD version by parsing phpinfo output
3265 *
3266 * @param type description
3267 * @todo Finish documenting this function
3268 */
74944b73 3269function check_gd_version() {
aa095969 3270 $gdversion = 0;
74944b73 3271
aa095969 3272 if (function_exists('gd_info')){
3273 $gd_info = gd_info();
b0ccd3fb 3274 if (substr_count($gd_info['GD Version'], '2.')) {
aa095969 3275 $gdversion = 2;
b0ccd3fb 3276 } else if (substr_count($gd_info['GD Version'], '1.')) {
3ee23682 3277 $gdversion = 1;
aa095969 3278 }
3ee23682 3279
aa095969 3280 } else {
3281 ob_start();
3282 phpinfo(8);
3283 $phpinfo = ob_get_contents();
3284 ob_end_clean();
74944b73 3285
aa095969 3286 $phpinfo = explode("\n",$phpinfo);
74944b73 3287
92a4b0f1 3288
aa095969 3289 foreach ($phpinfo as $text) {
3290 $parts = explode('</td>',$text);
3291 foreach ($parts as $key => $val) {
3292 $parts[$key] = trim(strip_tags($val));
3293 }
b0ccd3fb 3294 if ($parts[0] == 'GD Version') {
3295 if (substr_count($parts[1], '2.0')) {
3296 $parts[1] = '2.0';
aa095969 3297 }
3298 $gdversion = intval($parts[1]);
92a4b0f1 3299 }
74944b73 3300 }
3301 }
3302
3303 return $gdversion; // 1, 2 or 0
3304}
f9903ed0 3305
8c3dba73 3306/**
3307 * Checks version numbers of Main code and all modules to see
3308 * if there are any mismatches ... returns true or false
3309 *
3310 * @param type description
3311 * @todo Finish documenting this function
3312 */
3313function moodle_needs_upgrading() {
9fa49e22 3314 global $CFG;
3315
b0ccd3fb 3316 include_once($CFG->dirroot .'/version.php'); # defines $version and upgrades
d8ba183c 3317 if ($CFG->version) {
9fa49e22 3318 if ($version > $CFG->version) {
3319 return true;
3320 }
b0ccd3fb 3321 if ($mods = get_list_of_plugins('mod')) {
9fa49e22 3322 foreach ($mods as $mod) {
b0ccd3fb 3323 $fullmod = $CFG->dirroot .'/mod/'. $mod;
9fa49e22 3324 unset($module);
b0ccd3fb 3325 if (!is_readable($fullmod .'/version.php')) {
3326 notify('Module "'. $mod .'" is not readable - check permissions');
1079c8a8 3327 continue;
3328 }
b0ccd3fb 3329 include_once($fullmod .'/version.php'); # defines $module with version etc
3330 if ($currmodule = get_record('modules', 'name', $mod)) {
9fa49e22 3331 if ($module->version > $currmodule->version) {
3332 return true;
3333 }
3334 }
3335 }
3336 }
3337 } else {
3338 return true;
3339 }
3340 return false;
3341}
3342
3343
3344/// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
3345
8c3dba73 3346/**
3347 * notify admin users or admin user of any failed logins (since last notification).
3348 *
3349 * @param type description
3350 * @todo Finish documenting this function
3351 */
9d3c795c 3352function notify_login_failures() {
b40bc478 3353 global $CFG, $db;
9d3c795c 3354
9d3c795c 3355 switch ($CFG->notifyloginfailures) {
3356 case 'mainadmin' :
3357 $recip = array(get_admin());
3358 break;
3359 case 'alladmins':
3360 $recip = get_admins();
3361 break;
3362 }
8f0cd6ef 3363
9d3c795c 3364 if (empty($CFG->lastnotifyfailure)) {
3365 $CFG->lastnotifyfailur