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