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