New strings and help pages for file upload restrictions
[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
8a9e3fd7 403function isteacher($courseid, $userid=0) {
9fa49e22 404/// Is the user a teacher or admin?
f9903ed0 405 global $USER;
406
d115a57f 407 if (isadmin($userid)) { // admins can do anything the teacher can
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;
503
504 $cookiename = "MOODLEID{$CFG->prefix}";
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
4fe04be0 518 $cookiename = "MOODLEID{$CFG->prefix}";
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
872 $mail->Host = "$CFG->smtphosts"; // specify main and backup servers
9f58537a 873
874 if ($CFG->smtpuser) { // Use SMTP authentication
875 $mail->SMTPAuth = true;
876 $mail->Username = $CFG->smtpuser;
877 $mail->Password = $CFG->smtppass;
878 }
7f86ce17 879 } else {
1e411ffc 880 $mail->IsMail(); // use PHP mail() = sendmail
7f86ce17 881 }
f9903ed0 882
2b97bd71 883 $adminuser = get_admin();
884
885 $mail->Sender = "$adminuser->email";
886
136dabd8 887 $mail->From = "$from->email";
888 $mail->FromName = "$from->firstname $from->lastname";
889 $mail->Subject = stripslashes($subject);
f9903ed0 890
6b174680 891 $mail->AddAddress("$user->email", "$user->firstname $user->lastname");
f9903ed0 892
f9903ed0 893 $mail->WordWrap = 70; // set word wrap
f9903ed0 894
136dabd8 895 if ($messagehtml) {
896 $mail->IsHTML(true);
125898af 897 $mail->Encoding = "quoted-printable"; // Encoding to use
136dabd8 898 $mail->Body = $messagehtml;
78681899 899 $mail->AltBody = "\n$messagetext\n";
136dabd8 900 } else {
901 $mail->IsHTML(false);
78681899 902 $mail->Body = "\n$messagetext\n";
f9903ed0 903 }
904
136dabd8 905 if ($attachment && $attachname) {
906 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
4216daa6 907 $mail->AddAddress("$adminuser->email", "$adminuser->firstname $adminuser->lastname");
908 $mail->AddStringAttachment("Error in attachment. User attempted to attach a filename with a unsafe name.", "error.txt", "8bit", "text/plain");
136dabd8 909 } else {
910 include_once("$CFG->dirroot/files/mimetypes.php");
911 $mimetype = mimeinfo("type", $attachname);
912 $mail->AddAttachment("$CFG->dataroot/$attachment", "$attachname", "base64", "$mimetype");
913 }
f9903ed0 914 }
915
136dabd8 916 if ($mail->Send()) {
917 return true;
918 } else {
4216daa6 919 echo "ERROR: $mail->ErrorInfo\n";
920 $site = get_site();
921 add_to_log($site->id, "library", "mailer", $_SERVER["REQUEST_URI"], "ERROR: $mail->ErrorInfo");
f9903ed0 922 return false;
923 }
f9903ed0 924}
925
1d881d92 926function reset_password_and_mail($user) {
927
928 global $CFG;
929
930 $site = get_site();
931 $from = get_admin();
932
933 $newpassword = generate_password();
934
935 if (! set_field("user", "password", md5($newpassword), "id", $user->id) ) {
936 error("Could not set user password!");
937 }
938
939 $a->firstname = $user->firstname;
940 $a->sitename = $site->fullname;
941 $a->username = $user->username;
942 $a->newpassword = $newpassword;
943 $a->link = "$CFG->wwwroot/login/change_password.php";
944 $a->signoff = "$from->firstname $from->lastname ($from->email)";
945
946 $message = get_string("newpasswordtext", "", $a);
947
948 $subject = "$site->fullname: ".get_string("changedpassword");
949
950 return email_to_user($user, $from, $subject, $message);
951
952}
953
954function send_confirmation_email($user) {
955
956 global $CFG;
957
958 $site = get_site();
959 $from = get_admin();
960
961 $data->firstname = $user->firstname;
962 $data->sitename = $site->fullname;
963 $data->link = "$CFG->wwwroot/login/confirm.php?p=$user->secret&s=$user->username";
964 $data->admin = "$from->firstname $from->lastname ($from->email)";
965
966 $message = get_string("emailconfirmation", "", $data);
eb347b6b 967 $subject = get_string("emailconfirmationsubject", "", $site->fullname);
1d881d92 968
969 return email_to_user($user, $from, $subject, $message);
970
971}
972
eb347b6b 973function send_password_change_confirmation_email($user) {
974
975 global $CFG;
976
977 $site = get_site();
978 $from = get_admin();
979
980 $data->firstname = $user->firstname;
981 $data->sitename = $site->fullname;
982 $data->link = "$CFG->wwwroot/login/forgot_password.php?p=$user->secret&s=$user->username";
983 $data->admin = "$from->firstname $from->lastname ($from->email)";
984
985 $message = get_string("emailpasswordconfirmation", "", $data);
986 $subject = get_string("emailpasswordconfirmationsubject", "", $site->fullname);
987
988 return email_to_user($user, $from, $subject, $message);
989
990}
991
992
1d881d92 993
136dabd8 994
f9903ed0 995/// FILE HANDLING /////////////////////////////////////////////
996
6b174680 997function make_upload_directory($directory) {
9fa49e22 998/// $directory = a string of directory names under $CFG->dataroot
999/// eg stuff/assignment/1
1000/// Returns full directory if successful, false if not
6b174680 1001
1002 global $CFG;
1003
1004 $currdir = $CFG->dataroot;
fe287429 1005
2e6d4273 1006 umask(0000);
1007
6b174680 1008 if (!file_exists($currdir)) {
2e6d4273 1009 if (! mkdir($currdir, $CFG->directorypermissions)) {
6b174680 1010 notify("ERROR: You need to create the directory $currdir with web server write access");
1011 return false;
1012 }
1013 }
1014
1015 $dirarray = explode("/", $directory);
1016
1017 foreach ($dirarray as $dir) {
1018 $currdir = "$currdir/$dir";
1019 if (! file_exists($currdir)) {
2e6d4273 1020 if (! mkdir($currdir, $CFG->directorypermissions)) {
6b174680 1021 notify("ERROR: Could not find or create a directory ($currdir)");
1022 return false;
1023 }
feffa4e6 1024 @chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
6b174680 1025 }
1026 }
1027
1028 return $currdir;
1029}
1030
ca4f8eb8 1031function make_mod_upload_directory($courseid) {
9fa49e22 1032/// Makes an upload directory for a particular module
ca4f8eb8 1033 global $CFG;
1034
1035 if (! $moddata = make_upload_directory("$courseid/$CFG->moddata")) {
1036 return false;
1037 }
1038
1039 $strreadme = get_string("readme");
1040
1041 if (file_exists("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt")) {
1042 copy("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt", "$moddata/$strreadme.txt");
1043 } else {
1044 copy("$CFG->dirroot/lang/en/docs/module_files.txt", "$moddata/$strreadme.txt");
1045 }
1046 return $moddata;
1047}
1048
6b174680 1049
44e2d2bb 1050function valid_uploaded_file($newfile) {
9fa49e22 1051/// Returns current name of file on disk if true
9c9f7d77 1052 if (empty($newfile)) {
1053 return "";
1054 }
44e2d2bb 1055 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
1056 return $newfile['tmp_name'];
1057 } else {
1058 return "";
1059 }
1060}
1061
1062function get_max_upload_file_size() {
9fa49e22 1063/// Returns the maximum size for uploading files
44e2d2bb 1064 if (! $filesize = ini_get("upload_max_filesize")) {
1065 $filesize = "5M";
1066 }
1067 return get_real_size($filesize);
1068}
1069
774ab660 1070function get_directory_list($rootdir, $excludefile="", $descend=true) {
9fa49e22 1071/// Returns an array with all the filenames in
1072/// all subdirectories, relative to the given rootdir.
1073/// If excludefile is defined, then that file/directory is ignored
f9903ed0 1074
1075 $dirs = array();
f9903ed0 1076
12407705 1077 if (!is_dir($rootdir)) {
1078 return $dirs;
1079 }
1080
487c1711 1081 if (!$dir = opendir($rootdir)) {
d897cae4 1082 return $dirs;
1083 }
1084
ca4f8eb8 1085 while ($file = readdir($dir)) {
b35e8568 1086 $firstchar = substr($file, 0, 1);
1087 if ($firstchar == "." or $file == "CVS" or $file == $excludefile) {
1088 continue;
1089 }
1090 $fullfile = $rootdir."/".$file;
1091 if ($descend and filetype($fullfile) == "dir") {
1092 $subdirs = get_directory_list($fullfile, $excludefile, $descend);
1093 foreach ($subdirs as $subdir) {
1094 $dirs[] = $file."/".$subdir;
f9903ed0 1095 }
b35e8568 1096 } else {
1097 $dirs[] = $file;
f9903ed0 1098 }
1099 }
44e2d2bb 1100 closedir($dir);
f9903ed0 1101
774ab660 1102 asort($dirs);
1103
f9903ed0 1104 return $dirs;
1105}
1106
989bfa9d 1107function get_real_size($size=0) {
9fa49e22 1108/// Converts numbers like 10M into bytes
989bfa9d 1109 if (!$size) {
1110 return 0;
1111 }
1112 $scan['MB'] = 1048576;
64efda84 1113 $scan['Mb'] = 1048576;
989bfa9d 1114 $scan['M'] = 1048576;
1115 $scan['KB'] = 1024;
64efda84 1116 $scan['Kb'] = 1024;
989bfa9d 1117 $scan['K'] = 1024;
1118
1119 while (list($key) = each($scan)) {
1120 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1121 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1122 break;
1123 }
1124 }
1125 return $size;
1126}
1127
44e2d2bb 1128function display_size($size) {
9fa49e22 1129/// Converts bytes into display form
44e2d2bb 1130 if ($size >= 1073741824) {
1131 $size = round($size / 1073741824 * 10) / 10 . "Gb";
1132 } else if ($size >= 1048576) {
1133 $size = round($size / 1048576 * 10) / 10 . "Mb";
1134 } else if ($size >= 1024) {
1135 $size = round($size / 1024 * 10) / 10 . "Kb";
1136 } else {
1137 $size = $size . "b";
1138 }
1139 return $size;
1140}
1141
6b174680 1142function clean_filename($string) {
9fa49e22 1143/// Cleans a given filename by removing suspicious or troublesome characters
fc05fccb 1144 $string = stripslashes($string);
6b174680 1145 $string = eregi_replace("\.\.", "", $string);
5c219ea4 1146 $string = eregi_replace("[^(-|[:alnum:]|\.)]", "_", $string);
6b174680 1147 return eregi_replace("_+", "_", $string);
1148}
1149
1150
1180c6dc 1151/// STRING TRANSLATION ////////////////////////////////////////
1152
4bfa92e7 1153function current_language() {
9fa49e22 1154/// Returns the code for the current language
3db3acfb 1155 global $CFG, $USER, $SESSION;
4bfa92e7 1156
3db3acfb 1157 if (isset($SESSION->lang)) { // Session language can override other settings
1158 return $SESSION->lang;
1159
1160 } else if (isset($USER->lang)) { // User language can override site language
4bfa92e7 1161 return $USER->lang;
3db3acfb 1162
4bfa92e7 1163 } else {
1164 return $CFG->lang;
1165 }
1166}
bcc83c41 1167
9fa49e22 1168function print_string($identifier, $module="", $a=NULL) {
1169/// Given a string to translate - prints it out.
1170 echo get_string($identifier, $module, $a);
1171}
1172
a83fded1 1173function get_string($identifier, $module="", $a=NULL) {
9fa49e22 1174/// Return the translated string specified by $identifier as
1175/// for $module. Uses the same format files as STphp.
1176/// $a is an object, string or number that can be used
1177/// within translation strings
1178///
1179/// eg "hello \$a->firstname \$a->lastname"
1180/// or "hello \$a"
1180c6dc 1181
4bfa92e7 1182 global $CFG;
1180c6dc 1183
4bfa92e7 1184 $lang = current_language();
1180c6dc 1185
058eec18 1186 if ($module == "") {
1187 $module = "moodle";
1180c6dc 1188 }
1189
058eec18 1190 $langpath = "$CFG->dirroot/lang";
1191 $langfile = "$langpath/$lang/$module.php";
1180c6dc 1192
b947c69a 1193 // Look for the string - if found then return it
1194
1195 if (file_exists($langfile)) {
1196 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1197 eval($result);
1198 return $resultstring;
1180c6dc 1199 }
1200 }
1201
b947c69a 1202 // If the preferred language was English we can abort now
1180c6dc 1203
b947c69a 1204 if ($lang == "en") {
1205 return "[[$identifier]]";
1206 }
1180c6dc 1207
b947c69a 1208 // Is a parent language defined? If so, try it.
1209
1210 if ($result = get_string_from_file("parentlanguage", "$langpath/$lang/moodle.php", "\$parentlang")) {
1211 eval($result);
1212 if (!empty($parentlang)) {
1213 $langfile = "$langpath/$parentlang/$module.php";
1214 if (file_exists($langfile)) {
1215 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1216 eval($result);
1217 return $resultstring;
1218 }
1180c6dc 1219 }
1220 }
1221 }
b947c69a 1222
1223 // Our only remaining option is to try English
1224
1225 $langfile = "$langpath/en/$module.php";
1226 if (!file_exists($langfile)) {
1227 return "ERROR: No lang file ($langpath/en/$module.php)!";
1228 }
1229 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1230 eval($result);
1231 return $resultstring;
1232 }
1233
1234 return "[[$identifier]]"; // Last resort
1180c6dc 1235}
1236
1237
1180c6dc 1238function get_string_from_file($identifier, $langfile, $destination) {
9fa49e22 1239/// This function is only used from get_string().
2b32bddd 1240
1241 static $strings; // Keep the strings cached in memory.
1242
1243 if (empty($strings[$langfile])) {
1244 include ($langfile);
1245 $strings[$langfile] = $string;
1246 } else {
1247 $string = &$strings[$langfile];
1248 }
1180c6dc 1249
1250 if (!isset ($string[$identifier])) {
1251 return false;
1252 }
1253
a83fded1 1254 return "$destination = sprintf(\"".$string[$identifier]."\");";
1180c6dc 1255}
f9903ed0 1256
1257
1a72314d 1258function get_list_of_languages() {
1259/// Returns a list of language codes and their full names
1260 global $CFG;
1261
984a8bf3 1262 $languages = array();
1263
1264 if (!empty($CFG->langlist)) { // use admin's list of languages
1265 $langlist = explode(',', $CFG->langlist);
1266 foreach ($langlist as $lang) {
1267 if (file_exists("$CFG->dirroot/lang/$lang/moodle.php")) {
1268 include("$CFG->dirroot/lang/$lang/moodle.php");
1269 $languages[$lang] = $string["thislanguage"]." ($lang)";
1270 unset($string);
1271 }
1272 }
1273 } else {
1274 if (!$langdirs = get_list_of_plugins("lang")) {
1275 return false;
1276 }
1277 foreach ($langdirs as $lang) {
1278 include("$CFG->dirroot/lang/$lang/moodle.php");
1279 $languages[$lang] = $string["thislanguage"]." ($lang)";
1280 unset($string);
1281 }
1a72314d 1282 }
1283
1a72314d 1284 return $languages;
1285}
1286
5833a6c8 1287function get_list_of_countries() {
1288/// Returns a list of country names in the current language
1289 global $CFG, $USER;
1290
1291 $lang = current_language();
1292
1293 if (!file_exists("$CFG->dirroot/lang/$lang/countries.php")) {
aa3eb050 1294 if ($parentlang = get_string("parentlanguage")) {
1295 if (file_exists("$CFG->dirroot/lang/$parentlang/countries.php")) {
1296 $lang = $parentlang;
1297 } else {
1298 $lang = "en"; // countries.php must exist in this pack
1299 }
1300 } else {
1301 $lang = "en"; // countries.php must exist in this pack
1302 }
5833a6c8 1303 }
1304
1305 include("$CFG->dirroot/lang/$lang/countries.php");
1306
1307 asort($string);
1308
1309 return $string;
1310}
1311
9bd2c874 1312function document_file($file, $include=true) {
1313/// Can include a given document file (depends on second
1314/// parameter) or just return info about it
1315
c9d4e6da 1316 global $CFG;
9bd2c874 1317
db356340 1318 $file = clean_filename($file);
1319
9bd2c874 1320 if (empty($file)) {
9bd2c874 1321 return false;
1322 }
1323
db356340 1324 $langs = array(current_language(), get_string("parentlanguage"), "en");
9bd2c874 1325
db356340 1326 foreach ($langs as $lang) {
1327 $info->filepath = "$CFG->dirroot/lang/$lang/docs/$file";
1328 $info->urlpath = "$CFG->wwwroot/lang/$lang/docs/$file";
9bd2c874 1329
db356340 1330 if (file_exists($info->filepath)) {
1331 if ($include) {
1332 include($info->filepath);
1333 }
1334 return $info;
0c106cd3 1335 }
9bd2c874 1336 }
1337
db356340 1338 return false;
9bd2c874 1339}
1340
1a72314d 1341
f9903ed0 1342/// ENCRYPTION ////////////////////////////////////////////////
1343
1344function rc4encrypt($data) {
1345 $password = "nfgjeingjk";
1346 return endecrypt($password, $data, "");
1347}
1348
1349function rc4decrypt($data) {
1350 $password = "nfgjeingjk";
1351 return endecrypt($password, $data, "de");
1352}
1353
1354function endecrypt ($pwd, $data, $case) {
9fa49e22 1355/// Based on a class by Mukul Sabharwal [mukulsabharwal@yahoo.com]
f9903ed0 1356
1357 if ($case == 'de') {
1358 $data = urldecode($data);
1359 }
1360
1361 $key[] = "";
1362 $box[] = "";
1363 $temp_swap = "";
1364 $pwd_length = 0;
1365
1366 $pwd_length = strlen($pwd);
1367
1368 for ($i = 0; $i <= 255; $i++) {
1369 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
1370 $box[$i] = $i;
1371 }
1372
1373 $x = 0;
1374
1375 for ($i = 0; $i <= 255; $i++) {
1376 $x = ($x + $box[$i] + $key[$i]) % 256;
1377 $temp_swap = $box[$i];
1378 $box[$i] = $box[$x];
1379 $box[$x] = $temp_swap;
1380 }
1381
1382 $temp = "";
1383 $k = "";
1384
1385 $cipherby = "";
1386 $cipher = "";
1387
1388 $a = 0;
1389 $j = 0;
1390
1391 for ($i = 0; $i < strlen($data); $i++) {
1392 $a = ($a + 1) % 256;
1393 $j = ($j + $box[$a]) % 256;
1394 $temp = $box[$a];
1395 $box[$a] = $box[$j];
1396 $box[$j] = $temp;
1397 $k = $box[(($box[$a] + $box[$j]) % 256)];
1398 $cipherby = ord(substr($data, $i, 1)) ^ $k;
1399 $cipher .= chr($cipherby);
1400 }
1401
1402 if ($case == 'de') {
1403 $cipher = urldecode(urlencode($cipher));
1404 } else {
1405 $cipher = urlencode($cipher);
1406 }
1407
1408 return $cipher;
1409}
1410
1411
9fa49e22 1412/// ENVIRONMENT CHECKING ////////////////////////////////////////////////////////////
1e3e716f 1413
1d881d92 1414function get_list_of_plugins($plugin="mod") {
1415/// Lists plugin directories within some directory
1416
1417 global $CFG;
1418
1419 $basedir = opendir("$CFG->dirroot/$plugin");
1420 while ($dir = readdir($basedir)) {
b35e8568 1421 $firstchar = substr($dir, 0, 1);
bb9cf93d 1422 if ($firstchar == "." or $dir == "CVS" or $dir == "_vti_cnf") {
1d881d92 1423 continue;
1424 }
1425 if (filetype("$CFG->dirroot/$plugin/$dir") != "dir") {
1426 continue;
1427 }
1428 $plugins[] = $dir;
1429 }
1430 if ($plugins) {
1431 asort($plugins);
1432 }
1433 return $plugins;
1434}
1435
b0cb5e22 1436function check_php_version($version="4.1.0") {
9fa49e22 1437/// Returns true is the current version of PHP is greater that the specified one
b0cb5e22 1438 $minversion = intval(str_replace(".", "", $version));
1439 $curversion = intval(str_replace(".", "", phpversion()));
1440 return ($curversion >= $minversion);
1441}
1442
0095d5cd 1443function check_browser_version($brand="MSIE", $version=5.5) {
9fa49e22 1444/// Checks to see if is a browser matches the specified
1445/// brand and is equal or better version.
0095d5cd 1446
607809b3 1447 if (empty($_SERVER["HTTP_USER_AGENT"])) {
0095d5cd 1448 return false;
1449 }
607809b3 1450 $string = explode(";", $_SERVER["HTTP_USER_AGENT"]);
0095d5cd 1451 if (!isset($string[1])) {
1452 return false;
1453 }
1454 $string = explode(" ", trim($string[1]));
1455 if (!isset($string[0]) and !isset($string[1])) {
1456 return false;
1457 }
1458 if ($string[0] == $brand and (float)$string[1] >= $version ) {
1459 return true;
1460 }
1461 return false;
1462}
1463
c39c66a5 1464function ini_get_bool($ini_get_arg) {
1465/// This function makes the return value of ini_get consistent if you are
1466/// setting server directives through the .htaccess file in apache.
1467/// Current behavior for value set from php.ini On = 1, Off = [blank]
1468/// Current behavior for value set from .htaccess On = On, Off = Off
1469/// Contributed by jdell@unr.edu
1470
1471 $temp = ini_get($ini_get_arg);
1472
1473 if ($temp == "1" or strtolower($temp) == "on") {
1474 return true;
1475 }
1476 return false;
1477}
1478
0095d5cd 1479function can_use_richtext_editor() {
9fa49e22 1480/// Is the richedit editor enabled?
0095d5cd 1481 global $USER, $CFG;
ce78926d 1482 if (!empty($USER->htmleditor) and !empty($CFG->htmleditor)) {
7ce20f09 1483 return check_browser_version("MSIE", 5.5);
1484 }
1485 return false;
0095d5cd 1486}
1487
74944b73 1488function check_gd_version() {
9fa49e22 1489/// Hack to find out the GD version by parsing phpinfo output
aa095969 1490 $gdversion = 0;
74944b73 1491
aa095969 1492 if (function_exists('gd_info')){
1493 $gd_info = gd_info();
3ee23682 1494 if (substr_count($gd_info['GD Version'], "2.")) {
aa095969 1495 $gdversion = 2;
3ee23682 1496 } else if (substr_count($gd_info['GD Version'], "1.")) {
1497 $gdversion = 1;
aa095969 1498 }
3ee23682 1499
aa095969 1500 } else {
1501 ob_start();
1502 phpinfo(8);
1503 $phpinfo = ob_get_contents();
1504 ob_end_clean();
74944b73 1505
aa095969 1506 $phpinfo = explode("\n",$phpinfo);
74944b73 1507
92a4b0f1 1508
aa095969 1509 foreach ($phpinfo as $text) {
1510 $parts = explode('</td>',$text);
1511 foreach ($parts as $key => $val) {
1512 $parts[$key] = trim(strip_tags($val));
1513 }
1514 if ($parts[0] == "GD Version") {
1515 if (substr_count($parts[1], "2.0")) {
1516 $parts[1] = "2.0";
1517 }
1518 $gdversion = intval($parts[1]);
92a4b0f1 1519 }
74944b73 1520 }
1521 }
1522
1523 return $gdversion; // 1, 2 or 0
1524}
f9903ed0 1525
0095d5cd 1526
9fa49e22 1527function moodle_needs_upgrading() {
1528/// Checks version numbers of Main code and all modules to see
1529/// if there are any mismatches ... returns true or false
1530 global $CFG;
1531
1532 include_once("$CFG->dirroot/version.php"); # defines $version and upgrades
1533 if ($CFG->version) {
1534 if ($version > $CFG->version) {
1535 return true;
1536 }
1537 if ($mods = get_list_of_plugins("mod")) {
1538 foreach ($mods as $mod) {
1539 $fullmod = "$CFG->dirroot/mod/$mod";
1540 unset($module);
1079c8a8 1541 if (!is_readable("$fullmod/version.php")) {
1542 notify("Module '$mod' is not readable - check permissions");
1543 continue;
1544 }
9fa49e22 1545 include_once("$fullmod/version.php"); # defines $module with version etc
1546 if ($currmodule = get_record("modules", "name", $mod)) {
1547 if ($module->version > $currmodule->version) {
1548 return true;
1549 }
1550 }
1551 }
1552 }
1553 } else {
1554 return true;
1555 }
1556 return false;
1557}
1558
1559
1560/// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
1561
7d6cac54 1562function moodle_strtolower ($string, $encoding='') {
1563/// Converts string to lowercase using most compatible function available
1564 if (function_exists('mb_strtolower')) {
1565 if($encoding===''){
1566 return mb_strtolower($string); //use multibyte support with default encoding
1567 } else {
dbe0be00 1568 return mb_strtolower($string,$encoding); //use given encoding
7d6cac54 1569 }
1570 } else {
1571 return strtolower($string); // use common function what rely on current locale setting
1572 }
1573}
1574
9fa49e22 1575function count_words($string) {
1576/// Words are defined as things between whitespace
1577 $string = strip_tags($string);
1578 return count(preg_split("/\w\b/", $string)) - 1;
1579}
1580
1d881d92 1581function random_string ($length=15) {
1582 $pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
1583 $pool .= "abcdefghijklmnopqrstuvwxyz";
1584 $pool .= "0123456789";
1585 $poollen = strlen($pool);
1586 mt_srand ((double) microtime() * 1000000);
1587 $string = "";
1588 for ($i = 0; $i < $length; $i++) {
1589 $string .= substr($pool, (mt_rand()%($poollen)), 1);
1590 }
1591 return $string;
1592}
1593
1594
9fa49e22 1595function getweek ($startdate, $thedate) {
1596/// Given dates in seconds, how many weeks is the date from startdate
1597/// The first week is 1, the second 2 etc ...
1598
1599 if ($thedate < $startdate) { // error
1600 return 0;
1601 }
1602
1603 return floor(($thedate - $startdate) / 604800.0) + 1;
1604}
1605
1606function generate_password($maxlen=10) {
1607/// returns a randomly generated password of length $maxlen. inspired by
1608/// http://www.phpbuilder.com/columns/jesus19990502.php3
1609
1610 global $CFG;
1611
1612 $fillers = "1234567890!$-+";
1613 $wordlist = file($CFG->wordlist);
1614
1615 srand((double) microtime() * 1000000);
1616 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1617 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1618 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
1619
1620 return substr($word1 . $filler1 . $word2, 0, $maxlen);
1621}
1622
1623function format_float($num, $places=0) {
1624/// Given a float, prints it nicely
1625 return sprintf("%.$places"."f", $num);
1626}
1627
ee0e5d57 1628function swapshuffle($array) {
1629/// Given a simple array, this shuffles it up just like shuffle()
1630/// Unlike PHP's shuffle() ihis function works on any machine.
1631
1632 srand ((double) microtime() * 10000000);
1633 $last = count($array) - 1;
1634 for ($i=0;$i<=$last;$i++) {
1635 $from = rand(0,$last);
1636 $curr = $array[$i];
1637 $array[$i] = $array[$from];
1638 $array[$from] = $curr;
1639 }
1640 return $array;
1641}
1642
bc700e65 1643function swapshuffle_assoc($array) {
1644/// Like swapshuffle, but works on associative arrays
1645
1646 $newkeys = swapshuffle(array_keys($array));
1647 foreach ($newkeys as $newkey) {
1648 $newarray[$newkey] = $array[$newkey];
1649 }
1650 return $newarray;
1651}
1652
ee0e5d57 1653function draw_rand_array($array, $draws) {
1654/// Given an arbitrary array, and a number of draws,
1655/// this function returns an array with that amount
1656/// of items. The indexes are retained.
1657
1658 srand ((double) microtime() * 10000000);
1659
1660 $return = array();
1661
1662 $last = count($array);
1663
1664 if ($draws > $last) {
1665 $draws = $last;
1666 }
1667
1668 while ($draws > 0) {
1669 $last--;
1670
1671 $keys = array_keys($array);
1672 $rand = rand(0, $last);
1673
1674 $return[$keys[$rand]] = $array[$keys[$rand]];
1675 unset($array[$keys[$rand]]);
1676
1677 $draws--;
1678 }
1679
1680 return $return;
1681}
9fa49e22 1682
f5e82bc7 1683function microtime_diff($a, $b) {
1684 list($a_dec, $a_sec) = explode(" ", $a);
1685 list($b_dec, $b_sec) = explode(" ", $b);
1686 return $b_sec - $a_sec + $b_dec - $a_dec;
1687}
1688
02ebf404 1689function make_menu_from_list($list, $separator=",") {
1690/// Given a list (eg a,b,c,d,e) this function returns
1691/// an array of 1->a, 2->b, 3->c etc
1692
1693 $array = array_reverse(explode($separator, $list), true);
1694 foreach ($array as $key => $item) {
1695 $outarray[$key+1] = trim($item);
1696 }
1697 return $outarray;
1698}
1699
fdc47ee6 1700function make_grades_menu($gradingtype) {
1701/// Creates an array that represents all the current grades that
1702/// can be chosen using the given grading type. Negative numbers
1703/// are scales, zero is no grade, and positive numbers are maximum
1704/// grades.
1705
1706 $grades = array();
1707 if ($gradingtype < 0) {
1708 if ($scale = get_record("scale", "id", - $gradingtype)) {
1709 return make_menu_from_list($scale->scale);
1710 }
1711 } else if ($gradingtype > 0) {
1712 for ($i=$gradingtype; $i>=0; $i--) {
62ca135d 1713 $grades[$i] = "$i / $gradingtype";
fdc47ee6 1714 }
1715 return $grades;
1716 }
1717 return $grades;
1718}
1719
757a0abd 1720function make_unique_id_code($extra="") {
280faf9f 1721
1722 $hostname = "unknownhost";
1723 if (!empty($_SERVER["HTTP_HOST"])) {
1724 $hostname = $_SERVER["HTTP_HOST"];
1725 } else if (!empty($_ENV["HTTP_HOST"])) {
1726 $hostname = $_ENV["HTTP_HOST"];
1727 } else if (!empty($_SERVER["SERVER_NAME"])) {
1728 $hostname = $_SERVER["SERVER_NAME"];
1729 } else if (!empty($_ENV["SERVER_NAME"])) {
1730 $hostname = $_ENV["SERVER_NAME"];
1731 }
1732
1ccc73ac 1733 $date = gmdate("ymdHis");
280faf9f 1734
1735 $random = random_string(6);
1736
757a0abd 1737 if ($extra) {
1738 return "$hostname+$date+$random+$extra";
1739 } else {
1740 return "$hostname+$date+$random";
1741 }
280faf9f 1742}
1743
0095d5cd 1744
9d5b689c 1745// vim:autoindent:expandtab:shiftwidth=4:tabstop=4:tw=140:
f9903ed0 1746?>