Minor change to allow continue after upgrade_backup
[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 //
19// http://moodle.com //
20// //
21// Copyright (C) 2001-2003 Martin Dougiamas http://dougiamas.com //
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
f9903ed0 37
9fa49e22 38/// PARAMETER HANDLING ////////////////////////////////////////////////////
6b174680 39
9fa49e22 40function require_variable($var) {
41/// Variable must be present
42 if (! isset($var)) {
43 error("A required parameter was missing");
6b174680 44 }
45}
46
9fa49e22 47function optional_variable(&$var, $default=0) {
48/// Variable may be present, if not then set a default
49 if (! isset($var)) {
50 $var = $default;
6b174680 51 }
52}
53
54
9fa49e22 55function set_config($name, $value) {
56/// No need for get_config because they are usually always available in $CFG
dfc9ba9b 57
9fa49e22 58 if (get_field("config", "name", "name", $name)) {
59 return set_field("config", "value", $value, "name", $name);
d897cae4 60 } else {
9fa49e22 61 $config->name = $name;
62 $config->value = $value;
63 return insert_record("config", $config);
39917a09 64 }
39917a09 65}
66
39917a09 67
9fa49e22 68/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
39917a09 69
3db75c62 70function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99) {
9fa49e22 71/// Given date parts in user time, produce a GMT timestamp
39917a09 72
94e34118 73 global $USER;
74
03c17ddf 75 if ($timezone == 99) {
94e34118 76 $timezone = (float)$USER->timezone;
77 }
78
79 if (abs($timezone) > 13) {
03c17ddf 80 return mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
81 } else {
82 $time = gmmktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
83 return usertime($time, $timezone); // This is GMT
84 }
39917a09 85}
86
8dbed6be 87function format_time($totalsecs, $str=NULL) {
9fa49e22 88/// Given an amount of time in seconds, returns string
89/// formatted nicely as months, days, hours etc as needed
c7e3ac2a 90
6b174680 91 $totalsecs = abs($totalsecs);
c7e3ac2a 92
8dbed6be 93 if (!$str) { // Create the str structure the slow way
94 $str->day = get_string("day");
95 $str->days = get_string("days");
96 $str->hour = get_string("hour");
97 $str->hours = get_string("hours");
98 $str->min = get_string("min");
99 $str->mins = get_string("mins");
100 $str->sec = get_string("sec");
101 $str->secs = get_string("secs");
102 }
103
104 $days = floor($totalsecs/86400);
6b174680 105 $remainder = $totalsecs - ($days*86400);
8dbed6be 106 $hours = floor($remainder/3600);
6b174680 107 $remainder = $remainder - ($hours*3600);
8dbed6be 108 $mins = floor($remainder/60);
109 $secs = $remainder - ($mins*60);
110
111 $ss = ($secs == 1) ? $str->sec : $str->secs;
112 $sm = ($mins == 1) ? $str->min : $str->mins;
113 $sh = ($hours == 1) ? $str->hour : $str->hours;
114 $sd = ($days == 1) ? $str->day : $str->days;
115
9c9f7d77 116 $odays = "";
117 $ohours = "";
118 $omins = "";
119 $osecs = "";
120
8dbed6be 121 if ($days) $odays = "$days $sd";
122 if ($hours) $ohours = "$hours $sh";
123 if ($mins) $omins = "$mins $sm";
124 if ($secs) $osecs = "$secs $ss";
6b174680 125
126 if ($days) return "$odays $ohours";
127 if ($hours) return "$ohours $omins";
128 if ($mins) return "$omins $osecs";
129 if ($secs) return "$osecs";
130 return get_string("now");
131}
f9903ed0 132
61ae5d36 133function userdate($date, $format="", $timezone=99, $fixday = true) {
9fa49e22 134/// Returns a formatted string that represents a date in user time
135/// WARNING: note that the format is for strftime(), not date().
136/// Because of a bug in most Windows time libraries, we can't use
137/// the nicer %e, so we have to use %d which has leading zeroes.
138/// A lot of the fuss below is just getting rid of these leading
139/// zeroes as efficiently as possible.
61ae5d36 140///
141/// If parammeter fixday = true (default), then take off leading
142/// zero from %d, else mantain it.
7a302afc 143
873960de 144 global $USER;
145
5fa51a39 146 if ($format == "") {
dcde9f02 147 $format = get_string("strftimedaydatetime");
5fa51a39 148 }
035cdbff 149
dcde9f02 150 $formatnoday = str_replace("%d", "DD", $format);
61ae5d36 151 if ($fixday) {
152 $fixday = ($formatnoday != $format);
153 }
dcde9f02 154
5fa51a39 155 if ($timezone == 99) {
ab247495 156 if (isset($USER->timezone)) {
157 $timezone = (float)$USER->timezone;
158 }
5fa51a39 159 }
0431bd7c 160 if (abs($timezone) > 13) {
035cdbff 161 if ($fixday) {
162 $datestring = strftime($formatnoday, $date);
163 $daystring = str_replace(" 0", "", strftime(" %d", $date));
164 $datestring = str_replace("DD", $daystring, $datestring);
165 } else {
166 $datestring = strftime($format, $date);
167 }
bea7a51e 168 } else {
70d4cf82 169 $date = $date + (int)($timezone * 3600);
035cdbff 170 if ($fixday) {
70d4cf82 171 $datestring = gmstrftime($formatnoday, $date);
9fa49e22 172 $daystring = str_replace(" 0", "", gmstrftime(" %d", $date));
035cdbff 173 $datestring = str_replace("DD", $daystring, $datestring);
174 } else {
70d4cf82 175 $datestring = gmstrftime($format, $date);
035cdbff 176 }
873960de 177 }
bea7a51e 178
035cdbff 179 return $datestring;
873960de 180}
181
5fa51a39 182function usergetdate($date, $timezone=99) {
9fa49e22 183/// Given a $date timestamp in GMT, returns an array
184/// that represents the date in user time
6b174680 185
873960de 186 global $USER;
187
5fa51a39 188 if ($timezone == 99) {
189 $timezone = (float)$USER->timezone;
190 }
0431bd7c 191 if (abs($timezone) > 13) {
873960de 192 return getdate($date);
193 }
d2d6171f 194 //There is no gmgetdate so I have to fake it...
195 $date = $date + (int)($timezone * 3600);
196 $getdate["seconds"] = gmstrftime("%S", $date);
197 $getdate["minutes"] = gmstrftime("%M", $date);
198 $getdate["hours"] = gmstrftime("%H", $date);
199 $getdate["mday"] = gmstrftime("%d", $date);
200 $getdate["wday"] = gmstrftime("%u", $date);
201 $getdate["mon"] = gmstrftime("%m", $date);
202 $getdate["year"] = gmstrftime("%Y", $date);
203 $getdate["yday"] = gmstrftime("%j", $date);
204 $getdate["weekday"] = gmstrftime("%A", $date);
205 $getdate["month"] = gmstrftime("%B", $date);
206 return $getdate;
d552ead0 207}
208
209function usertime($date, $timezone=99) {
9fa49e22 210/// Given a GMT timestamp (seconds since epoch), offsets it by
211/// the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
d552ead0 212 global $USER;
213
214 if ($timezone == 99) {
215 $timezone = (float)$USER->timezone;
216 }
0431bd7c 217 if (abs($timezone) > 13) {
d552ead0 218 return $date;
219 }
220 return $date - (int)($timezone * 3600);
221}
222
edf7fe8c 223function usergetmidnight($date, $timezone=99) {
9fa49e22 224/// Given a time, return the GMT timestamp of the most recent midnight
225/// for the current user.
edf7fe8c 226 global $USER;
227
4606d9bb 228 if ($timezone == 99) {
229 $timezone = (float)$USER->timezone;
230 }
231
edf7fe8c 232 $userdate = usergetdate($date, $timezone);
4606d9bb 233
0431bd7c 234 if (abs($timezone) > 13) {
4606d9bb 235 return mktime(0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
236 }
237
edf7fe8c 238 $timemidnight = gmmktime (0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
239 return usertime($timemidnight, $timezone); // Time of midnight of this user's day, in GMT
240
241}
242
d552ead0 243function usertimezone($timezone=99) {
9fa49e22 244/// Returns a string that prints the user's timezone
d552ead0 245 global $USER;
246
247 if ($timezone == 99) {
248 $timezone = (float)$USER->timezone;
249 }
0431bd7c 250 if (abs($timezone) > 13) {
d552ead0 251 return "server time";
252 }
253 if (abs($timezone) < 0.5) {
254 return "GMT";
255 }
256 if ($timezone > 0) {
257 return "GMT+$timezone";
258 } else {
259 return "GMT$timezone";
260 }
f9903ed0 261}
262
263
9fa49e22 264/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
f9903ed0 265
da5c172a 266function require_login($courseid=0) {
9fa49e22 267/// This function checks that the current user is logged in, and optionally
268/// whether they are "logged in" or allowed to be in a particular course.
269/// If not, then it redirects them to the site login or course enrolment.
f9903ed0 270
607809b3 271 global $CFG, $SESSION, $USER, $FULLME, $PHPSESSID;
f9903ed0 272
da5c172a 273 // First check that the user is logged in to the site.
c21c671d 274 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
f9903ed0 275 $SESSION->wantsurl = $FULLME;
9f44d972 276 if (!empty($_SERVER["HTTP_REFERER"])) {
277 $SESSION->fromurl = $_SERVER["HTTP_REFERER"];
278 }
c21c671d 279 $USER = NULL;
f9903ed0 280 if ($PHPSESSID) { // Cookies not enabled.
a7b9e8bc 281 redirect("$CFG->wwwroot/login/index.php?PHPSESSID=$PHPSESSID");
f9903ed0 282 } else {
a7b9e8bc 283 redirect("$CFG->wwwroot/login/index.php");
f9903ed0 284 }
285 die;
f9903ed0 286 }
808a3baa 287
288 // Check that the user account is properly set up
289 if (user_not_fully_set_up($USER)) {
290 $site = get_site();
291 redirect("$CFG->wwwroot/user/edit.php?id=$USER->id&course=$site->id");
292 die;
293 }
da5c172a 294
295 // Next, check if the user can be in a particular course
296 if ($courseid) {
9c9f7d77 297 if (!empty($USER->student[$courseid]) or !empty($USER->teacher[$courseid]) or !empty($USER->admin)) {
cb909d74 298 if (isset($USER->realuser)) { // Make sure the REAL person can also access this course
299 if (!isteacher($courseid, $USER->realuser)) {
300 print_header();
5ebe27e2 301 notice(get_string("studentnotallowed", "", "$USER->firstname $USER->lastname"), $CFG->wwwroot);
cb909d74 302 }
303
304 } else { // just update their last login time
3ce2f1e0 305 update_user_in_db();
306 }
da5c172a 307 return; // user is a member of this course.
308 }
309 if (! $course = get_record("course", "id", $courseid)) {
310 error("That course doesn't exist");
311 }
1efa27fd 312 if (!$course->visible) {
313 print_header();
314 notice(get_string("studentnotallowed", "", "$USER->firstname $USER->lastname"), $CFG->wwwroot);
315 }
7363ff91 316 if ($USER->username == "guest") {
317 switch ($course->guest) {
318 case 0: // Guests not allowed
319 print_header();
320 notice(get_string("guestsnotallowed", "", $course->fullname));
321 break;
322 case 1: // Guests allowed
323 update_user_in_db();
324 return;
325 case 2: // Guests allowed with key (drop through)
326 break;
327 }
da5c172a 328 }
f9903ed0 329
7363ff91 330 // Currently not enrolled in the course, so see if they want to enrol
da5c172a 331 $SESSION->wantsurl = $FULLME;
332 redirect("$CFG->wwwroot/course/enrol.php?id=$courseid");
333 die;
334 }
f9903ed0 335}
336
1d881d92 337function update_user_login_times() {
338 global $USER;
339
340 $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
341 $USER->currentlogin = $user->currentlogin = time();
1d881d92 342
343 $user->id = $USER->id;
344
345 return update_record("user", $user);
346}
347
808a3baa 348function user_not_fully_set_up($user) {
ac5d88eb 349 return ($user->username != "guest" and (empty($user->firstname) or empty($user->lastname) or empty($user->email)));
808a3baa 350}
f9903ed0 351
f9903ed0 352function update_login_count() {
9fa49e22 353/// Keeps track of login attempts
354
f9903ed0 355 global $SESSION;
356
357 $max_logins = 10;
358
359 if (empty($SESSION->logincount)) {
360 $SESSION->logincount = 1;
361 } else {
362 $SESSION->logincount++;
363 }
364
365 if ($SESSION->logincount > $max_logins) {
9fa49e22 366 unset($SESSION->wantsurl);
1d881d92 367 error(get_string("errortoomanylogins"));
d578afc8 368 }
369}
370
9fa49e22 371function reset_login_count() {
372/// Resets login attempts
373 global $SESSION;
d578afc8 374
9fa49e22 375 $SESSION->logincount = 0;
d578afc8 376}
377
581d7b49 378function isadmin($userid=0) {
9fa49e22 379/// Is the user an admin?
f9903ed0 380 global $USER;
aa095969 381 static $admins = array();
382 static $nonadmins = array();
f9903ed0 383
581d7b49 384 if (!$userid){
385 if (empty($USER->id)) {
386 return false;
387 }
388 $userid = $USER->id;
9bd2c874 389 }
390
581d7b49 391 if (in_array($userid, $admins)) {
aa095969 392 return true;
581d7b49 393 } else if (in_array($userid, $nonadmins)) {
aa095969 394 return false;
581d7b49 395 } else if (record_exists("user_admins", "userid", $userid)){
396 $admins[] = $userid;
aa095969 397 return true;
398 } else {
581d7b49 399 $nonadmins[] = $userid;
aa095969 400 return false;
f9903ed0 401 }
f9903ed0 402}
403
8a9e3fd7 404function isteacher($courseid, $userid=0) {
9fa49e22 405/// Is the user a teacher or admin?
f9903ed0 406 global $USER;
407
d115a57f 408 if (isadmin($userid)) { // admins can do anything the teacher can
409 return true;
410 }
411
f9903ed0 412 if (!$userid) {
9bd2c874 413 return !empty($USER->teacher[$courseid]);
f9903ed0 414 }
415
ebc3bd2b 416 return record_exists("user_teachers", "userid", $userid, "course", $courseid);
f9903ed0 417}
418
1924074c 419function iscreator ($userid=0) {
420/// Can user create new courses?
421 global $USER;
8a205861 422 if (empty($USER->id)) {
423 return false;
424 }
1924074c 425 if (isadmin($userid)) { // admins can do anything
426 return true;
427 }
8a205861 428 if (empty($userid)) {
1924074c 429 return record_exists("user_coursecreators", "userid", $USER->id);
430 }
431
432 return record_exists("user_coursecreators", "userid", $userid);
433}
434
8a9e3fd7 435function isstudent($courseid, $userid=0) {
9fa49e22 436/// Is the user a student in this course?
f9903ed0 437 global $USER;
438
439 if (!$userid) {
346b1a24 440 return !empty($USER->student[$courseid]);
f9903ed0 441 }
442
ebc3bd2b 443 // $timenow = time(); // todo: add time check below
f9903ed0 444
ebc3bd2b 445 return record_exists("user_students", "userid", $userid, "course", $courseid);
f9903ed0 446}
447
da5c172a 448function isguest($userid=0) {
9fa49e22 449/// Is the user a guest?
da5c172a 450 global $USER;
451
452 if (!$userid) {
b35e8568 453 if (empty($USER->username)) {
454 return false;
455 }
da5c172a 456 return ($USER->username == "guest");
457 }
458
9fa49e22 459 return record_exists("user", "id", $userid, "username", "guest");
da5c172a 460}
461
9fa49e22 462
2c309dc2 463function isediting($courseid, $user=NULL) {
9fa49e22 464/// Is the current user in editing mode?
2c309dc2 465 global $USER;
466 if (!$user){
467 $user = $USER;
468 }
9c9f7d77 469 if (empty($user->editing)) {
470 return false;
471 }
2c309dc2 472 return ($user->editing and isteacher($courseid, $user->id));
473}
474
7977cffd 475function ismoving($courseid) {
476/// Is the current user currently moving an activity?
477 global $USER;
478
479 if (!empty($USER->activitycopy)) {
480 return ($USER->activitycopycourse == $courseid);
481 }
482 return false;
483}
484
f9903ed0 485
486function set_moodle_cookie($thing) {
9fa49e22 487/// Sets a moodle cookie with an encrypted string
7185e073 488 global $CFG;
489
490 $cookiename = "MOODLEID{$CFG->prefix}";
f9903ed0 491
492 $days = 60;
493 $seconds = 60*60*24*$days;
494
7185e073 495 setCookie($cookiename, "", time() - 3600, "/");
496 setCookie($cookiename, rc4encrypt($thing), time()+$seconds, "/");
f9903ed0 497}
498
499
500function get_moodle_cookie() {
9fa49e22 501/// Gets a moodle cookie with an encrypted string
7185e073 502 global $CFG;
503
4fe04be0 504 $cookiename = "MOODLEID{$CFG->prefix}";
7185e073 505
1079c8a8 506 if (empty($_COOKIE[$cookiename])) {
507 return "";
508 } else {
509 return rc4decrypt($_COOKIE[$cookiename]);
510 }
f9903ed0 511}
512
513
faebaf0f 514function create_user_record($username, $password) {
9fa49e22 515/// Creates a bare-bones user record
e858f9da 516 global $REMOTE_ADDR, $CFG;
1e22bc9c 517 //just in case check text case
518 $username = trim(moodle_strtolower($username));
6ae24de0 519 if (function_exists(auth_get_userinfo)) {
e858f9da 520 if ($newinfo = auth_get_userinfo($username)) {
34daec9b 521 foreach ($newinfo as $key => $value){
9f44d972 522 $newuser->$key = addslashes(stripslashes($value)); // Just in case
e858f9da 523 }
524 }
525 }
f9903ed0 526
faebaf0f 527 $newuser->username = $username;
528 $newuser->password = md5($password);
a0bac19d 529 $newuser->lang = $CFG->lang;
faebaf0f 530 $newuser->confirmed = 1;
531 $newuser->lastIP = $REMOTE_ADDR;
532 $newuser->timemodified = time();
f9903ed0 533
faebaf0f 534 if (insert_record("user", $newuser)) {
535 return get_user_info_from_db("username", $username);
536 }
537 return false;
538}
539
540function authenticate_user_login($username, $password) {
9fa49e22 541/// Given a username and password, this function looks them
542/// up using the currently selected authentication mechanism,
543/// and if the authentication is successful, it returns a
544/// valid $user object from the 'user' table.
545///
546/// Uses auth_ functions from the currently active auth module
faebaf0f 547
548 global $CFG;
549
466558e3 550 $md5password = md5($password);
551
14217044 552 if (empty($CFG->auth)) {
faebaf0f 553 $CFG->auth = "email"; // Default authentication module
554 }
555
466558e3 556 if ($username == "guest") {
557 $CFG->auth = "none"; // Guest account always internal
558 }
559
560 // If this is the admin, then just use internal methods
92710226 561 // Doing this first (even though it's less efficient) because
562 // the chosen authentication method might hang and lock the
563 // admin out.
9fa49e22 564 if (adminlogin($username, $md5password)) {
466558e3 565 return get_user_info_from_db("username", $username);
566 }
567
92710226 568 // OK, the user is a normal user, so try and authenticate them
e858f9da 569 require_once("$CFG->dirroot/auth/$CFG->auth/lib.php");
faebaf0f 570
571 if (auth_user_login($username, $password)) { // Successful authentication
faebaf0f 572 if ($user = get_user_info_from_db("username", $username)) {
92710226 573 if ($md5password <> $user->password) { // Update local copy of password for reference
466558e3 574 set_field("user", "password", $md5password, "username", $username);
faebaf0f 575 }
faebaf0f 576 } else {
e582b65e 577 $user = create_user_record($username, $password);
faebaf0f 578 }
89b54325 579
e582b65e 580 if (function_exists('auth_iscreator')) { // Check if the user is a creator
581 if (auth_iscreator($username)) {
582 if (! record_exists("user_coursecreators", "userid", $user->id)) {
583 $cdata['userid']=$user->id;
584 $creator = insert_record("user_coursecreators",$cdata);
585 if (! $creator) {
586 error("Cannot add user to course creators.");
587 }
588 }
589 } else {
590 if ( record_exists("user_coursecreators", "userid", $user->id)) {
f5cdd4d1 591 $creator = delete_records("user_coursecreators", "userid", $user->id);
e582b65e 592 if (! $creator) {
593 error("Cannot remove user from course creators.");
594 }
595 }
596 }
597 }
598
599 return $user;
600 } else {
601 return false;
602 }
f9903ed0 603}
604
faebaf0f 605
9fa49e22 606function enrol_student($user, $course) {
607/// Enrols a student in a given course
608 global $db;
f9903ed0 609
ebc3bd2b 610 $record->userid = $user;
9fa49e22 611 $record->course = $course;
612 $record->start = 0;
613 $record->end = 0;
614 $record->time = time();
f9903ed0 615
ebc3bd2b 616 return insert_record("user_students", $record);
d7facad8 617}
618
9fa49e22 619function unenrol_student($user, $course=0) {
620/// Unenrols a student from a given course
621 global $db;
d7facad8 622
9fa49e22 623 if ($course) {
624 /// First delete any crucial stuff that might still send mail
625 if ($forums = get_records("forum", "course", $course)) {
626 foreach ($forums as $forum) {
ebc3bd2b 627 delete_records("forum_subscriptions", "forum", $forum->id, "userid", $user);
bb09fb11 628 }
f9903ed0 629 }
ebc3bd2b 630 return delete_records("user_students", "userid", $user, "course", $course);
9fa49e22 631
f9903ed0 632 } else {
ebc3bd2b 633 delete_records("forum_subscriptions", "userid", $user);
634 return delete_records("user_students", "userid", $user);
f9903ed0 635 }
636}
637
9fa49e22 638function remove_teacher($user, $course=0) {
639/// Removes a teacher from a given course (or ALL courses)
640/// Does not delete the user account
641 global $db;
57507290 642
9fa49e22 643 if ($course) {
644 /// First delete any crucial stuff that might still send mail
645 if ($forums = get_records("forum", "course", $course)) {
646 foreach ($forums as $forum) {
ebc3bd2b 647 delete_records("forum_subscriptions", "forum", $forum->id, "userid", $user);
9fa49e22 648 }
649 }
ebc3bd2b 650 return delete_records("user_teachers", "userid", $user, "course", $course);
57507290 651 } else {
ebc3bd2b 652 delete_records("forum_subscriptions", "userid", $user);
653 return delete_records("user_teachers", "userid", $user);
57507290 654 }
f9903ed0 655}
656
9fa49e22 657function remove_admin($user) {
658/// Removes an admin from a site
659 global $db;
f9903ed0 660
ebc3bd2b 661 return delete_records("user_admins", "userid", $user);
f9903ed0 662}
663
f9903ed0 664
665
f9903ed0 666/// CORRESPONDENCE ////////////////////////////////////////////////
667
5fa51a39 668function email_to_user($user, $from, $subject, $messagetext, $messagehtml="", $attachment="", $attachname="") {
9fa49e22 669/// user - a user record as an object
670/// from - a user record as an object
671/// subject - plain text subject line of the email
672/// messagetext - plain text version of the message
673/// messagehtml - complete html version of the message (optional)
674/// attachment - a file on the filesystem, relative to $CFG->dataroot
675/// attachname - the name of the file (extension indicates MIME)
f9903ed0 676
4216daa6 677 global $CFG, $_SERVER;
f9903ed0 678
136dabd8 679 include_once("$CFG->libdir/phpmailer/class.phpmailer.php");
f9903ed0 680
5fa51a39 681 if (!$user) {
f9903ed0 682 return false;
683 }
684
f9903ed0 685 $mail = new phpmailer;
686
72c578ca 687 $mail->Version = "Moodle $CFG->version"; // mailer version
136dabd8 688 $mail->PluginDir = "$CFG->libdir/phpmailer/"; // plugin directory (eg smtp plugin)
562bbe90 689
98c4eae3 690
d483bcd3 691 if (current_language() != "en") {
692 $mail->CharSet = get_string("thischarset");
98c4eae3 693 }
694
7f86ce17 695 if ($CFG->smtphosts) {
1e411ffc 696 $mail->IsSMTP(); // use SMTP directly
697 $mail->Host = "$CFG->smtphosts"; // specify main and backup servers
9f58537a 698
699 if ($CFG->smtpuser) { // Use SMTP authentication
700 $mail->SMTPAuth = true;
701 $mail->Username = $CFG->smtpuser;
702 $mail->Password = $CFG->smtppass;
703 }
7f86ce17 704 } else {
1e411ffc 705 $mail->IsMail(); // use PHP mail() = sendmail
7f86ce17 706 }
f9903ed0 707
2b97bd71 708 $adminuser = get_admin();
709
710 $mail->Sender = "$adminuser->email";
711
136dabd8 712 $mail->From = "$from->email";
713 $mail->FromName = "$from->firstname $from->lastname";
714 $mail->Subject = stripslashes($subject);
f9903ed0 715
6b174680 716 $mail->AddAddress("$user->email", "$user->firstname $user->lastname");
f9903ed0 717
f9903ed0 718 $mail->WordWrap = 70; // set word wrap
f9903ed0 719
136dabd8 720 if ($messagehtml) {
721 $mail->IsHTML(true);
722 $mail->Body = $messagehtml;
78681899 723 $mail->AltBody = "\n$messagetext\n";
136dabd8 724 } else {
725 $mail->IsHTML(false);
78681899 726 $mail->Body = "\n$messagetext\n";
f9903ed0 727 }
728
136dabd8 729 if ($attachment && $attachname) {
730 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
4216daa6 731 $mail->AddAddress("$adminuser->email", "$adminuser->firstname $adminuser->lastname");
732 $mail->AddStringAttachment("Error in attachment. User attempted to attach a filename with a unsafe name.", "error.txt", "8bit", "text/plain");
136dabd8 733 } else {
734 include_once("$CFG->dirroot/files/mimetypes.php");
735 $mimetype = mimeinfo("type", $attachname);
736 $mail->AddAttachment("$CFG->dataroot/$attachment", "$attachname", "base64", "$mimetype");
737 }
f9903ed0 738 }
739
136dabd8 740 if ($mail->Send()) {
741 return true;
742 } else {
4216daa6 743 echo "ERROR: $mail->ErrorInfo\n";
744 $site = get_site();
745 add_to_log($site->id, "library", "mailer", $_SERVER["REQUEST_URI"], "ERROR: $mail->ErrorInfo");
f9903ed0 746 return false;
747 }
f9903ed0 748}
749
1d881d92 750function reset_password_and_mail($user) {
751
752 global $CFG;
753
754 $site = get_site();
755 $from = get_admin();
756
757 $newpassword = generate_password();
758
759 if (! set_field("user", "password", md5($newpassword), "id", $user->id) ) {
760 error("Could not set user password!");
761 }
762
763 $a->firstname = $user->firstname;
764 $a->sitename = $site->fullname;
765 $a->username = $user->username;
766 $a->newpassword = $newpassword;
767 $a->link = "$CFG->wwwroot/login/change_password.php";
768 $a->signoff = "$from->firstname $from->lastname ($from->email)";
769
770 $message = get_string("newpasswordtext", "", $a);
771
772 $subject = "$site->fullname: ".get_string("changedpassword");
773
774 return email_to_user($user, $from, $subject, $message);
775
776}
777
778function send_confirmation_email($user) {
779
780 global $CFG;
781
782 $site = get_site();
783 $from = get_admin();
784
785 $data->firstname = $user->firstname;
786 $data->sitename = $site->fullname;
787 $data->link = "$CFG->wwwroot/login/confirm.php?p=$user->secret&s=$user->username";
788 $data->admin = "$from->firstname $from->lastname ($from->email)";
789
790 $message = get_string("emailconfirmation", "", $data);
eb347b6b 791 $subject = get_string("emailconfirmationsubject", "", $site->fullname);
1d881d92 792
793 return email_to_user($user, $from, $subject, $message);
794
795}
796
eb347b6b 797function send_password_change_confirmation_email($user) {
798
799 global $CFG;
800
801 $site = get_site();
802 $from = get_admin();
803
804 $data->firstname = $user->firstname;
805 $data->sitename = $site->fullname;
806 $data->link = "$CFG->wwwroot/login/forgot_password.php?p=$user->secret&s=$user->username";
807 $data->admin = "$from->firstname $from->lastname ($from->email)";
808
809 $message = get_string("emailpasswordconfirmation", "", $data);
810 $subject = get_string("emailpasswordconfirmationsubject", "", $site->fullname);
811
812 return email_to_user($user, $from, $subject, $message);
813
814}
815
816
1d881d92 817
136dabd8 818
f9903ed0 819/// FILE HANDLING /////////////////////////////////////////////
820
6b174680 821function make_upload_directory($directory) {
9fa49e22 822/// $directory = a string of directory names under $CFG->dataroot
823/// eg stuff/assignment/1
824/// Returns full directory if successful, false if not
6b174680 825
826 global $CFG;
827
828 $currdir = $CFG->dataroot;
fe287429 829
2e6d4273 830 umask(0000);
831
6b174680 832 if (!file_exists($currdir)) {
2e6d4273 833 if (! mkdir($currdir, $CFG->directorypermissions)) {
6b174680 834 notify("ERROR: You need to create the directory $currdir with web server write access");
835 return false;
836 }
837 }
838
839 $dirarray = explode("/", $directory);
840
841 foreach ($dirarray as $dir) {
842 $currdir = "$currdir/$dir";
843 if (! file_exists($currdir)) {
2e6d4273 844 if (! mkdir($currdir, $CFG->directorypermissions)) {
6b174680 845 notify("ERROR: Could not find or create a directory ($currdir)");
846 return false;
847 }
feffa4e6 848 @chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
6b174680 849 }
850 }
851
852 return $currdir;
853}
854
ca4f8eb8 855function make_mod_upload_directory($courseid) {
9fa49e22 856/// Makes an upload directory for a particular module
ca4f8eb8 857 global $CFG;
858
859 if (! $moddata = make_upload_directory("$courseid/$CFG->moddata")) {
860 return false;
861 }
862
863 $strreadme = get_string("readme");
864
865 if (file_exists("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt")) {
866 copy("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt", "$moddata/$strreadme.txt");
867 } else {
868 copy("$CFG->dirroot/lang/en/docs/module_files.txt", "$moddata/$strreadme.txt");
869 }
870 return $moddata;
871}
872
6b174680 873
44e2d2bb 874function valid_uploaded_file($newfile) {
9fa49e22 875/// Returns current name of file on disk if true
9c9f7d77 876 if (empty($newfile)) {
877 return "";
878 }
44e2d2bb 879 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
880 return $newfile['tmp_name'];
881 } else {
882 return "";
883 }
884}
885
886function get_max_upload_file_size() {
9fa49e22 887/// Returns the maximum size for uploading files
44e2d2bb 888 if (! $filesize = ini_get("upload_max_filesize")) {
889 $filesize = "5M";
890 }
891 return get_real_size($filesize);
892}
893
774ab660 894function get_directory_list($rootdir, $excludefile="", $descend=true) {
9fa49e22 895/// Returns an array with all the filenames in
896/// all subdirectories, relative to the given rootdir.
897/// If excludefile is defined, then that file/directory is ignored
f9903ed0 898
899 $dirs = array();
900
44e2d2bb 901 $dir = opendir($rootdir);
f9903ed0 902
d897cae4 903 if (!$dir) {
904 notify("Error: unable to read this directory! : $rootdir");
905 return $dirs;
906 }
907
ca4f8eb8 908 while ($file = readdir($dir)) {
b35e8568 909 $firstchar = substr($file, 0, 1);
910 if ($firstchar == "." or $file == "CVS" or $file == $excludefile) {
911 continue;
912 }
913 $fullfile = $rootdir."/".$file;
914 if ($descend and filetype($fullfile) == "dir") {
915 $subdirs = get_directory_list($fullfile, $excludefile, $descend);
916 foreach ($subdirs as $subdir) {
917 $dirs[] = $file."/".$subdir;
f9903ed0 918 }
b35e8568 919 } else {
920 $dirs[] = $file;
f9903ed0 921 }
922 }
44e2d2bb 923 closedir($dir);
f9903ed0 924
774ab660 925 asort($dirs);
926
f9903ed0 927 return $dirs;
928}
929
989bfa9d 930function get_real_size($size=0) {
9fa49e22 931/// Converts numbers like 10M into bytes
989bfa9d 932 if (!$size) {
933 return 0;
934 }
935 $scan['MB'] = 1048576;
64efda84 936 $scan['Mb'] = 1048576;
989bfa9d 937 $scan['M'] = 1048576;
938 $scan['KB'] = 1024;
64efda84 939 $scan['Kb'] = 1024;
989bfa9d 940 $scan['K'] = 1024;
941
942 while (list($key) = each($scan)) {
943 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
944 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
945 break;
946 }
947 }
948 return $size;
949}
950
44e2d2bb 951function display_size($size) {
9fa49e22 952/// Converts bytes into display form
44e2d2bb 953 if ($size >= 1073741824) {
954 $size = round($size / 1073741824 * 10) / 10 . "Gb";
955 } else if ($size >= 1048576) {
956 $size = round($size / 1048576 * 10) / 10 . "Mb";
957 } else if ($size >= 1024) {
958 $size = round($size / 1024 * 10) / 10 . "Kb";
959 } else {
960 $size = $size . "b";
961 }
962 return $size;
963}
964
6b174680 965function clean_filename($string) {
9fa49e22 966/// Cleans a given filename by removing suspicious or troublesome characters
fc05fccb 967 $string = stripslashes($string);
6b174680 968 $string = eregi_replace("\.\.", "", $string);
5c219ea4 969 $string = eregi_replace("[^(-|[:alnum:]|\.)]", "_", $string);
6b174680 970 return eregi_replace("_+", "_", $string);
971}
972
973
1180c6dc 974/// STRING TRANSLATION ////////////////////////////////////////
975
4bfa92e7 976function current_language() {
9fa49e22 977/// Returns the code for the current language
3db3acfb 978 global $CFG, $USER, $SESSION;
4bfa92e7 979
3db3acfb 980 if (isset($SESSION->lang)) { // Session language can override other settings
981 return $SESSION->lang;
982
983 } else if (isset($USER->lang)) { // User language can override site language
4bfa92e7 984 return $USER->lang;
3db3acfb 985
4bfa92e7 986 } else {
987 return $CFG->lang;
988 }
989}
bcc83c41 990
9fa49e22 991function print_string($identifier, $module="", $a=NULL) {
992/// Given a string to translate - prints it out.
993 echo get_string($identifier, $module, $a);
994}
995
a83fded1 996function get_string($identifier, $module="", $a=NULL) {
9fa49e22 997/// Return the translated string specified by $identifier as
998/// for $module. Uses the same format files as STphp.
999/// $a is an object, string or number that can be used
1000/// within translation strings
1001///
1002/// eg "hello \$a->firstname \$a->lastname"
1003/// or "hello \$a"
1180c6dc 1004
4bfa92e7 1005 global $CFG;
1180c6dc 1006
4bfa92e7 1007 $lang = current_language();
1180c6dc 1008
058eec18 1009 if ($module == "") {
1010 $module = "moodle";
1180c6dc 1011 }
1012
058eec18 1013 $langpath = "$CFG->dirroot/lang";
1014 $langfile = "$langpath/$lang/$module.php";
1180c6dc 1015
b947c69a 1016 // Look for the string - if found then return it
1017
1018 if (file_exists($langfile)) {
1019 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1020 eval($result);
1021 return $resultstring;
1180c6dc 1022 }
1023 }
1024
b947c69a 1025 // If the preferred language was English we can abort now
1180c6dc 1026
b947c69a 1027 if ($lang == "en") {
1028 return "[[$identifier]]";
1029 }
1180c6dc 1030
b947c69a 1031 // Is a parent language defined? If so, try it.
1032
1033 if ($result = get_string_from_file("parentlanguage", "$langpath/$lang/moodle.php", "\$parentlang")) {
1034 eval($result);
1035 if (!empty($parentlang)) {
1036 $langfile = "$langpath/$parentlang/$module.php";
1037 if (file_exists($langfile)) {
1038 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1039 eval($result);
1040 return $resultstring;
1041 }
1180c6dc 1042 }
1043 }
1044 }
b947c69a 1045
1046 // Our only remaining option is to try English
1047
1048 $langfile = "$langpath/en/$module.php";
1049 if (!file_exists($langfile)) {
1050 return "ERROR: No lang file ($langpath/en/$module.php)!";
1051 }
1052 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1053 eval($result);
1054 return $resultstring;
1055 }
1056
1057 return "[[$identifier]]"; // Last resort
1180c6dc 1058}
1059
1060
1180c6dc 1061function get_string_from_file($identifier, $langfile, $destination) {
9fa49e22 1062/// This function is only used from get_string().
2b32bddd 1063
1064 static $strings; // Keep the strings cached in memory.
1065
1066 if (empty($strings[$langfile])) {
1067 include ($langfile);
1068 $strings[$langfile] = $string;
1069 } else {
1070 $string = &$strings[$langfile];
1071 }
1180c6dc 1072
1073 if (!isset ($string[$identifier])) {
1074 return false;
1075 }
1076
a83fded1 1077 return "$destination = sprintf(\"".$string[$identifier]."\");";
1180c6dc 1078}
f9903ed0 1079
1080
1a72314d 1081function get_list_of_languages() {
1082/// Returns a list of language codes and their full names
1083 global $CFG;
1084
984a8bf3 1085 $languages = array();
1086
1087 if (!empty($CFG->langlist)) { // use admin's list of languages
1088 $langlist = explode(',', $CFG->langlist);
1089 foreach ($langlist as $lang) {
1090 if (file_exists("$CFG->dirroot/lang/$lang/moodle.php")) {
1091 include("$CFG->dirroot/lang/$lang/moodle.php");
1092 $languages[$lang] = $string["thislanguage"]." ($lang)";
1093 unset($string);
1094 }
1095 }
1096 } else {
1097 if (!$langdirs = get_list_of_plugins("lang")) {
1098 return false;
1099 }
1100 foreach ($langdirs as $lang) {
1101 include("$CFG->dirroot/lang/$lang/moodle.php");
1102 $languages[$lang] = $string["thislanguage"]." ($lang)";
1103 unset($string);
1104 }
1a72314d 1105 }
1106
1a72314d 1107 return $languages;
1108}
1109
9bd2c874 1110function document_file($file, $include=true) {
1111/// Can include a given document file (depends on second
1112/// parameter) or just return info about it
1113
c9d4e6da 1114 global $CFG;
9bd2c874 1115
db356340 1116 $file = clean_filename($file);
1117
9bd2c874 1118 if (empty($file)) {
9bd2c874 1119 return false;
1120 }
1121
db356340 1122 $langs = array(current_language(), get_string("parentlanguage"), "en");
9bd2c874 1123
db356340 1124 foreach ($langs as $lang) {
1125 $info->filepath = "$CFG->dirroot/lang/$lang/docs/$file";
1126 $info->urlpath = "$CFG->wwwroot/lang/$lang/docs/$file";
9bd2c874 1127
db356340 1128 if (file_exists($info->filepath)) {
1129 if ($include) {
1130 include($info->filepath);
1131 }
1132 return $info;
0c106cd3 1133 }
9bd2c874 1134 }
1135
db356340 1136 return false;
9bd2c874 1137}
1138
1a72314d 1139
f9903ed0 1140/// ENCRYPTION ////////////////////////////////////////////////
1141
1142function rc4encrypt($data) {
1143 $password = "nfgjeingjk";
1144 return endecrypt($password, $data, "");
1145}
1146
1147function rc4decrypt($data) {
1148 $password = "nfgjeingjk";
1149 return endecrypt($password, $data, "de");
1150}
1151
1152function endecrypt ($pwd, $data, $case) {
9fa49e22 1153/// Based on a class by Mukul Sabharwal [mukulsabharwal@yahoo.com]
f9903ed0 1154
1155 if ($case == 'de') {
1156 $data = urldecode($data);
1157 }
1158
1159 $key[] = "";
1160 $box[] = "";
1161 $temp_swap = "";
1162 $pwd_length = 0;
1163
1164 $pwd_length = strlen($pwd);
1165
1166 for ($i = 0; $i <= 255; $i++) {
1167 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
1168 $box[$i] = $i;
1169 }
1170
1171 $x = 0;
1172
1173 for ($i = 0; $i <= 255; $i++) {
1174 $x = ($x + $box[$i] + $key[$i]) % 256;
1175 $temp_swap = $box[$i];
1176 $box[$i] = $box[$x];
1177 $box[$x] = $temp_swap;
1178 }
1179
1180 $temp = "";
1181 $k = "";
1182
1183 $cipherby = "";
1184 $cipher = "";
1185
1186 $a = 0;
1187 $j = 0;
1188
1189 for ($i = 0; $i < strlen($data); $i++) {
1190 $a = ($a + 1) % 256;
1191 $j = ($j + $box[$a]) % 256;
1192 $temp = $box[$a];
1193 $box[$a] = $box[$j];
1194 $box[$j] = $temp;
1195 $k = $box[(($box[$a] + $box[$j]) % 256)];
1196 $cipherby = ord(substr($data, $i, 1)) ^ $k;
1197 $cipher .= chr($cipherby);
1198 }
1199
1200 if ($case == 'de') {
1201 $cipher = urldecode(urlencode($cipher));
1202 } else {
1203 $cipher = urlencode($cipher);
1204 }
1205
1206 return $cipher;
1207}
1208
1209
9fa49e22 1210/// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
1e3e716f 1211
1d881d92 1212function get_list_of_plugins($plugin="mod") {
1213/// Lists plugin directories within some directory
1214
1215 global $CFG;
1216
1217 $basedir = opendir("$CFG->dirroot/$plugin");
1218 while ($dir = readdir($basedir)) {
b35e8568 1219 $firstchar = substr($dir, 0, 1);
1220 if ($firstchar == "." or $dir == "CVS") {
1d881d92 1221 continue;
1222 }
1223 if (filetype("$CFG->dirroot/$plugin/$dir") != "dir") {
1224 continue;
1225 }
1226 $plugins[] = $dir;
1227 }
1228 if ($plugins) {
1229 asort($plugins);
1230 }
1231 return $plugins;
1232}
1233
b0cb5e22 1234function check_php_version($version="4.1.0") {
9fa49e22 1235/// Returns true is the current version of PHP is greater that the specified one
b0cb5e22 1236 $minversion = intval(str_replace(".", "", $version));
1237 $curversion = intval(str_replace(".", "", phpversion()));
1238 return ($curversion >= $minversion);
1239}
1240
0095d5cd 1241function check_browser_version($brand="MSIE", $version=5.5) {
9fa49e22 1242/// Checks to see if is a browser matches the specified
1243/// brand and is equal or better version.
0095d5cd 1244
607809b3 1245 if (empty($_SERVER["HTTP_USER_AGENT"])) {
0095d5cd 1246 return false;
1247 }
607809b3 1248 $string = explode(";", $_SERVER["HTTP_USER_AGENT"]);
0095d5cd 1249 if (!isset($string[1])) {
1250 return false;
1251 }
1252 $string = explode(" ", trim($string[1]));
1253 if (!isset($string[0]) and !isset($string[1])) {
1254 return false;
1255 }
1256 if ($string[0] == $brand and (float)$string[1] >= $version ) {
1257 return true;
1258 }
1259 return false;
1260}
1261
c39c66a5 1262function ini_get_bool($ini_get_arg) {
1263/// This function makes the return value of ini_get consistent if you are
1264/// setting server directives through the .htaccess file in apache.
1265/// Current behavior for value set from php.ini On = 1, Off = [blank]
1266/// Current behavior for value set from .htaccess On = On, Off = Off
1267/// Contributed by jdell@unr.edu
1268
1269 $temp = ini_get($ini_get_arg);
1270
1271 if ($temp == "1" or strtolower($temp) == "on") {
1272 return true;
1273 }
1274 return false;
1275}
1276
0095d5cd 1277function can_use_richtext_editor() {
9fa49e22 1278/// Is the richedit editor enabled?
0095d5cd 1279 global $USER, $CFG;
ce78926d 1280 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
7ce20f09 1281 return check_browser_version("MSIE", 5.5);
1282 }
1283 return false;
0095d5cd 1284}
1285
74944b73 1286function check_gd_version() {
9fa49e22 1287/// Hack to find out the GD version by parsing phpinfo output
aa095969 1288 $gdversion = 0;
74944b73 1289
aa095969 1290 if (function_exists('gd_info')){
1291 $gd_info = gd_info();
3ee23682 1292 if (substr_count($gd_info['GD Version'], "2.")) {
aa095969 1293 $gdversion = 2;
3ee23682 1294 } else if (substr_count($gd_info['GD Version'], "1.")) {
1295 $gdversion = 1;
aa095969 1296 }
3ee23682 1297
aa095969 1298 } else {
1299 ob_start();
1300 phpinfo(8);
1301 $phpinfo = ob_get_contents();
1302 ob_end_clean();
74944b73 1303
aa095969 1304 $phpinfo = explode("\n",$phpinfo);
74944b73 1305
92a4b0f1 1306
aa095969 1307 foreach ($phpinfo as $text) {
1308 $parts = explode('</td>',$text);
1309 foreach ($parts as $key => $val) {
1310 $parts[$key] = trim(strip_tags($val));
1311 }
1312 if ($parts[0] == "GD Version") {
1313 if (substr_count($parts[1], "2.0")) {
1314 $parts[1] = "2.0";
1315 }
1316 $gdversion = intval($parts[1]);
92a4b0f1 1317 }
74944b73 1318 }
1319 }
1320
1321 return $gdversion; // 1, 2 or 0
1322}
f9903ed0 1323
0095d5cd 1324
9fa49e22 1325function moodle_needs_upgrading() {
1326/// Checks version numbers of Main code and all modules to see
1327/// if there are any mismatches ... returns true or false
1328 global $CFG;
1329
1330 include_once("$CFG->dirroot/version.php"); # defines $version and upgrades
1331 if ($CFG->version) {
1332 if ($version > $CFG->version) {
1333 return true;
1334 }
1335 if ($mods = get_list_of_plugins("mod")) {
1336 foreach ($mods as $mod) {
1337 $fullmod = "$CFG->dirroot/mod/$mod";
1338 unset($module);
1079c8a8 1339 if (!is_readable("$fullmod/version.php")) {
1340 notify("Module '$mod' is not readable - check permissions");
1341 continue;
1342 }
9fa49e22 1343 include_once("$fullmod/version.php"); # defines $module with version etc
1344 if ($currmodule = get_record("modules", "name", $mod)) {
1345 if ($module->version > $currmodule->version) {
1346 return true;
1347 }
1348 }
1349 }
1350 }
1351 } else {
1352 return true;
1353 }
1354 return false;
1355}
1356
1357
1358/// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
1359
7d6cac54 1360function moodle_strtolower ($string, $encoding='') {
1361/// Converts string to lowercase using most compatible function available
1362 if (function_exists('mb_strtolower')) {
1363 if($encoding===''){
1364 return mb_strtolower($string); //use multibyte support with default encoding
1365 } else {
dbe0be00 1366 return mb_strtolower($string,$encoding); //use given encoding
7d6cac54 1367 }
1368 } else {
1369 return strtolower($string); // use common function what rely on current locale setting
1370 }
1371}
1372
9fa49e22 1373function count_words($string) {
1374/// Words are defined as things between whitespace
1375 $string = strip_tags($string);
1376 return count(preg_split("/\w\b/", $string)) - 1;
1377}
1378
1d881d92 1379function random_string ($length=15) {
1380 $pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1381 $pool .= "abcdefghijklmnopqrstuvwxyz";
1382 $pool .= "0123456789";
1383 $poollen = strlen($pool);
1384 mt_srand ((double) microtime() * 1000000);
1385 $string = "";
1386 for ($i = 0; $i < $length; $i++) {
1387 $string .= substr($pool, (mt_rand()%($poollen)), 1);
1388 }
1389 return $string;
1390}
1391
1392
9fa49e22 1393function getweek ($startdate, $thedate) {
1394/// Given dates in seconds, how many weeks is the date from startdate
1395/// The first week is 1, the second 2 etc ...
1396
1397 if ($thedate < $startdate) { // error
1398 return 0;
1399 }
1400
1401 return floor(($thedate - $startdate) / 604800.0) + 1;
1402}
1403
1404function generate_password($maxlen=10) {
1405/// returns a randomly generated password of length $maxlen. inspired by
1406/// http://www.phpbuilder.com/columns/jesus19990502.php3
1407
1408 global $CFG;
1409
1410 $fillers = "1234567890!$-+";
1411 $wordlist = file($CFG->wordlist);
1412
1413 srand((double) microtime() * 1000000);
1414 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1415 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1416 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
1417
1418 return substr($word1 . $filler1 . $word2, 0, $maxlen);
1419}
1420
1421function format_float($num, $places=0) {
1422/// Given a float, prints it nicely
1423 return sprintf("%.$places"."f", $num);
1424}
1425
ee0e5d57 1426function swapshuffle($array) {
1427/// Given a simple array, this shuffles it up just like shuffle()
1428/// Unlike PHP's shuffle() ihis function works on any machine.
1429
1430 srand ((double) microtime() * 10000000);
1431 $last = count($array) - 1;
1432 for ($i=0;$i<=$last;$i++) {
1433 $from = rand(0,$last);
1434 $curr = $array[$i];
1435 $array[$i] = $array[$from];
1436 $array[$from] = $curr;
1437 }
1438 return $array;
1439}
1440
bc700e65 1441function swapshuffle_assoc($array) {
1442/// Like swapshuffle, but works on associative arrays
1443
1444 $newkeys = swapshuffle(array_keys($array));
1445 foreach ($newkeys as $newkey) {
1446 $newarray[$newkey] = $array[$newkey];
1447 }
1448 return $newarray;
1449}
1450
ee0e5d57 1451function draw_rand_array($array, $draws) {
1452/// Given an arbitrary array, and a number of draws,
1453/// this function returns an array with that amount
1454/// of items. The indexes are retained.
1455
1456 srand ((double) microtime() * 10000000);
1457
1458 $return = array();
1459
1460 $last = count($array);
1461
1462 if ($draws > $last) {
1463 $draws = $last;
1464 }
1465
1466 while ($draws > 0) {
1467 $last--;
1468
1469 $keys = array_keys($array);
1470 $rand = rand(0, $last);
1471
1472 $return[$keys[$rand]] = $array[$keys[$rand]];
1473 unset($array[$keys[$rand]]);
1474
1475 $draws--;
1476 }
1477
1478 return $return;
1479}
9fa49e22 1480
f5e82bc7 1481function microtime_diff($a, $b) {
1482 list($a_dec, $a_sec) = explode(" ", $a);
1483 list($b_dec, $b_sec) = explode(" ", $b);
1484 return $b_sec - $a_sec + $b_dec - $a_dec;
1485}
1486
0095d5cd 1487
9d5b689c 1488// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
f9903ed0 1489?>