Step 1 of Bug 1223 done.
[moodle.git] / lib / moodlelib.php
CommitLineData
f9903ed0 1<?PHP // $Id$
2
9fa49e22 3///////////////////////////////////////////////////////////////////////////
4// //
5// moodlelib.php //
6// //
7// Main library file of miscellaneous general-purpose Moodle functions //
8// //
9// Other main libraries: //
10// //
11// weblib.php - functions that produce web output //
12// datalib.php - functions that access the database //
13// //
14///////////////////////////////////////////////////////////////////////////
15// //
16// NOTICE OF COPYRIGHT //
17// //
18// Moodle - Modular Object-Oriented Dynamic Learning Environment //
abc3b857 19// http://moodle.org //
9fa49e22 20// //
abc3b857 21// Copyright (C) 1999-2004 Martin Dougiamas http://dougiamas.com //
9fa49e22 22// //
23// This program is free software; you can redistribute it and/or modify //
24// it under the terms of the GNU General Public License as published by //
25// the Free Software Foundation; either version 2 of the License, or //
26// (at your option) any later version. //
27// //
28// This program is distributed in the hope that it will be useful, //
29// but WITHOUT ANY WARRANTY; without even the implied warranty of //
30// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
31// GNU General Public License for more details: //
32// //
33// http://www.gnu.org/copyleft/gpl.html //
34// //
35///////////////////////////////////////////////////////////////////////////
65ccdd8c 36
f374fb10 37/// CONSTANTS /////////////////////////////////////////////////////////////
38
d8ba183c 39define('NOGROUPS', 0);
f374fb10 40define('SEPARATEGROUPS', 1);
41define('VISIBLEGROUPS', 2);
42
f9903ed0 43
9fa49e22 44/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 45
9fa49e22 46function require_variable($var) {
47/// Variable must be present
48 if (! isset($var)) {
49 error("A required parameter was missing");
6b174680 50 }
51}
52
9fa49e22 53function optional_variable(&$var, $default=0) {
54/// Variable may be present, if not then set a default
55 if (! isset($var)) {
56 $var = $default;
6b174680 57 }
58}
59
60
9fa49e22 61function set_config($name, $value) {
62/// No need for get_config because they are usually always available in $CFG
70812e39 63
42282810 64 global $CFG;
65
66 $CFG->$name = $value; // So it's defined for this invocation at least
dfc9ba9b 67
9fa49e22 68 if (get_field("config", "name", "name", $name)) {
69 return set_field("config", "value", $value, "name", $name);
d897cae4 70 } else {
9fa49e22 71 $config->name = $name;
72 $config->value = $value;
73 return insert_record("config", $config);
39917a09 74 }
39917a09 75}
76
39917a09 77
70812e39 78function reload_user_preferences() {
79/// Refresh current USER with all their current preferences
80
81 global $USER;
82
d8ba183c 83 unset($USER->preference);
70812e39 84
85 if ($preferences = get_records('user_preferences', 'userid', $USER->id)) {
86 foreach ($preferences as $preference) {
87 $USER->preference[$preference->name] = $preference->value;
88 }
89 }
90}
91
92function set_user_preference($name, $value) {
93/// Sets a preference for the current user
94
95 global $USER;
96
97 if (empty($name)) {
98 return false;
99 }
100
101 if ($preference = get_record('user_preferences', 'userid', $USER->id, 'name', $name)) {
066af654 102 if (set_field("user_preferences", "value", $value, "id", $preference->id)) {
103 $USER->preference[$name] = $value;
104 return true;
105 } else {
106 return false;
107 }
70812e39 108
109 } else {
110 $preference->userid = $USER->id;
111 $preference->name = $name;
112 $preference->value = (string)$value;
066af654 113 if (insert_record('user_preferences', $preference)) {
70812e39 114 $USER->preference[$name] = $value;
115 return true;
116 } else {
117 return false;
118 }
119 }
120}
121
122function set_user_preferences($prefarray) {
123/// Sets a whole array of preferences for the current user
124
125 if (!is_array($prefarray) or empty($prefarray)) {
126 return false;
127 }
128
129 $return = true;
130 foreach ($prefarray as $name => $value) {
131 // The order is important; if the test for return is done first,
132 // then if one function call fails all the remaining ones will
133 // be "optimized away"
134 $return = set_user_preference($name, $value) and $return;
135 }
136 return $return;
137}
138
139function get_user_preferences($name=NULL, $default=NULL) {
140/// Without arguments, returns all the current user preferences
d8ba183c 141/// as an array. If a name is specified, then this function
142/// attempts to return that particular preference value. If
70812e39 143/// none is found, then the optional value $default is returned,
144/// otherwise NULL.
145
146 global $USER;
147
148 if (empty($USER->preference)) {
149 return $default; // Default value (or NULL)
150 }
151 if (empty($name)) {
152 return $USER->preference; // Whole array
153 }
154 if (!isset($USER->preference[$name])) {
155 return $default; // Default value (or NULL)
156 }
157 return $USER->preference[$name]; // The single value
158}
159
160
9fa49e22 161/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 162
3db75c62 163function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99) {
9fa49e22 164/// Given date parts in user time, produce a GMT timestamp
39917a09 165
f30fe8d0 166 $timezone = get_user_timezone($timezone);
94e34118 167
168 if (abs($timezone) > 13) {
03c17ddf 169 return mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
170 } else {
171 $time = gmmktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
172 return usertime($time, $timezone); // This is GMT
173 }
39917a09 174}
175
8dbed6be 176function format_time($totalsecs, $str=NULL) {
9fa49e22 177/// Given an amount of time in seconds, returns string
178/// formatted nicely as months, days, hours etc as needed
c7e3ac2a 179
6b174680 180 $totalsecs = abs($totalsecs);
c7e3ac2a 181
8dbed6be 182 if (!$str) { // Create the str structure the slow way
183 $str->day = get_string("day");
184 $str->days = get_string("days");
185 $str->hour = get_string("hour");
186 $str->hours = get_string("hours");
187 $str->min = get_string("min");
188 $str->mins = get_string("mins");
189 $str->sec = get_string("sec");
190 $str->secs = get_string("secs");
191 }
192
193 $days = floor($totalsecs/86400);
6b174680 194 $remainder = $totalsecs - ($days*86400);
8dbed6be 195 $hours = floor($remainder/3600);
6b174680 196 $remainder = $remainder - ($hours*3600);
8dbed6be 197 $mins = floor($remainder/60);
198 $secs = $remainder - ($mins*60);
199
200 $ss = ($secs == 1) ? $str->sec : $str->secs;
201 $sm = ($mins == 1) ? $str->min : $str->mins;
202 $sh = ($hours == 1) ? $str->hour : $str->hours;
203 $sd = ($days == 1) ? $str->day : $str->days;
204
9c9f7d77 205 $odays = "";
206 $ohours = "";
207 $omins = "";
208 $osecs = "";
209
8dbed6be 210 if ($days) $odays = "$days $sd";
211 if ($hours) $ohours = "$hours $sh";
212 if ($mins) $omins = "$mins $sm";
213 if ($secs) $osecs = "$secs $ss";
6b174680 214
215 if ($days) return "$odays $ohours";
216 if ($hours) return "$ohours $omins";
217 if ($mins) return "$omins $osecs";
218 if ($secs) return "$osecs";
219 return get_string("now");
220}
f9903ed0 221
61ae5d36 222function userdate($date, $format="", $timezone=99, $fixday = true) {
9fa49e22 223/// Returns a formatted string that represents a date in user time
224/// WARNING: note that the format is for strftime(), not date().
d8ba183c 225/// Because of a bug in most Windows time libraries, we can't use
9fa49e22 226/// the nicer %e, so we have to use %d which has leading zeroes.
d8ba183c 227/// A lot of the fuss below is just getting rid of these leading
9fa49e22 228/// zeroes as efficiently as possible.
61ae5d36 229///
d8ba183c 230/// If parammeter fixday = true (default), then take off leading
61ae5d36 231/// zero from %d, else mantain it.
7a302afc 232
5fa51a39 233 if ($format == "") {
dcde9f02 234 $format = get_string("strftimedaydatetime");
5fa51a39 235 }
035cdbff 236
dcde9f02 237 $formatnoday = str_replace("%d", "DD", $format);
61ae5d36 238 if ($fixday) {
239 $fixday = ($formatnoday != $format);
240 }
dcde9f02 241
f30fe8d0 242 $timezone = get_user_timezone($timezone);
90207a06 243
0431bd7c 244 if (abs($timezone) > 13) {
035cdbff 245 if ($fixday) {
246 $datestring = strftime($formatnoday, $date);
247 $daystring = str_replace(" 0", "", strftime(" %d", $date));
248 $datestring = str_replace("DD", $daystring, $datestring);
249 } else {
250 $datestring = strftime($format, $date);
251 }
bea7a51e 252 } else {
70d4cf82 253 $date = $date + (int)($timezone * 3600);
035cdbff 254 if ($fixday) {
70d4cf82 255 $datestring = gmstrftime($formatnoday, $date);
9fa49e22 256 $daystring = str_replace(" 0", "", gmstrftime(" %d", $date));
035cdbff 257 $datestring = str_replace("DD", $daystring, $datestring);
258 } else {
70d4cf82 259 $datestring = gmstrftime($format, $date);
035cdbff 260 }
873960de 261 }
bea7a51e 262
035cdbff 263 return $datestring;
873960de 264}
265
5fa51a39 266function usergetdate($date, $timezone=99) {
d8ba183c 267/// Given a $date timestamp in GMT, returns an array
9fa49e22 268/// that represents the date in user time
6b174680 269
f30fe8d0 270 $timezone = get_user_timezone($timezone);
a36166d3 271
0431bd7c 272 if (abs($timezone) > 13) {
873960de 273 return getdate($date);
274 }
d2d6171f 275 //There is no gmgetdate so I have to fake it...
276 $date = $date + (int)($timezone * 3600);
277 $getdate["seconds"] = gmstrftime("%S", $date);
278 $getdate["minutes"] = gmstrftime("%M", $date);
279 $getdate["hours"] = gmstrftime("%H", $date);
280 $getdate["mday"] = gmstrftime("%d", $date);
281 $getdate["wday"] = gmstrftime("%u", $date);
282 $getdate["mon"] = gmstrftime("%m", $date);
283 $getdate["year"] = gmstrftime("%Y", $date);
284 $getdate["yday"] = gmstrftime("%j", $date);
285 $getdate["weekday"] = gmstrftime("%A", $date);
286 $getdate["month"] = gmstrftime("%B", $date);
287 return $getdate;
d552ead0 288}
289
290function usertime($date, $timezone=99) {
d8ba183c 291/// Given a GMT timestamp (seconds since epoch), offsets it by
9fa49e22 292/// the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
a36166d3 293
f30fe8d0 294 $timezone = get_user_timezone($timezone);
0431bd7c 295 if (abs($timezone) > 13) {
d552ead0 296 return $date;
297 }
298 return $date - (int)($timezone * 3600);
299}
300
edf7fe8c 301function usergetmidnight($date, $timezone=99) {
9fa49e22 302/// Given a time, return the GMT timestamp of the most recent midnight
303/// for the current user.
edf7fe8c 304
f30fe8d0 305 $timezone = get_user_timezone($timezone);
edf7fe8c 306 $userdate = usergetdate($date, $timezone);
4606d9bb 307
0431bd7c 308 if (abs($timezone) > 13) {
4606d9bb 309 return mktime(0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
310 }
311
edf7fe8c 312 $timemidnight = gmmktime (0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
313 return usertime($timemidnight, $timezone); // Time of midnight of this user's day, in GMT
314
315}
316
d552ead0 317function usertimezone($timezone=99) {
9fa49e22 318/// Returns a string that prints the user's timezone
d552ead0 319
f30fe8d0 320 $timezone = get_user_timezone($timezone);
321
0431bd7c 322 if (abs($timezone) > 13) {
d552ead0 323 return "server time";
324 }
325 if (abs($timezone) < 0.5) {
326 return "GMT";
327 }
328 if ($timezone > 0) {
329 return "GMT+$timezone";
330 } else {
331 return "GMT$timezone";
332 }
f9903ed0 333}
334
f30fe8d0 335function get_user_timezone($tz = 99) {
336// Returns a float which represents the user's timezone difference from GMT in hours
337// Checks various settings and picks the most dominant of those which have a value
338
339 // Variables declared explicitly global here so that if we add
340 // something later we won't forget to global it...
341 $timezones = array(
342 isset($GLOBALS['USER']->timezone) ? $GLOBALS['USER']->timezone : 99,
343 isset($GLOBALS['CFG']->timezone) ? $GLOBALS['CFG']->timezone : 99,
344 );
345 while($tz == 99 && $next = each($timezones)) {
346 $tz = (float)$next['value'];
347 }
348
349 return $tz;
350}
f9903ed0 351
9fa49e22 352/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 353
da5c172a 354function require_login($courseid=0) {
9fa49e22 355/// This function checks that the current user is logged in, and optionally
356/// whether they are "logged in" or allowed to be in a particular course.
357/// If not, then it redirects them to the site login or course enrolment.
f9903ed0 358
73047f2f 359 global $CFG, $SESSION, $USER, $FULLME, $MoodleSession;
d8ba183c 360
da5c172a 361 // First check that the user is logged in to the site.
c21c671d 362 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
f9903ed0 363 $SESSION->wantsurl = $FULLME;
9f44d972 364 if (!empty($_SERVER["HTTP_REFERER"])) {
365 $SESSION->fromurl = $_SERVER["HTTP_REFERER"];
366 }
c21c671d 367 $USER = NULL;
73047f2f 368 redirect("$CFG->wwwroot/login/index.php");
f9903ed0 369 die;
f9903ed0 370 }
808a3baa 371
372 // Check that the user account is properly set up
373 if (user_not_fully_set_up($USER)) {
374 $site = get_site();
375 redirect("$CFG->wwwroot/user/edit.php?id=$USER->id&course=$site->id");
376 die;
377 }
d8ba183c 378
da5c172a 379 // Next, check if the user can be in a particular course
380 if ($courseid) {
9c9f7d77 381 if (!empty($USER->student[$courseid]) or !empty($USER->teacher[$courseid]) or !empty($USER->admin)) {
cb909d74 382 if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
383 if (!isteacher($courseid, $USER->realuser)) {
384 print_header();
319b4729 385 notice(get_string("studentnotallowed", "", fullname($USER, true)), "$CFG->wwwroot/");
cb909d74 386 }
387
388 } else { // just update their last login time
3ce2f1e0 389 update_user_in_db();
390 }
da5c172a 391 return; // user is a member of this course.
392 }
393 if (! $course = get_record("course", "id", $courseid)) {
394 error("That course doesn't exist");
395 }
1efa27fd 396 if (!$course->visible) {
397 print_header();
319b4729 398 notice(get_string("studentnotallowed", "", fullname($USER, true)), "$CFG->wwwroot/");
1efa27fd 399 }
7363ff91 400 if ($USER->username == "guest") {
401 switch ($course->guest) {
402 case 0: // Guests not allowed
403 print_header();
404 notice(get_string("guestsnotallowed", "", $course->fullname));
405 break;
406 case 1: // Guests allowed
407 update_user_in_db();
408 return;
409 case 2: // Guests allowed with key (drop through)
410 break;
411 }
da5c172a 412 }
f9903ed0 413
7363ff91 414 // Currently not enrolled in the course, so see if they want to enrol
da5c172a 415 $SESSION->wantsurl = $FULLME;
416 redirect("$CFG->wwwroot/course/enrol.php?id=$courseid");
417 die;
418 }
f9903ed0 419}
420
1d881d92 421function update_user_login_times() {
422 global $USER;
423
424 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
425 $USER->currentlogin = $user->currentlogin = time();
1d881d92 426
427 $user->id = $USER->id;
428
429 return update_record("user", $user);
430}
431
808a3baa 432function user_not_fully_set_up($user) {
ac5d88eb 433 return ($user->username != "guest" and (empty($user->firstname) or empty($user->lastname) or empty($user->email)));
808a3baa 434}
f9903ed0 435
f9903ed0 436function update_login_count() {
9fa49e22 437/// Keeps track of login attempts
438
f9903ed0 439 global $SESSION;
440
441 $max_logins = 10;
442
443 if (empty($SESSION->logincount)) {
444 $SESSION->logincount = 1;
445 } else {
446 $SESSION->logincount++;
447 }
448
449 if ($SESSION->logincount > $max_logins) {
9fa49e22 450 unset($SESSION->wantsurl);
1d881d92 451 error(get_string("errortoomanylogins"));
d578afc8 452 }
453}
454
9fa49e22 455function reset_login_count() {
456/// Resets login attempts
457 global $SESSION;
d578afc8 458
9fa49e22 459 $SESSION->logincount = 0;
d578afc8 460}
461
cb98d312 462function check_for_restricted_user($username=NULL, $redirect="") {
463 global $CFG, $USER;
464
465 if (!$username) {
466 if (!empty($USER->username)) {
467 $username = $USER->username;
468 } else {
469 return false;
470 }
471 }
472
473 if (!empty($CFG->restrictusers)) {
474 $names = explode(',', $CFG->restrictusers);
475 if (in_array($username, $names)) {
9b591be6 476 error(get_string("restricteduser", "error", fullname($USER)), $redirect);
cb98d312 477 }
478 }
479}
480
581d7b49 481function isadmin($userid=0) {
9fa49e22 482/// Is the user an admin?
f9903ed0 483 global $USER;
aa095969 484 static $admins = array();
485 static $nonadmins = array();
f9903ed0 486
581d7b49 487 if (!$userid){
488 if (empty($USER->id)) {
489 return false;
490 }
491 $userid = $USER->id;
9bd2c874 492 }
493
581d7b49 494 if (in_array($userid, $admins)) {
aa095969 495 return true;
581d7b49 496 } else if (in_array($userid, $nonadmins)) {
aa095969 497 return false;
581d7b49 498 } else if (record_exists("user_admins", "userid", $userid)){
499 $admins[] = $userid;
aa095969 500 return true;
501 } else {
581d7b49 502 $nonadmins[] = $userid;
aa095969 503 return false;
f9903ed0 504 }
f9903ed0 505}
506
9788367b 507function isteacher($courseid, $userid=0, $includeadmin=true) {
9fa49e22 508/// Is the user a teacher or admin?
f9903ed0 509 global $USER;
510
9788367b 511 if ($includeadmin and isadmin($userid)) { // admins can do anything the teacher can
d115a57f 512 return true;
513 }
514
f9903ed0 515 if (!$userid) {
9bd2c874 516 return !empty($USER->teacher[$courseid]);
f9903ed0 517 }
518
ebc3bd2b 519 return record_exists("user_teachers", "userid", $userid, "course", $courseid);
f9903ed0 520}
521
73047f2f 522function isteacheredit($courseid, $userid=0) {
523/// Is the user allowed to edit this course?
524 global $USER;
525
d8ba183c 526 if (isadmin($userid)) { // admins can do anything
73047f2f 527 return true;
528 }
529
530 if (!$userid) {
531 return !empty($USER->teacheredit[$courseid]);
532 }
533
534 return get_field("user_teachers", "editall", "userid", $userid, "course", $courseid);
535}
536
1924074c 537function iscreator ($userid=0) {
538/// Can user create new courses?
539 global $USER;
8a205861 540 if (empty($USER->id)) {
541 return false;
542 }
1924074c 543 if (isadmin($userid)) { // admins can do anything
544 return true;
545 }
8a205861 546 if (empty($userid)) {
1924074c 547 return record_exists("user_coursecreators", "userid", $USER->id);
548 }
549
550 return record_exists("user_coursecreators", "userid", $userid);
551}
552
8a9e3fd7 553function isstudent($courseid, $userid=0) {
9fa49e22 554/// Is the user a student in this course?
f9903ed0 555 global $USER;
556
557 if (!$userid) {
346b1a24 558 return !empty($USER->student[$courseid]);
f9903ed0 559 }
560
ebc3bd2b 561 // $timenow = time(); // todo: add time check below
f9903ed0 562
ebc3bd2b 563 return record_exists("user_students", "userid", $userid, "course", $courseid);
f9903ed0 564}
565
da5c172a 566function isguest($userid=0) {
9fa49e22 567/// Is the user a guest?
da5c172a 568 global $USER;
569
570 if (!$userid) {
b35e8568 571 if (empty($USER->username)) {
572 return false;
573 }
da5c172a 574 return ($USER->username == "guest");
575 }
576
9fa49e22 577 return record_exists("user", "id", $userid, "username", "guest");
da5c172a 578}
579
9fa49e22 580
2c309dc2 581function isediting($courseid, $user=NULL) {
9fa49e22 582/// Is the current user in editing mode?
2c309dc2 583 global $USER;
584 if (!$user){
585 $user = $USER;
586 }
9c9f7d77 587 if (empty($user->editing)) {
588 return false;
589 }
2c309dc2 590 return ($user->editing and isteacher($courseid, $user->id));
591}
592
7977cffd 593function ismoving($courseid) {
594/// Is the current user currently moving an activity?
595 global $USER;
596
597 if (!empty($USER->activitycopy)) {
598 return ($USER->activitycopycourse == $courseid);
599 }
600 return false;
601}
602
e2cd5065 603function fullname($user, $override=false) {
b5cbb64d 604/// Given an object containing firstname and lastname
d8ba183c 605/// values, this function returns a string with the
b5cbb64d 606/// full name of the person.
e2cd5065 607/// The result may depend on system settings
b5cbb64d 608/// or language. 'override' will force both names
e2cd5065 609/// to be used even if system settings specify one.
b5cbb64d 610
f374fb10 611 global $CFG, $SESSION;
612
613 if (!empty($SESSION->fullnamedisplay)) {
614 $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
615 }
e2cd5065 616
b5cbb64d 617 if ($CFG->fullnamedisplay == 'firstname lastname') {
618 return "$user->firstname $user->lastname";
619
620 } else if ($CFG->fullnamedisplay == 'lastname firstname') {
621 return "$user->lastname $user->firstname";
e2cd5065 622
b5cbb64d 623 } else if ($CFG->fullnamedisplay == 'firstname') {
624 if ($override) {
625 return get_string('fullnamedisplay', '', $user);
626 } else {
627 return $user->firstname;
628 }
629 }
e2cd5065 630
b5cbb64d 631 return get_string('fullnamedisplay', '', $user);
e2cd5065 632}
633
f9903ed0 634
635function set_moodle_cookie($thing) {
9fa49e22 636/// Sets a moodle cookie with an encrypted string
7185e073 637 global $CFG;
482b6e6e 638
639 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
f9903ed0 640
641 $days = 60;
642 $seconds = 60*60*24*$days;
643
7185e073 644 setCookie($cookiename, "", time() - 3600, "/");
645 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, "/");
f9903ed0 646}
647
648
649function get_moodle_cookie() {
9fa49e22 650/// Gets a moodle cookie with an encrypted string
7185e073 651 global $CFG;
652
482b6e6e 653 $cookiename = 'MOODLEID_'.$CFG->sessioncookie;
7185e073 654
1079c8a8 655 if (empty($_COOKIE[$cookiename])) {
656 return "";
657 } else {
658 return rc4decrypt($_COOKIE[$cookiename]);
659 }
f9903ed0 660}
661
ba7166c3 662function is_internal_auth() {
663/// Returns true if an internal authentication method is being used.
664
665 global $CFG;
666
667 return ($CFG->auth == "email" || $CFG->auth == "none" || $CFG->auth == "manual");
668}
f9903ed0 669
faebaf0f 670function create_user_record($username, $password) {
d8ba183c 671/// Creates a bare-bones user record
e858f9da 672 global $REMOTE_ADDR, $CFG;
1e22bc9c 673 //just in case check text case
674 $username = trim(moodle_strtolower($username));
6ae24de0 675 if (function_exists(auth_get_userinfo)) {
e858f9da 676 if ($newinfo = auth_get_userinfo($username)) {
34daec9b 677 foreach ($newinfo as $key => $value){
9f44d972 678 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 679 }
680 }
681 }
f9903ed0 682
faebaf0f 683 $newuser->username = $username;
684 $newuser->password = md5($password);
a0bac19d 685 $newuser->lang = $CFG->lang;
faebaf0f 686 $newuser->confirmed = 1;
687 $newuser->lastIP = $REMOTE_ADDR;
688 $newuser->timemodified = time();
f9903ed0 689
faebaf0f 690 if (insert_record("user", $newuser)) {
691 return get_user_info_from_db("username", $username);
692 }
693 return false;
694}
695
0609562b 696
697function guest_user() {
698 global $CFG;
699
700 if ($newuser = get_record("user", "username", "guest")) {
701 $newuser->loggedin = true;
702 $newuser->confirmed = 1;
703 $newuser->site = $CFG->wwwroot;
704 $newuser->lang = $CFG->lang;
705 }
706
707 return $newuser;
708}
709
faebaf0f 710function authenticate_user_login($username, $password) {
d8ba183c 711/// Given a username and password, this function looks them
9fa49e22 712/// up using the currently selected authentication mechanism,
d8ba183c 713/// and if the authentication is successful, it returns a
9fa49e22 714/// valid $user object from the 'user' table.
715///
716/// Uses auth_ functions from the currently active auth module
faebaf0f 717
718 global $CFG;
719
466558e3 720 $md5password = md5($password);
721
14217044 722 if (empty($CFG->auth)) {
faebaf0f 723 $CFG->auth = "email"; // Default authentication module
724 }
725
466558e3 726 if ($username == "guest") {
727 $CFG->auth = "none"; // Guest account always internal
728 }
729
730 // If this is the admin, then just use internal methods
d8ba183c 731 // Doing this first (even though it's less efficient) because
732 // the chosen authentication method might hang and lock the
92710226 733 // admin out.
9fa49e22 734 if (adminlogin($username, $md5password)) {
466558e3 735 return get_user_info_from_db("username", $username);
736 }
737
92710226 738 // OK, the user is a normal user, so try and authenticate them
e858f9da 739 require_once("$CFG->dirroot/auth/$CFG->auth/lib.php");
faebaf0f 740
741 if (auth_user_login($username, $password)) { // Successful authentication
faebaf0f 742 if ($user = get_user_info_from_db("username", $username)) {
92710226 743 if ($md5password <> $user->password) { // Update local copy of password for reference
466558e3 744 set_field("user", "password", $md5password, "username", $username);
faebaf0f 745 }
faebaf0f 746 } else {
e582b65e 747 $user = create_user_record($username, $password);
faebaf0f 748 }
89b54325 749
e582b65e 750 if (function_exists('auth_iscreator')) { // Check if the user is a creator
751 if (auth_iscreator($username)) {
752 if (! record_exists("user_coursecreators", "userid", $user->id)) {
753 $cdata['userid']=$user->id;
754 $creator = insert_record("user_coursecreators",$cdata);
755 if (! $creator) {
756 error("Cannot add user to course creators.");
757 }
758 }
759 } else {
760 if ( record_exists("user_coursecreators", "userid", $user->id)) {
f5cdd4d1 761 $creator = delete_records("user_coursecreators", "userid", $user->id);
e582b65e 762 if (! $creator) {
763 error("Cannot remove user from course creators.");
764 }
765 }
766 }
767 }
d8ba183c 768
e582b65e 769 return $user;
770 } else {
771 return false;
772 }
f9903ed0 773}
774
4d312bbe 775function enrol_student($userid, $courseid) {
9fa49e22 776/// Enrols a student in a given course
f9903ed0 777
4d312bbe 778 if (!record_exists("user_students", "userid", $userid, "course", $courseid)) {
3041b0f8 779 if (record_exists("user", "id", $userid)) {
780 $student->userid = $userid;
781 $student->course = $courseid;
782 $student->start = 0;
783 $student->end = 0;
784 $student->time = time();
785 return insert_record("user_students", $student);
786 }
787 return false;
4d312bbe 788 }
789 return true;
d7facad8 790}
791
9fa62805 792function unenrol_student($userid, $courseid=0) {
9fa49e22 793/// Unenrols a student from a given course
d7facad8 794
9fa62805 795 if ($courseid) {
9fa49e22 796 /// First delete any crucial stuff that might still send mail
9fa62805 797 if ($forums = get_records("forum", "course", $courseid)) {
9fa49e22 798 foreach ($forums as $forum) {
9fa62805 799 delete_records("forum_subscriptions", "forum", $forum->id, "userid", $userid);
800 }
801 }
802 if ($groups = get_groups($courseid, $userid)) {
803 foreach ($groups as $group) {
804 delete_records("groups_members", "groupid", $group->id, "userid", $userid);
bb09fb11 805 }
f9903ed0 806 }
9fa62805 807 return delete_records("user_students", "userid", $userid, "course", $courseid);
9fa49e22 808
f9903ed0 809 } else {
9fa62805 810 delete_records("forum_subscriptions", "userid", $userid);
84bbca53 811 delete_records("groups_members", "userid", $userid);
9fa62805 812 return delete_records("user_students", "userid", $userid);
f9903ed0 813 }
814}
815
3041b0f8 816function add_teacher($userid, $courseid) {
817/// Add a teacher to a given course
818
819 if (!record_exists("user_teachers", "userid", $userid, "course", $courseid)) {
820 if (record_exists("user", "id", $userid)) {
821 $teacher->userid = $userid;
822 $teacher->course = $courseid;
823 $teacher->editall = 1;
824 $teacher->role = "";
825 if (record_exists("user_teachers", "course", $courseid)) {
826 $teacher->authority = 2;
827 } else {
828 $teacher->authority = 1;
829 }
bb8c3631 830 delete_records("user_students", "userid", $userid, "course", $courseid); // Unenrol as student
831
3041b0f8 832 return insert_record("user_teachers", $teacher);
833 }
834 return false;
835 }
836 return true;
837}
838
839function remove_teacher($userid, $courseid=0) {
9fa49e22 840/// Removes a teacher from a given course (or ALL courses)
841/// Does not delete the user account
3041b0f8 842 if ($courseid) {
9fa49e22 843 /// First delete any crucial stuff that might still send mail
3041b0f8 844 if ($forums = get_records("forum", "course", $courseid)) {
9fa49e22 845 foreach ($forums as $forum) {
3041b0f8 846 delete_records("forum_subscriptions", "forum", $forum->id, "userid", $userid);
9fa49e22 847 }
848 }
3041b0f8 849 return delete_records("user_teachers", "userid", $userid, "course", $courseid);
57507290 850 } else {
3041b0f8 851 delete_records("forum_subscriptions", "userid", $userid);
852 return delete_records("user_teachers", "userid", $userid);
57507290 853 }
f9903ed0 854}
855
3041b0f8 856
857function add_creator($userid) {
858/// Add a creator to the site
859
860 if (!record_exists("user_admins", "userid", $userid)) {
861 if (record_exists("user", "id", $userid)) {
862 $creator->userid = $userid;
863 return insert_record("user_coursecreators", $creator);
864 }
865 return false;
866 }
867 return true;
868}
869
870function remove_creator($userid) {
871/// Removes a creator from a site
872 global $db;
873
874 return delete_records("user_coursecreators", "userid", $userid);
875}
876
877function add_admin($userid) {
878/// Add an admin to the site
879
880 if (!record_exists("user_admins", "userid", $userid)) {
881 if (record_exists("user", "id", $userid)) {
882 $admin->userid = $userid;
883 return insert_record("user_admins", $admin);
884 }
885 return false;
886 }
887 return true;
888}
889
890function remove_admin($userid) {
9fa49e22 891/// Removes an admin from a site
892 global $db;
f9903ed0 893
3041b0f8 894 return delete_records("user_admins", "userid", $userid);
f9903ed0 895}
896
f9903ed0 897
07aeb7b0 898function remove_course_contents($courseid, $showfeedback=true) {
899/// Clear a course out completely, deleting all content
900/// but don't delete the course itself
901
ee23f384 902 global $CFG, $THEME, $USER, $SESSION;
07aeb7b0 903
904 $result = true;
905
906 if (! $course = get_record("course", "id", $courseid)) {
907 error("Course ID was incorrect (can't find it)");
908 }
909
910 $strdeleted = get_string("deleted");
911
912 // First delete every instance of every module
d8ba183c 913
07aeb7b0 914 if ($allmods = get_records("modules") ) {
915 foreach ($allmods as $mod) {
916 $modname = $mod->name;
917 $modfile = "$CFG->dirroot/mod/$modname/lib.php";
ca952b03 918 $moddelete = $modname."_delete_instance"; // Delete everything connected to an instance
919 $moddeletecourse = $modname."_delete_course"; // Delete other stray stuff (uncommon)
07aeb7b0 920 $count=0;
921 if (file_exists($modfile)) {
922 include_once($modfile);
923 if (function_exists($moddelete)) {
924 if ($instances = get_records($modname, "course", $course->id)) {
925 foreach ($instances as $instance) {
926 if ($moddelete($instance->id)) {
927 $count++;
928 } else {
929 notify("Could not delete $modname instance $instance->id ($instance->name)");
930 $result = false;
931 }
932 }
933 }
934 } else {
935 notify("Function $moddelete() doesn't exist!");
936 $result = false;
937 }
938
ca952b03 939 if (function_exists($moddeletecourse)) {
940 $moddeletecourse($course);
941 }
07aeb7b0 942 }
943 if ($showfeedback) {
944 notify("$strdeleted $count x $modname");
945 }
946 }
947 } else {
948 error("No modules are installed!");
949 }
950
951 // Delete any user stuff
952
953 if (delete_records("user_students", "course", $course->id)) {
954 if ($showfeedback) {
955 notify("$strdeleted user_students");
956 }
957 } else {
958 $result = false;
959 }
960
961 if (delete_records("user_teachers", "course", $course->id)) {
962 if ($showfeedback) {
963 notify("$strdeleted user_teachers");
964 }
965 } else {
966 $result = false;
967 }
968
082e3ebc 969 // Delete any groups
970
971 if ($groups = get_records("groups", "courseid", $course->id)) {
972 foreach ($groups as $group) {
973 if (delete_records("groups_members", "groupid", $group->id)) {
974 if ($showfeedback) {
975 notify("$strdeleted groups_members");
976 }
977 } else {
978 $result = false;
979 }
980 if (delete_records("groups", "id", $group->id)) {
981 if ($showfeedback) {
982 notify("$strdeleted groups");
983 }
984 } else {
985 $result = false;
986 }
987 }
988 }
989
990 // Delete events
991
992 if (delete_records("event", "courseid", $course->id)) {
993 if ($showfeedback) {
994 notify("$strdeleted event");
995 }
996 } else {
997 $result = false;
998 }
999
07aeb7b0 1000 // Delete logs
1001
1002 if (delete_records("log", "course", $course->id)) {
1003 if ($showfeedback) {
1004 notify("$strdeleted log");
1005 }
1006 } else {
1007 $result = false;
1008 }
1009
1010 // Delete any course stuff
1011
1012 if (delete_records("course_sections", "course", $course->id)) {
1013 if ($showfeedback) {
1014 notify("$strdeleted course_sections");
1015 }
1016 } else {
1017 $result = false;
1018 }
1019
1020 if (delete_records("course_modules", "course", $course->id)) {
1021 if ($showfeedback) {
1022 notify("$strdeleted course_modules");
1023 }
1024 } else {
1025 $result = false;
1026 }
1027
1028 return $result;
1029
1030}
1031
f9903ed0 1032
f374fb10 1033/// GROUPS /////////////////////////////////////////////////////////
d8ba183c 1034
f374fb10 1035
1036/**
1037* Returns a boolean: is the user a member of the given group?
d8ba183c 1038*
dcd338ff 1039* @param type description
f374fb10 1040*/
1041function ismember($groupid, $userid=0) {
1042 global $USER;
1043
8a2c9076 1044 if (!$groupid) { // No point doing further checks
1045 return false;
1046 }
1047
f374fb10 1048 if (!$userid) {
0d67c514 1049 if (empty($USER->groupmember)) {
1050 return false;
1051 }
1052 foreach ($USER->groupmember as $courseid => $mgroupid) {
1053 if ($mgroupid == $groupid) {
1054 return true;
1055 }
1056 }
1057 return false;
f374fb10 1058 }
1059
0da33e07 1060 return record_exists("groups_members", "groupid", $groupid, "userid", $userid);
f374fb10 1061}
1062
0d67c514 1063/**
1064* Returns the group ID of the current user in the given course
d8ba183c 1065*
dcd338ff 1066* @param type description
0d67c514 1067*/
1068function mygroupid($courseid) {
1069 global $USER;
1070
1071 if (empty($USER->groupmember[$courseid])) {
1072 return 0;
1073 } else {
1074 return $USER->groupmember[$courseid];
1075 }
1076}
1077
f374fb10 1078/**
d8ba183c 1079* For a given course, and possibly course module, determine
f374fb10 1080* what the current default groupmode is:
1081* NOGROUPS, SEPARATEGROUPS or VISIBLEGROUPS
d8ba183c 1082*
dcd338ff 1083* @param type description
f374fb10 1084*/
1085function groupmode($course, $cm=null) {
1086
1087 if ($cm and !$course->groupmodeforce) {
1088 return $cm->groupmode;
1089 }
1090 return $course->groupmode;
1091}
1092
1093
1094/**
1095* Sets the current group in the session variable
d8ba183c 1096*
dcd338ff 1097* @param type description
f374fb10 1098*/
1099function set_current_group($courseid, $groupid) {
1100 global $SESSION;
1101
1102 return $SESSION->currentgroup[$courseid] = $groupid;
1103}
1104
1105
1106/**
1107* Gets the current group for the current user as an id or an object
d8ba183c 1108*
dcd338ff 1109* @param type description
f374fb10 1110*/
1111function get_current_group($courseid, $full=false) {
1112 global $SESSION, $USER;
1113
1114 if (empty($SESSION->currentgroup[$courseid])) {
1115 if (empty($USER->groupmember[$courseid])) {
8a2c9076 1116 return 0;
f374fb10 1117 } else {
1118 $SESSION->currentgroup[$courseid] = $USER->groupmember[$courseid];
1119 }
1120 }
1121
1122 if ($full) {
0da33e07 1123 return get_record('groups', 'id', $SESSION->currentgroup[$courseid]);
f374fb10 1124 } else {
1125 return $SESSION->currentgroup[$courseid];
1126 }
1127}
1128
0d67c514 1129/**
1130* A combination function to make it easier for modules
1131* to set up groups.
1132*
1133* It will use a given "groupid" parameter and try to use
1134* that to reset the current group for the user.
1135*
dcd338ff 1136* @param type description
0d67c514 1137*/
eb6147a8 1138function get_and_set_current_group($course, $groupmode, $groupid=-1) {
0d67c514 1139
1140 if (!$groupmode) { // Groups don't even apply
d8ba183c 1141 return false;
0d67c514 1142 }
1143
1144 $currentgroupid = get_current_group($course->id);
1145
eb6147a8 1146 if ($groupid < 0) { // No change was specified
1147 return $currentgroupid;
1148 }
1149
1150 if ($groupid) { // Try to change the current group to this groupid
0d67c514 1151 if ($group = get_record('groups', 'id', $groupid, 'courseid', $course->id)) { // Exists
1152 if (isteacheredit($course->id)) { // Sets current default group
1153 $currentgroupid = set_current_group($course->id, $group->id);
1154
1155 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
1156 $currentgroupid = $group->id;
1157 }
1158 }
eb6147a8 1159 } else { // When groupid = 0 it means show ALL groups
1160 if (isteacheredit($course->id)) { // Sets current default group
1161 $currentgroupid = set_current_group($course->id, 0);
1162
1163 } else if ($groupmode == VISIBLEGROUPS) { // All groups are visible
1164 $currentgroupid = 0;
1165 }
0d67c514 1166 }
1167
1168 return $currentgroupid;
1169}
1170
1171
c3cbfe7f 1172/**
1173* A big combination function to make it easier for modules
1174* to set up groups.
1175*
1176* Terminates if the current user shouldn't be looking at this group
1177* Otherwise returns the current group if there is one
1178* Otherwise returns false if groups aren't relevant
1179*
dcd338ff 1180* @param type description
c3cbfe7f 1181*/
1182function setup_and_print_groups($course, $groupmode, $urlroot) {
1183
eb6147a8 1184 if (isset($_GET['group'])) {
1185 $changegroup = $_GET['group']; /// 0 or higher
1186 } else {
1187 $changegroup = -1; /// This means no group change was specified
1188 }
1189
1190 $currentgroup = get_and_set_current_group($course, $groupmode, $changegroup);
c3cbfe7f 1191
eb6147a8 1192 if ($currentgroup === false) {
c3cbfe7f 1193 return false;
1194 }
1195
4b6d8dd5 1196 if ($groupmode == SEPARATEGROUPS and !isteacheredit($course->id) and !$currentgroup) {
1197 print_heading(get_string('notingroup'));
c3cbfe7f 1198 print_footer($course);
1199 exit;
1200 }
1201
1202 if ($groupmode == VISIBLEGROUPS or ($groupmode and isteacheredit($course->id))) {
1203 if ($groups = get_records_menu("groups", "courseid", $course->id, "name ASC", "id,name")) {
eb6147a8 1204 echo '<div align="center">';
c3cbfe7f 1205 print_group_menu($groups, $groupmode, $currentgroup, $urlroot);
eb6147a8 1206 echo '</div>';
c3cbfe7f 1207 }
1208 }
1209
1210 return $currentgroup;
1211}
0d67c514 1212
f374fb10 1213
1214
f9903ed0 1215/// CORRESPONDENCE ////////////////////////////////////////////////
1216
5fa51a39 1217function email_to_user($user, $from, $subject, $messagetext, $messagehtml="", $attachment="", $attachname="") {
9fa49e22 1218/// user - a user record as an object
1219/// from - a user record as an object
1220/// subject - plain text subject line of the email
1221/// messagetext - plain text version of the message
1222/// messagehtml - complete html version of the message (optional)
1223/// attachment - a file on the filesystem, relative to $CFG->dataroot
1224/// attachname - the name of the file (extension indicates MIME)
f9903ed0 1225
4216daa6 1226 global $CFG, $_SERVER;
f9903ed0 1227
0cc6fa6a 1228 global $course; // This is a bit of an ugly hack to be gotten rid of later
1229 if (!empty($course->lang)) { // Course language is defined
1230 $CFG->courselang = $course->lang;
1231 }
1232
136dabd8 1233 include_once("$CFG->libdir/phpmailer/class.phpmailer.php");
f9903ed0 1234
cadb96f2 1235 if (empty($user)) {
1236 return false;
1237 }
1238
1239 if (!empty($user->emailstop)) {
f9903ed0 1240 return false;
1241 }
d8ba183c 1242
f9903ed0 1243 $mail = new phpmailer;
1244
d8ba183c 1245 $mail->Version = "Moodle $CFG->version"; // mailer version
136dabd8 1246 $mail->PluginDir = "$CFG->libdir/phpmailer/"; // plugin directory (eg smtp plugin)
562bbe90 1247
98c4eae3 1248
d483bcd3 1249 if (current_language() != "en") {
1250 $mail->CharSet = get_string("thischarset");
98c4eae3 1251 }
1252
62740736 1253 if ($CFG->smtphosts == "qmail") {
1254 $mail->IsQmail(); // use Qmail system
1255
1256 } else if (empty($CFG->smtphosts)) {
1257 $mail->IsMail(); // use PHP mail() = sendmail
1258
1259 } else {
1e411ffc 1260 $mail->IsSMTP(); // use SMTP directly
57ef3480 1261 if ($CFG->debug > 7) {
1262 echo "<pre>\n";
1263 $mail->SMTPDebug = true;
1264 }
1e411ffc 1265 $mail->Host = "$CFG->smtphosts"; // specify main and backup servers
9f58537a 1266
1267 if ($CFG->smtpuser) { // Use SMTP authentication
1268 $mail->SMTPAuth = true;
1269 $mail->Username = $CFG->smtpuser;
1270 $mail->Password = $CFG->smtppass;
1271 }
7f86ce17 1272 }
f9903ed0 1273
2b97bd71 1274 $adminuser = get_admin();
1275
1276 $mail->Sender = "$adminuser->email";
1277
136dabd8 1278 $mail->From = "$from->email";
0b4c5822 1279 $mail->FromName = fullname($from);
136dabd8 1280 $mail->Subject = stripslashes($subject);
f9903ed0 1281
d8ba183c 1282 $mail->AddAddress("$user->email", fullname($user) );
f9903ed0 1283
58d24720 1284 $mail->WordWrap = 79; // set word wrap
f9903ed0 1285
b68dca19 1286 if (!empty($from->precedence)) {
1287 $mail->Precedence = $from->precedence; // set precedence level eg "bulk" "list" or "junk"
1288 }
1289
136dabd8 1290 if ($messagehtml) {
1291 $mail->IsHTML(true);
125898af 1292 $mail->Encoding = "quoted-printable"; // Encoding to use
136dabd8 1293 $mail->Body = $messagehtml;
78681899 1294 $mail->AltBody = "\n$messagetext\n";
136dabd8 1295 } else {
1296 $mail->IsHTML(false);
78681899 1297 $mail->Body = "\n$messagetext\n";
f9903ed0 1298 }
1299
136dabd8 1300 if ($attachment && $attachname) {
1301 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
0b4c5822 1302 $mail->AddAddress("$adminuser->email", fullname($adminuser) );
4216daa6 1303 $mail->AddStringAttachment("Error in attachment. User attempted to attach a filename with a unsafe name.", "error.txt", "8bit", "text/plain");
136dabd8 1304 } else {
1305 include_once("$CFG->dirroot/files/mimetypes.php");
1306 $mimetype = mimeinfo("type", $attachname);
1307 $mail->AddAttachment("$CFG->dataroot/$attachment", "$attachname", "base64", "$mimetype");
1308 }
f9903ed0 1309 }
1310
136dabd8 1311 if ($mail->Send()) {
1312 return true;
1313 } else {
4216daa6 1314 echo "ERROR: $mail->ErrorInfo\n";
1315 $site = get_site();
1316 add_to_log($site->id, "library", "mailer", $_SERVER["REQUEST_URI"], "ERROR: $mail->ErrorInfo");
f9903ed0 1317 return false;
1318 }
f9903ed0 1319}
1320
1d881d92 1321function reset_password_and_mail($user) {
1322
1323 global $CFG;
1324
1325 $site = get_site();
1326 $from = get_admin();
1327
1328 $newpassword = generate_password();
1329
1330 if (! set_field("user", "password", md5($newpassword), "id", $user->id) ) {
1331 error("Could not set user password!");
1332 }
1333
1334 $a->firstname = $user->firstname;
1335 $a->sitename = $site->fullname;
1336 $a->username = $user->username;
1337 $a->newpassword = $newpassword;
1338 $a->link = "$CFG->wwwroot/login/change_password.php";
0b4c5822 1339 $a->signoff = fullname($from, true)." ($from->email)";
1d881d92 1340
1341 $message = get_string("newpasswordtext", "", $a);
1342
1343 $subject = "$site->fullname: ".get_string("changedpassword");
1344
1345 return email_to_user($user, $from, $subject, $message);
1346
1347}
1348
1349function send_confirmation_email($user) {
1350
1351 global $CFG;
1352
1353 $site = get_site();
1354 $from = get_admin();
1355
1356 $data->firstname = $user->firstname;
1357 $data->sitename = $site->fullname;
1358 $data->link = "$CFG->wwwroot/login/confirm.php?p=$user->secret&s=$user->username";
0b4c5822 1359 $data->admin = fullname($from)." ($from->email)";
1d881d92 1360
1361 $message = get_string("emailconfirmation", "", $data);
eb347b6b 1362 $subject = get_string("emailconfirmationsubject", "", $site->fullname);
1d881d92 1363
58d24720 1364 $messagehtml = text_to_html($message, false, false, true);
1365
1366 return email_to_user($user, $from, $subject, $message, $messagehtml);
1d881d92 1367
1368}
1369
eb347b6b 1370function send_password_change_confirmation_email($user) {
1371
1372 global $CFG;
1373
1374 $site = get_site();
1375 $from = get_admin();
1376
1377 $data->firstname = $user->firstname;
1378 $data->sitename = $site->fullname;
1379 $data->link = "$CFG->wwwroot/login/forgot_password.php?p=$user->secret&s=$user->username";
0b4c5822 1380 $data->admin = fullname($from)." ($from->email)";
eb347b6b 1381
1382 $message = get_string("emailpasswordconfirmation", "", $data);
1383 $subject = get_string("emailpasswordconfirmationsubject", "", $site->fullname);
1384
1385 return email_to_user($user, $from, $subject, $message);
1386
1387}
1388
1389
1d881d92 1390
136dabd8 1391
f9903ed0 1392/// FILE HANDLING /////////////////////////////////////////////
1393
1e03c552 1394
6b174680 1395function make_upload_directory($directory) {
9fa49e22 1396/// $directory = a string of directory names under $CFG->dataroot
1397/// eg stuff/assignment/1
1398/// Returns full directory if successful, false if not
6b174680 1399
1400 global $CFG;
1401
1402 $currdir = $CFG->dataroot;
fe287429 1403
2e6d4273 1404 umask(0000);
1405
6b174680 1406 if (!file_exists($currdir)) {
2e6d4273 1407 if (! mkdir($currdir, $CFG->directorypermissions)) {
6b174680 1408 notify("ERROR: You need to create the directory $currdir with web server write access");
1409 return false;
1410 }
1411 }
1412
1e03c552 1413 $dirarray = explode("/", $directory);
6b174680 1414
1415 foreach ($dirarray as $dir) {
1416 $currdir = "$currdir/$dir";
1417 if (! file_exists($currdir)) {
2e6d4273 1418 if (! mkdir($currdir, $CFG->directorypermissions)) {
6b174680 1419 notify("ERROR: Could not find or create a directory ($currdir)");
1420 return false;
1421 }
feffa4e6 1422 @chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
6b174680 1423 }
1424 }
1425
1426 return $currdir;
1427}
1e03c552 1428
1429
ca4f8eb8 1430function make_mod_upload_directory($courseid) {
9fa49e22 1431/// Makes an upload directory for a particular module
ca4f8eb8 1432 global $CFG;
1433
1434 if (! $moddata = make_upload_directory("$courseid/$CFG->moddata")) {
1435 return false;
1436 }
1437
1438 $strreadme = get_string("readme");
1439
1440 if (file_exists("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt")) {
1441 copy("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt", "$moddata/$strreadme.txt");
1442 } else {
1443 copy("$CFG->dirroot/lang/en/docs/module_files.txt", "$moddata/$strreadme.txt");
1444 }
1445 return $moddata;
1446}
1447
6b174680 1448
44e2d2bb 1449function valid_uploaded_file($newfile) {
9fa49e22 1450/// Returns current name of file on disk if true
9c9f7d77 1451 if (empty($newfile)) {
1452 return "";
1453 }
44e2d2bb 1454 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
1455 return $newfile['tmp_name'];
1456 } else {
1457 return "";
1458 }
1459}
1460
4909e176 1461function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0) {
9fa49e22 1462/// Returns the maximum size for uploading files
316ebf78 1463/// There are seven possible upload limits:
4909e176 1464///
1465/// 1) in Apache using LimitRequestBody (no way of checking or changing this)
1466/// 2) in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
1467/// 3) in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
316ebf78 1468/// 4) in php.ini for 'post_max_size' (can not be changed inside PHP)
1469/// 5) by the Moodle admin in $CFG->maxbytes
1470/// 6) by the teacher in the current course $course->maxbytes
1471/// 7) by the teacher for the current module, eg $assignment->maxbytes
4909e176 1472///
1473/// These last two are passed to this function as arguments (in bytes).
1474/// Anything defined as 0 is ignored.
1475/// The smallest of all the non-zero numbers is returned.
1476
44e2d2bb 1477 if (! $filesize = ini_get("upload_max_filesize")) {
1478 $filesize = "5M";
1479 }
4909e176 1480 $minimumsize = get_real_size($filesize);
1481
316ebf78 1482 if ($postsize = ini_get("post_max_size")) {
1483 $postsize = get_real_size($postsize);
1484 if ($postsize < $minimumsize) {
1485 $minimumsize = $postsize;
1486 }
1487 }
1488
4909e176 1489 if ($sitebytes and $sitebytes < $minimumsize) {
1490 $minimumsize = $sitebytes;
1491 }
1492
1493 if ($coursebytes and $coursebytes < $minimumsize) {
1494 $minimumsize = $coursebytes;
1495 }
1496
1497 if ($modulebytes and $modulebytes < $minimumsize) {
1498 $minimumsize = $modulebytes;
1499 }
1500
1501 return $minimumsize;
1502}
1503
1504function get_max_upload_sizes($sitebytes=0, $coursebytes=0, $modulebytes=0) {
d8ba183c 1505/// Related to the above function - this function returns an
1506/// array of possible sizes in an array, translated to the
4909e176 1507/// local language.
1508
1509 if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
1510 return array();
1511 }
1512
1513 $filesize[$maxsize] = display_size($maxsize);
1514
d8ba183c 1515 $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
4909e176 1516 5242880, 10485760, 20971520, 52428800, 104857600);
1517
1518 foreach ($sizelist as $sizebytes) {
1519 if ($sizebytes < $maxsize) {
1520 $filesize[$sizebytes] = display_size($sizebytes);
1521 }
1522 }
1523
1524 krsort($filesize, SORT_NUMERIC);
1525
1526 return $filesize;
44e2d2bb 1527}
1528
55fd8177 1529function get_directory_list($rootdir, $excludefile="", $descend=true, $justdirs=false) {
d8ba183c 1530/// Returns an array with all the filenames in
9fa49e22 1531/// all subdirectories, relative to the given rootdir.
1532/// If excludefile is defined, then that file/directory is ignored
55fd8177 1533/// If justdirs is defined, then only subdirectories are listed, otherwise just files
f9903ed0 1534
1535 $dirs = array();
f9903ed0 1536
12407705 1537 if (!is_dir($rootdir)) {
1538 return $dirs;
1539 }
1540
487c1711 1541 if (!$dir = opendir($rootdir)) {
d897cae4 1542 return $dirs;
1543 }
1544
81fcd0f0 1545 while (false !== ($file = readdir($dir))) {
b35e8568 1546 $firstchar = substr($file, 0, 1);
1547 if ($firstchar == "." or $file == "CVS" or $file == $excludefile) {
1548 continue;
1549 }
55fd8177 1550 $fullfile = "$rootdir/$file";
bf5c2e84 1551 if (filetype($fullfile) == "dir") {
55fd8177 1552 if ($justdirs) {
1553 $dirs[] = $file;
1554 }
bf5c2e84 1555 if ($descend) {
1556 $subdirs = get_directory_list($fullfile, $excludefile, $descend, $justdirs);
1557 foreach ($subdirs as $subdir) {
1558 $dirs[] = "$file/$subdir";
1559 }
f9903ed0 1560 }
55fd8177 1561 } else if (!$justdirs) {
b35e8568 1562 $dirs[] = $file;
f9903ed0 1563 }
1564 }
44e2d2bb 1565 closedir($dir);
f9903ed0 1566
774ab660 1567 asort($dirs);
1568
f9903ed0 1569 return $dirs;
1570}
1571
989bfa9d 1572function get_real_size($size=0) {
9fa49e22 1573/// Converts numbers like 10M into bytes
989bfa9d 1574 if (!$size) {
d8ba183c 1575 return 0;
989bfa9d 1576 }
1577 $scan['MB'] = 1048576;
64efda84 1578 $scan['Mb'] = 1048576;
989bfa9d 1579 $scan['M'] = 1048576;
266a416e 1580 $scan['m'] = 1048576;
989bfa9d 1581 $scan['KB'] = 1024;
64efda84 1582 $scan['Kb'] = 1024;
989bfa9d 1583 $scan['K'] = 1024;
266a416e 1584 $scan['k'] = 1024;
989bfa9d 1585
1586 while (list($key) = each($scan)) {
1587 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1588 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1589 break;
1590 }
1591 }
1592 return $size;
1593}
1594
44e2d2bb 1595function display_size($size) {
9fa49e22 1596/// Converts bytes into display form
4909e176 1597
1598 static $gb,$mb,$kb,$b;
1599
1600 if (empty($gb)) {
1601 $gb = get_string('sizegb');
1602 $mb = get_string('sizemb');
1603 $kb = get_string('sizekb');
1604 $b = get_string('sizeb');
1605 }
1606
44e2d2bb 1607 if ($size >= 1073741824) {
4909e176 1608 $size = round($size / 1073741824 * 10) / 10 . $gb;
44e2d2bb 1609 } else if ($size >= 1048576) {
4909e176 1610 $size = round($size / 1048576 * 10) / 10 . $mb;
44e2d2bb 1611 } else if ($size >= 1024) {
4909e176 1612 $size = round($size / 1024 * 10) / 10 . $kb;
d8ba183c 1613 } else {
4909e176 1614 $size = $size ." $b";
44e2d2bb 1615 }
1616 return $size;
1617}
1618
6b174680 1619function clean_filename($string) {
9fa49e22 1620/// Cleans a given filename by removing suspicious or troublesome characters
bbf4d8e6 1621/// Only these are allowed:
1622/// alphanumeric _ - .
1623
1624 $string = eregi_replace("\.\.+", "", $string);
8644437d 1625 $string = preg_replace('/[^\.a-zA-Z\d\_-]/','_', $string ); // only allowed chars
bbf4d8e6 1626 $string = eregi_replace("_+", "_", $string);
1627 return $string;
6b174680 1628}
1629
1630
1180c6dc 1631/// STRING TRANSLATION ////////////////////////////////////////
1632
4bfa92e7 1633function current_language() {
9fa49e22 1634/// Returns the code for the current language
3db3acfb 1635 global $CFG, $USER, $SESSION;
4bfa92e7 1636
e5415d58 1637 if (!empty($CFG->courselang)) { // Course language can override all other settings for this page
b3153e4b 1638 return $CFG->courselang;
1639
e5415d58 1640 } else if (!empty($SESSION->lang)) { // Session language can override other settings
3db3acfb 1641 return $SESSION->lang;
1642
e5415d58 1643 } else if (!empty($USER->lang)) { // User language can override site language
4bfa92e7 1644 return $USER->lang;
3db3acfb 1645
4bfa92e7 1646 } else {
1647 return $CFG->lang;
1648 }
1649}
bcc83c41 1650
9fa49e22 1651function print_string($identifier, $module="", $a=NULL) {
1652/// Given a string to translate - prints it out.
1653 echo get_string($identifier, $module, $a);
1654}
1655
a83fded1 1656function get_string($identifier, $module="", $a=NULL) {
d8ba183c 1657/// Return the translated string specified by $identifier as
9fa49e22 1658/// for $module. Uses the same format files as STphp.
1659/// $a is an object, string or number that can be used
1660/// within translation strings
1661///
1662/// eg "hello \$a->firstname \$a->lastname"
1663/// or "hello \$a"
1180c6dc 1664
4bfa92e7 1665 global $CFG;
1180c6dc 1666
e11dc9b6 1667 global $course; /// Not a nice hack, but quick
ac8abb5f 1668 if (empty($CFG->courselang)) {
1669 if (!empty($course->lang)) {
1670 $CFG->courselang = $course->lang;
1671 }
e11dc9b6 1672 }
1673
4bfa92e7 1674 $lang = current_language();
1180c6dc 1675
058eec18 1676 if ($module == "") {
1677 $module = "moodle";
1180c6dc 1678 }
1679
058eec18 1680 $langpath = "$CFG->dirroot/lang";
1681 $langfile = "$langpath/$lang/$module.php";
1180c6dc 1682
b947c69a 1683 // Look for the string - if found then return it
1684
1685 if (file_exists($langfile)) {
1686 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1687 eval($result);
1688 return $resultstring;
1180c6dc 1689 }
1690 }
1691
b947c69a 1692 // If the preferred language was English we can abort now
1180c6dc 1693
d8ba183c 1694 if ($lang == "en") {
b947c69a 1695 return "[[$identifier]]";
1696 }
1180c6dc 1697
b947c69a 1698 // Is a parent language defined? If so, try it.
d8ba183c 1699
b947c69a 1700 if ($result = get_string_from_file("parentlanguage", "$langpath/$lang/moodle.php", "\$parentlang")) {
1701 eval($result);
1702 if (!empty($parentlang)) {
1703 $langfile = "$langpath/$parentlang/$module.php";
1704 if (file_exists($langfile)) {
1705 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1706 eval($result);
1707 return $resultstring;
1708 }
1180c6dc 1709 }
1710 }
1711 }
b947c69a 1712
1713 // Our only remaining option is to try English
1714
1715 $langfile = "$langpath/en/$module.php";
1716 if (!file_exists($langfile)) {
1717 return "ERROR: No lang file ($langpath/en/$module.php)!";
1718 }
1719 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1720 eval($result);
1721 return $resultstring;
1722 }
1723
1724 return "[[$identifier]]"; // Last resort
1180c6dc 1725}
1726
1727
1180c6dc 1728function get_string_from_file($identifier, $langfile, $destination) {
9fa49e22 1729/// This function is only used from get_string().
2b32bddd 1730
1731 static $strings; // Keep the strings cached in memory.
1732
1733 if (empty($strings[$langfile])) {
1734 include ($langfile);
1735 $strings[$langfile] = $string;
1736 } else {
1737 $string = &$strings[$langfile];
1738 }
1180c6dc 1739
1740 if (!isset ($string[$identifier])) {
1741 return false;
1742 }
1743
a83fded1 1744 return "$destination = sprintf(\"".$string[$identifier]."\");";
1180c6dc 1745}
f9903ed0 1746
1747
1a72314d 1748function get_list_of_languages() {
1749/// Returns a list of language codes and their full names
1750 global $CFG;
1751
984a8bf3 1752 $languages = array();
1753
1754 if (!empty($CFG->langlist)) { // use admin's list of languages
1755 $langlist = explode(',', $CFG->langlist);
1756 foreach ($langlist as $lang) {
1757 if (file_exists("$CFG->dirroot/lang/$lang/moodle.php")) {
1758 include("$CFG->dirroot/lang/$lang/moodle.php");
1759 $languages[$lang] = $string["thislanguage"]." ($lang)";
1760 unset($string);
1761 }
1762 }
1763 } else {
1764 if (!$langdirs = get_list_of_plugins("lang")) {
1765 return false;
1766 }
1767 foreach ($langdirs as $lang) {
1768 include("$CFG->dirroot/lang/$lang/moodle.php");
1769 $languages[$lang] = $string["thislanguage"]." ($lang)";
1770 unset($string);
1771 }
1a72314d 1772 }
1773
1a72314d 1774 return $languages;
1775}
1776
5833a6c8 1777function get_list_of_countries() {
1778/// Returns a list of country names in the current language
1779 global $CFG, $USER;
1780
1781 $lang = current_language();
1782
1783 if (!file_exists("$CFG->dirroot/lang/$lang/countries.php")) {
aa3eb050 1784 if ($parentlang = get_string("parentlanguage")) {
1785 if (file_exists("$CFG->dirroot/lang/$parentlang/countries.php")) {
1786 $lang = $parentlang;
1787 } else {
1788 $lang = "en"; // countries.php must exist in this pack
1789 }
1790 } else {
1791 $lang = "en"; // countries.php must exist in this pack
1792 }
5833a6c8 1793 }
1794
d8ba183c 1795 include("$CFG->dirroot/lang/$lang/countries.php");
5833a6c8 1796
f8dbffb1 1797 if (!empty($string)) {
1798 asort($string);
1799 }
5833a6c8 1800
1801 return $string;
1802}
1803
82196932 1804function get_list_of_pixnames() {
1805/// Returns a list of picture names in the current language
1806 global $CFG;
1807
1808 $lang = current_language();
1809
1810 if (!file_exists("$CFG->dirroot/lang/$lang/pix.php")) {
1811 if ($parentlang = get_string("parentlanguage")) {
1812 if (file_exists("$CFG->dirroot/lang/$parentlang/pix.php")) {
1813 $lang = $parentlang;
1814 } else {
1815 $lang = "en"; // countries.php must exist in this pack
1816 }
1817 } else {
1818 $lang = "en"; // countries.php must exist in this pack
1819 }
1820 }
1821
d8ba183c 1822 include_once("$CFG->dirroot/lang/$lang/pix.php");
82196932 1823
1824 return $string;
1825}
1826
9bd2c874 1827function document_file($file, $include=true) {
1828/// Can include a given document file (depends on second
1829/// parameter) or just return info about it
1830
c9d4e6da 1831 global $CFG;
9bd2c874 1832
db356340 1833 $file = clean_filename($file);
1834
9bd2c874 1835 if (empty($file)) {
9bd2c874 1836 return false;
1837 }
1838
db356340 1839 $langs = array(current_language(), get_string("parentlanguage"), "en");
9bd2c874 1840
db356340 1841 foreach ($langs as $lang) {
1842 $info->filepath = "$CFG->dirroot/lang/$lang/docs/$file";
1843 $info->urlpath = "$CFG->wwwroot/lang/$lang/docs/$file";
9bd2c874 1844
db356340 1845 if (file_exists($info->filepath)) {
1846 if ($include) {
1847 include($info->filepath);
1848 }
1849 return $info;
0c106cd3 1850 }
9bd2c874 1851 }
1852
db356340 1853 return false;
9bd2c874 1854}
1855
1a72314d 1856
f9903ed0 1857/// ENCRYPTION ////////////////////////////////////////////////
1858
1859function rc4encrypt($data) {
1860 $password = "nfgjeingjk";
1861 return endecrypt($password, $data, "");
1862}
1863
1864function rc4decrypt($data) {
1865 $password = "nfgjeingjk";
1866 return endecrypt($password, $data, "de");
1867}
1868
1869function endecrypt ($pwd, $data, $case) {
9fa49e22 1870/// Based on a class by Mukul Sabharwal [mukulsabharwal@yahoo.com]
f9903ed0 1871
1872 if ($case == 'de') {
1873 $data = urldecode($data);
1874 }
1875
1876 $key[] = "";
1877 $box[] = "";
1878 $temp_swap = "";
1879 $pwd_length = 0;
1880
1881 $pwd_length = strlen($pwd);
1882
1883 for ($i = 0; $i <= 255; $i++) {
1884 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
1885 $box[$i] = $i;
1886 }
1887
1888 $x = 0;
1889
1890 for ($i = 0; $i <= 255; $i++) {
1891 $x = ($x + $box[$i] + $key[$i]) % 256;
1892 $temp_swap = $box[$i];
1893 $box[$i] = $box[$x];
1894 $box[$x] = $temp_swap;
1895 }
1896
1897 $temp = "";
1898 $k = "";
1899
1900 $cipherby = "";
1901 $cipher = "";
1902
1903 $a = 0;
1904 $j = 0;
1905
1906 for ($i = 0; $i < strlen($data); $i++) {
1907 $a = ($a + 1) % 256;
1908 $j = ($j + $box[$a]) % 256;
1909 $temp = $box[$a];
1910 $box[$a] = $box[$j];
1911 $box[$j] = $temp;
1912 $k = $box[(($box[$a] + $box[$j]) % 256)];
1913 $cipherby = ord(substr($data, $i, 1)) ^ $k;
1914 $cipher .= chr($cipherby);
1915 }
1916
1917 if ($case == 'de') {
1918 $cipher = urldecode(urlencode($cipher));
1919 } else {
1920 $cipher = urlencode($cipher);
1921 }
1922
1923 return $cipher;
1924}
1925
1926
5fba04fb 1927/// CALENDAR MANAGEMENT ////////////////////////////////////////////////////////////////
1928
1929
1930function add_event($event) {
1931/// call this function to add an event to the calendar table
1932/// and to call any calendar plugins
1933/// The function returns the id number of the resulting record
1934/// The object event should include the following:
1935/// $event->name Name for the event
1936/// $event->description Description of the event (defaults to '')
1937/// $event->courseid The id of the course this event belongs to (0 = all courses)
1938/// $event->groupid The id of the group this event belongs to (0 = no group)
1939/// $event->userid The id of the user this event belongs to (0 = no user)
1940/// $event->modulename Name of the module that creates this event
1941/// $event->instance Instance of the module that owns this event
1942/// $event->eventtype The type info together with the module info could
1943/// be used by calendar plugins to decide how to display event
1944/// $event->timestart Timestamp for start of event
1945/// $event->timeduration Duration (defaults to zero)
1946
1947 global $CFG;
1948
1949 $event->timemodified = time();
d8ba183c 1950
5fba04fb 1951 if (!$event->id = insert_record("event", $event)) {
1952 return false;
1953 }
d8ba183c 1954
5fba04fb 1955 if (!empty($CFG->calendar)) { // call the add_event function of the selected calendar
1956 if (file_exists("$CFG->dirroot/calendar/$CFG->calendar/lib.php")) {
1957 include_once("$CFG->dirroot/calendar/$CFG->calendar/lib.php");
1958 $calendar_add_event = $CFG->calendar.'_add_event';
1959 if (function_exists($calendar_add_event)) {
1960 $calendar_add_event($event);
1961 }
1962 }
1963 }
d8ba183c 1964
5fba04fb 1965 return $event->id;
1966}
1967
1968
1969function update_event($event) {
1970/// call this function to update an event in the calendar table
1971/// the event will be identified by the id field of the $event object
1972
1973 global $CFG;
1974
1975 $event->timemodified = time();
d8ba183c 1976
5fba04fb 1977 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
1978 if (file_exists("$CFG->dirroot/calendar/$CFG->calendar/lib.php")) {
1979 include_once("$CFG->dirroot/calendar/$CFG->calendar/lib.php");
1980 $calendar_update_event = $CFG->calendar.'_update_event';
1981 if (function_exists($calendar_update_event)) {
1982 $calendar_update_event($event);
1983 }
1984 }
1985 }
1986 return update_record("event", $event);
1987}
1988
1989
1990function delete_event($id) {
1991/// call this function to delete the event with id $id from calendar table
1992
1993 global $CFG;
1994
1995 if (!empty($CFG->calendar)) { // call the delete_event function of the selected calendar
1996 if (file_exists("$CFG->dirroot/calendar/$CFG->calendar/lib.php")) {
1997 include_once("$CFG->dirroot/calendar/$CFG->calendar/lib.php");
1998 $calendar_delete_event = $CFG->calendar.'_delete_event';
1999 if (function_exists($calendar_delete_event)) {
2000 $calendar_delete_event($id);
2001 }
2002 }
2003 }
2004 return delete_records("event", 'id', $id);
2005}
2006
2007
dcd338ff 2008function hide_event($event) {
2009/// call this function to hide an event in the calendar table
2010/// the event will be identified by the id field of the $event object
2011
2012 global $CFG;
2013
2014 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
2015 if (file_exists("$CFG->dirroot/calendar/$CFG->calendar/lib.php")) {
2016 include_once("$CFG->dirroot/calendar/$CFG->calendar/lib.php");
2017 $calendar_hide_event = $CFG->calendar.'_hide_event';
2018 if (function_exists($calendar_hide_event)) {
2019 $calendar_hide_event($event);
2020 }
2021 }
2022 }
2023 return set_field('event', 'visible', 0, 'id', $event->id);
2024}
2025
2026
2027function show_event($event) {
2028/// call this function to unhide an event in the calendar table
2029/// the event will be identified by the id field of the $event object
2030
2031 global $CFG;
2032
2033 if (!empty($CFG->calendar)) { // call the update_event function of the selected calendar
2034 if (file_exists("$CFG->dirroot/calendar/$CFG->calendar/lib.php")) {
2035 include_once("$CFG->dirroot/calendar/$CFG->calendar/lib.php");
2036 $calendar_show_event = $CFG->calendar.'_show_event';
2037 if (function_exists($calendar_show_event)) {
2038 $calendar_show_event($event);
2039 }
2040 }
2041 }
2042 return set_field('event', 'visible', 1, 'id', $event->id);
2043}
5fba04fb 2044
2045
9fa49e22 2046/// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
1e3e716f 2047
0cb77f5a 2048function get_list_of_plugins($plugin="mod", $exclude="") {
1d881d92 2049/// Lists plugin directories within some directory
2050
2051 global $CFG;
2052
2053 $basedir = opendir("$CFG->dirroot/$plugin");
2054 while ($dir = readdir($basedir)) {
b35e8568 2055 $firstchar = substr($dir, 0, 1);
0cb77f5a 2056 if ($firstchar == "." or $dir == "CVS" or $dir == "_vti_cnf" or $dir == $exclude) {
1d881d92 2057 continue;
2058 }
2059 if (filetype("$CFG->dirroot/$plugin/$dir") != "dir") {
2060 continue;
2061 }
2062 $plugins[] = $dir;
2063 }
2064 if ($plugins) {
2065 asort($plugins);
2066 }
2067 return $plugins;
2068}
2069
b0cb5e22 2070function check_php_version($version="4.1.0") {
9fa49e22 2071/// Returns true is the current version of PHP is greater that the specified one
b0cb5e22 2072 $minversion = intval(str_replace(".", "", $version));
2073 $curversion = intval(str_replace(".", "", phpversion()));
2074 return ($curversion >= $minversion);
2075}
2076
0095d5cd 2077function check_browser_version($brand="MSIE", $version=5.5) {
9fa49e22 2078/// Checks to see if is a browser matches the specified
2079/// brand and is equal or better version.
0095d5cd 2080
4c46c425 2081 $agent = $_SERVER["HTTP_USER_AGENT"];
2082
2083 if (empty($agent)) {
0095d5cd 2084 return false;
2085 }
4c46c425 2086
2087 switch ($brand) {
2088
2089 case "Gecko": /// Gecko based browsers
2090
2091 if (substr_count($agent, "Camino")) { // MacOS X Camino not supported.
2092 return false;
2093 }
2094
2095 // the proper string - Gecko/CCYYMMDD Vendor/Version
2096 if (ereg("^([a-zA-Z]+)/([0-9]+\.[0-9]+) \((.*)\) (.*)$", $agent, $match)) {
2097 if (ereg("^([Gecko]+)/([0-9]+)",$match[4], $reldate)) {
2098 if ($reldate[2] > $version) {
2099 return true;
2100 }
2101 }
2102 }
2103 break;
2104
2105
2106 case "MSIE": /// Internet Explorer
2107
0e2585ac 2108 if (strpos($agent, 'Opera')) { // Reject Opera
2109 return false;
2110 }
4c46c425 2111 $string = explode(";", $agent);
2112 if (!isset($string[1])) {
2113 return false;
2114 }
2115 $string = explode(" ", trim($string[1]));
2116 if (!isset($string[0]) and !isset($string[1])) {
2117 return false;
2118 }
2119 if ($string[0] == $brand and (float)$string[1] >= $version ) {
2120 return true;
2121 }
2122 break;
2123
0095d5cd 2124 }
4c46c425 2125
0095d5cd 2126 return false;
2127}
2128
c39c66a5 2129function ini_get_bool($ini_get_arg) {
2130/// This function makes the return value of ini_get consistent if you are
2131/// setting server directives through the .htaccess file in apache.
2132/// Current behavior for value set from php.ini On = 1, Off = [blank]
2133/// Current behavior for value set from .htaccess On = On, Off = Off
2134/// Contributed by jdell@unr.edu
2135
2136 $temp = ini_get($ini_get_arg);
2137
2138 if ($temp == "1" or strtolower($temp) == "on") {
2139 return true;
2140 }
2141 return false;
2142}
2143
0095d5cd 2144function can_use_richtext_editor() {
47037513 2145/// Compatibility stub to provide backward compatibility
2146 return can_use_html_editor();
2147}
2148
2149function can_use_html_editor() {
4c46c425 2150/// Is the HTML editor enabled? This depends on site and user
2151/// settings, as well as the current browser being used.
47037513 2152/// Returns false is editor is not being used, otherwise
2153/// returns "MSIE" or "Gecko"
4c46c425 2154
0095d5cd 2155 global $USER, $CFG;
4c46c425 2156
ce78926d 2157 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
4c46c425 2158 if (check_browser_version("MSIE", 5.5)) {
47037513 2159 return "MSIE";
2160 } else if (check_browser_version("Gecko", 20030516)) {
2161 return "Gecko";
4c46c425 2162 }
7ce20f09 2163 }
2164 return false;
0095d5cd 2165}
2166
47037513 2167
74944b73 2168function check_gd_version() {
9fa49e22 2169/// Hack to find out the GD version by parsing phpinfo output
aa095969 2170 $gdversion = 0;
74944b73 2171
aa095969 2172 if (function_exists('gd_info')){
2173 $gd_info = gd_info();
3ee23682 2174 if (substr_count($gd_info['GD Version'], "2.")) {
aa095969 2175 $gdversion = 2;
3ee23682 2176 } else if (substr_count($gd_info['GD Version'], "1.")) {
2177 $gdversion = 1;
aa095969 2178 }
3ee23682 2179
aa095969 2180 } else {
2181 ob_start();
2182 phpinfo(8);
2183 $phpinfo = ob_get_contents();
2184 ob_end_clean();
74944b73 2185
aa095969 2186 $phpinfo = explode("\n",$phpinfo);
74944b73 2187
92a4b0f1 2188
aa095969 2189 foreach ($phpinfo as $text) {
2190 $parts = explode('</td>',$text);
2191 foreach ($parts as $key => $val) {
2192 $parts[$key] = trim(strip_tags($val));
2193 }
2194 if ($parts[0] == "GD Version") {
2195 if (substr_count($parts[1], "2.0")) {
2196 $parts[1] = "2.0";
2197 }
2198 $gdversion = intval($parts[1]);
92a4b0f1 2199 }
74944b73 2200 }
2201 }
2202
2203 return $gdversion; // 1, 2 or 0
2204}
f9903ed0 2205
0095d5cd 2206
9fa49e22 2207function moodle_needs_upgrading() {
2208/// Checks version numbers of Main code and all modules to see
2209/// if there are any mismatches ... returns true or false
2210 global $CFG;
2211
2212 include_once("$CFG->dirroot/version.php"); # defines $version and upgrades
d8ba183c 2213 if ($CFG->version) {
9fa49e22 2214 if ($version > $CFG->version) {
2215 return true;
2216 }
2217 if ($mods = get_list_of_plugins("mod")) {
2218 foreach ($mods as $mod) {
2219 $fullmod = "$CFG->dirroot/mod/$mod";
2220 unset($module);
1079c8a8 2221 if (!is_readable("$fullmod/version.php")) {
2222 notify("Module '$mod' is not readable - check permissions");
2223 continue;
2224 }
9fa49e22 2225 include_once("$fullmod/version.php"); # defines $module with version etc
2226 if ($currmodule = get_record("modules", "name", $mod)) {
2227 if ($module->version > $currmodule->version) {
2228 return true;
2229 }
2230 }
2231 }
2232 }
2233 } else {
2234 return true;
2235 }
2236 return false;
2237}
2238
2239
2240/// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
2241
7d6cac54 2242function moodle_strtolower ($string, $encoding='') {
2243/// Converts string to lowercase using most compatible function available
2244 if (function_exists('mb_strtolower')) {
2245 if($encoding===''){
2246 return mb_strtolower($string); //use multibyte support with default encoding
2247 } else {
dbe0be00 2248 return mb_strtolower($string,$encoding); //use given encoding
d8ba183c 2249 }
7d6cac54 2250 } else {
2251 return strtolower($string); // use common function what rely on current locale setting
d8ba183c 2252 }
7d6cac54 2253}
2254
9fa49e22 2255function count_words($string) {
2256/// Words are defined as things between whitespace
2257 $string = strip_tags($string);
2258 return count(preg_split("/\w\b/", $string)) - 1;
2259}
2260
1d881d92 2261function random_string ($length=15) {
2262 $pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2263 $pool .= "abcdefghijklmnopqrstuvwxyz";
2264 $pool .= "0123456789";
2265 $poollen = strlen($pool);
2266 mt_srand ((double) microtime() * 1000000);
2267 $string = "";
2268 for ($i = 0; $i < $length; $i++) {
2269 $string .= substr($pool, (mt_rand()%($poollen)), 1);
2270 }
2271 return $string;
2272}
2273
2274
9fa49e22 2275function getweek ($startdate, $thedate) {
2276/// Given dates in seconds, how many weeks is the date from startdate
d8ba183c 2277/// The first week is 1, the second 2 etc ...
2278
9fa49e22 2279 if ($thedate < $startdate) { // error
d8ba183c 2280 return 0;
9fa49e22 2281 }
2282
2283 return floor(($thedate - $startdate) / 604800.0) + 1;
2284}
2285
2286function generate_password($maxlen=10) {
2287/// returns a randomly generated password of length $maxlen. inspired by
d8ba183c 2288/// http://www.phpbuilder.com/columns/jesus19990502.php3
9fa49e22 2289
2290 global $CFG;
2291
2292 $fillers = "1234567890!$-+";
2293 $wordlist = file($CFG->wordlist);
2294
2295 srand((double) microtime() * 1000000);
2296 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
2297 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
2298 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
2299
2300 return substr($word1 . $filler1 . $word2, 0, $maxlen);
2301}
2302
12659521 2303function format_float($num, $places=1) {
9fa49e22 2304/// Given a float, prints it nicely
2305 return sprintf("%.$places"."f", $num);
2306}
2307
ee0e5d57 2308function swapshuffle($array) {
2309/// Given a simple array, this shuffles it up just like shuffle()
2310/// Unlike PHP's shuffle() ihis function works on any machine.
2311
2312 srand ((double) microtime() * 10000000);
2313 $last = count($array) - 1;
2314 for ($i=0;$i<=$last;$i++) {
2315 $from = rand(0,$last);
2316 $curr = $array[$i];
2317 $array[$i] = $array[$from];
2318 $array[$from] = $curr;
d8ba183c 2319 }
ee0e5d57 2320 return $array;
2321}
2322
bc700e65 2323function swapshuffle_assoc($array) {
2324/// Like swapshuffle, but works on associative arrays
2325
2326 $newkeys = swapshuffle(array_keys($array));
2327 foreach ($newkeys as $newkey) {
2328 $newarray[$newkey] = $array[$newkey];
2329 }
2330 return $newarray;
2331}
2332
ee0e5d57 2333function draw_rand_array($array, $draws) {
d8ba183c 2334/// Given an arbitrary array, and a number of draws,
2335/// this function returns an array with that amount
ee0e5d57 2336/// of items. The indexes are retained.
2337
2338 srand ((double) microtime() * 10000000);
2339
2340 $return = array();
2341
2342 $last = count($array);
2343
2344 if ($draws > $last) {
2345 $draws = $last;
2346 }
2347
2348 while ($draws > 0) {
2349 $last--;
2350
2351 $keys = array_keys($array);
2352 $rand = rand(0, $last);
2353
2354 $return[$keys[$rand]] = $array[$keys[$rand]];
2355 unset($array[$keys[$rand]]);
d8ba183c 2356
ee0e5d57 2357 $draws--;
2358 }
2359
2360 return $return;
d8ba183c 2361}
9fa49e22 2362
f5e82bc7 2363function microtime_diff($a, $b) {
2364 list($a_dec, $a_sec) = explode(" ", $a);
2365 list($b_dec, $b_sec) = explode(" ", $b);
2366 return $b_sec - $a_sec + $b_dec - $a_dec;
2367}
2368
02ebf404 2369function make_menu_from_list($list, $separator=",") {
d8ba183c 2370/// Given a list (eg a,b,c,d,e) this function returns
02ebf404 2371/// an array of 1->a, 2->b, 3->c etc
2372
2373 $array = array_reverse(explode($separator, $list), true);
2374 foreach ($array as $key => $item) {
2375 $outarray[$key+1] = trim($item);
2376 }
2377 return $outarray;
2378}
2379
fdc47ee6 2380function make_grades_menu($gradingtype) {
2381/// Creates an array that represents all the current grades that
2382/// can be chosen using the given grading type. Negative numbers
2383/// are scales, zero is no grade, and positive numbers are maximum
2384/// grades.
2385
2386 $grades = array();
2387 if ($gradingtype < 0) {
2388 if ($scale = get_record("scale", "id", - $gradingtype)) {
2389 return make_menu_from_list($scale->scale);
2390 }
2391 } else if ($gradingtype > 0) {
2392 for ($i=$gradingtype; $i>=0; $i--) {
62ca135d 2393 $grades[$i] = "$i / $gradingtype";
fdc47ee6 2394 }
2395 return $grades;
2396 }
2397 return $grades;
2398}
2399
757a0abd 2400function make_unique_id_code($extra="") {
280faf9f 2401
2402 $hostname = "unknownhost";
2403 if (!empty($_SERVER["HTTP_HOST"])) {
2404 $hostname = $_SERVER["HTTP_HOST"];
2405 } else if (!empty($_ENV["HTTP_HOST"])) {
2406 $hostname = $_ENV["HTTP_HOST"];
2407 } else if (!empty($_SERVER["SERVER_NAME"])) {
2408 $hostname = $_SERVER["SERVER_NAME"];
2409 } else if (!empty($_ENV["SERVER_NAME"])) {
2410 $hostname = $_ENV["SERVER_NAME"];
2411 }
2412
1ccc73ac 2413 $date = gmdate("ymdHis");
280faf9f 2414
2415 $random = random_string(6);
2416
757a0abd 2417 if ($extra) {
2418 return "$hostname+$date+$random+$extra";
2419 } else {
2420 return "$hostname+$date+$random";
2421 }
280faf9f 2422}
2423
0095d5cd 2424
9d5b689c 2425// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
f9903ed0 2426?>