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