Added popup links for IP addresses in logs (display IP location on world map)
[moodle.git] / lib / moodlelib.php
blob0ec1cc2405e4211ec88b02afaba3db43dc35b727
1 <?PHP // $Id$
3 //
4 // moodlelib.php
5 //
6 // Large collection of useful functions used by many parts of Moodle.
7 //
8 // Martin Dougiamas, 2000
9 //
12 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
14 function print_header ($title="", $heading="", $navigation="", $focus="", $meta="", $cache=true, $button="") {
15 // $title - appears top of window
16 // $heading - appears top of page
17 // $navigation - premade navigation string
18 // $focus - indicates form element eg inputform.password
19 // $meta - meta tags in the header
20 // $cache - should this page be cacheable?
21 // $button - code for a button in the top-right
22 global $USER, $CFG, $THEME;
24 if (file_exists("$CFG->dirroot/theme/$CFG->theme/styles.css")) {
25 $styles = "$CFG->wwwroot/theme/$CFG->theme/styles.css";
26 } else {
27 $styles = "$CFG->wwwroot/theme/standard/styles.css";
30 if (!$button and $navigation) {
31 if (isset($USER->id)) {
32 $button = "<FONT SIZE=2><A HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A></FONT>";
33 } else {
34 $button = "<FONT SIZE=2><A HREF=\"$CFG->wwwroot/login\">".get_string("login")."</A></FONT>";
38 if (!$cache) { // Do everything we can to prevent clients and proxies caching
39 @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
40 @header("Pragma: no-cache");
41 $meta .= "\n<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">";
42 $meta .= "\n<META HTTP-EQUIV=\"Expires\" CONTENT=\"0\">";
45 include ("$CFG->dirroot/theme/$CFG->theme/header.html");
48 function print_footer ($course=NULL) {
49 // Can provide a course object to make the footer contain a link to
50 // to the course home page, otherwise the link will go to the site home
51 global $USER, $CFG, $THEME;
53 if ($course) {
54 if ($course == "home") { // special case for site home page - please do not remove
55 if (!$dversion = get_field("config", "value", "name", "version")) {
56 $dversion = "unknown!";
58 $homelink = "<P ALIGN=center><A TITLE=\"Version $dversion: Click to visit moodle.com\" HREF=\"http://moodle.com/\">";
59 $homelink .= "<IMG WIDTH=85 HEIGHT=25 SRC=\"pix/madewithmoodle.gif\" BORDER=0></A></P>";
60 } else {
61 $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</A>";
63 } else {
64 $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot\">".get_string("home")."</A>";
66 if ($USER->realuser) {
67 if ($realuser = get_record("user", "id", $USER->realuser)) {
68 $realuserinfo = " [$realuser->firstname $realuser->lastname] ";
71 if ($USER->id) {
72 $loggedinas = $realuserinfo.get_string("loggedinas", "moodle", "$USER->firstname $USER->lastname").
73 " (<A HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A>)";
74 } else {
75 $loggedinas = get_string("loggedinnot", "moodle").
76 " (<A HREF=\"$CFG->wwwroot/login/\">".get_string("login")."</A>)";
79 include ("$CFG->dirroot/theme/$CFG->theme/footer.html");
82 function print_navigation ($navigation) {
83 global $CFG;
85 if ($navigation) {
86 if (! $site = get_site()) {
87 $site->shortname = get_string("home");;
89 echo "<A TARGET=_top HREF=\"$CFG->wwwroot/\">$site->shortname</A> -> $navigation";
93 function print_heading($text, $align="CENTER", $size=3) {
94 echo "<P ALIGN=\"$align\"><FONT SIZE=\"$size\"><B>$text</B></FONT></P>";
97 function print_continue($link) {
98 global $HTTP_REFERER;
100 if (!$link) {
101 $link = $HTTP_REFERER;
104 print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
108 function print_simple_box($message, $align="", $width="", $color="#FFFFFF", $padding=5, $border=1) {
109 print_simple_box_start($align, $width, $color, $padding, $border);
110 echo "<P>$message</P>";
111 print_simple_box_end();
114 function print_simple_box_start($align="", $width="", $color="#FFFFFF", $padding=5, $border=1) {
115 global $THEME;
117 if ($align) {
118 $tablealign = "ALIGN=\"$align\"";
120 if ($width) {
121 $tablewidth = "WIDTH=\"$width\"";
122 $innertablewidth = "WIDTH=\"100%\"";
124 echo "<TABLE $tablealign $tablewidth BORDER=0 CELLPADDING=\"$border\" CELLSPACING=0>";
125 echo "<TR><TD BGCOLOR=\"$THEME->borders\">\n";
126 echo "<TABLE $innertablewidth BORDER=0 CELLPADDING=\"$padding\" CELLSPACING=0><TR><TD BGCOLOR=\"$color\">";
129 function print_simple_box_end() {
130 echo "</TD></TR></TABLE>";
131 echo "</TD></TR></TABLE>";
134 function print_single_button($link, $options, $label="OK") {
135 echo "<FORM ACTION=\"$link\" METHOD=GET>";
136 if ($options) {
137 foreach ($options as $name => $value) {
138 echo "<INPUT TYPE=hidden NAME=\"$name\" VALUE=\"$value\">";
141 echo "<INPUT TYPE=submit VALUE=\"$label\"></FORM>";
144 function print_spacer($height=1, $width=1, $br=true) {
145 global $CFG;
146 echo "<IMG HEIGHT=\"$height\" WIDTH=\"$width\" SRC=\"$CFG->wwwroot/pix/spacer.gif\" ALT=\"\">";
147 if ($br) {
148 echo "<BR>\n";
152 function print_user_picture($userid, $courseid, $picture, $large=false, $returnstring=false) {
153 global $CFG;
155 $output = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$userid&course=$courseid\">";
156 if ($large) {
157 $file = "f1.jpg";
158 $size = 100;
159 } else {
160 $file = "f2.jpg";
161 $size = 35;
163 if ($picture) {
164 if (iswindows()) { // Workaround for a PATH_INFO problem on Windows PHP
165 $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php?file=/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
166 } else { // Use this method if possible for better caching
167 $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
169 } else {
170 $output .= "<IMG SRC=\"$CFG->wwwroot/user/default/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
172 $output .= "</A>";
174 if ($returnstring) {
175 return $output;
176 } else {
177 echo $output;
181 function print_table($table) {
182 // Prints a nicely formatted table.
183 // $table is an object with three properties.
184 // $table->head is an array of heading names.
185 // $table->align is an array of column alignments
186 // $table->data[] is an array of arrays containing the data.
187 // $table->width is an percentage of the page
189 if ($table->align) {
190 foreach ($table->align as $key => $aa) {
191 if ($aa) {
192 $align[$key] = "ALIGN=\"$aa\"";
193 } else {
194 $align[$key] = "";
199 if (!$table->width) {
200 $table->width = "80%";
203 print_simple_box_start("CENTER", "$table->width", "#FFFFFF", 0);
204 echo "<TABLE WIDTH=100% BORDER=0 valign=top align=center cellpadding=10 cellspacing=1>\n";
206 if ($table->head) {
207 echo "<TR>";
208 foreach ($table->head as $key => $heading) {
209 echo "<TH ".$align[$key].">$heading</TH>";
211 echo "</TR>\n";
214 foreach ($table->data as $row) {
215 echo "<TR VALIGN=TOP>";
216 foreach ($row as $key => $item) {
217 echo "<TD ".$align[$key].">$item</TD>";
219 echo "</TR>\n";
221 echo "</TABLE>\n";
222 print_simple_box_end();
224 return true;
227 function print_editing_switch($courseid) {
228 global $CFG, $USER;
230 if (isteacher($courseid)) {
231 if ($USER->editing) {
232 echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=off\">Turn editing off</A>";
233 } else {
234 echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=on\">Turn editing on</A>";
239 function update_course_icon($courseid) {
240 global $CFG, $USER;
242 if (isteacher($courseid)) {
243 if ($USER->editing) {
244 return "<A TITLE=\"".get_string("turneditingoff")."\"
245 HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=off\"
246 TARGET=_top><IMG SRC=\"$CFG->wwwroot/pix/i/edit.gif\" ALIGN=right BORDER=0></A>";
247 } else {
248 return "<A TITLE=\"".get_string("turneditingon")."\"
249 HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=on\"
250 TARGET=_top><IMG SRC=\"$CFG->wwwroot/pix/i/edit.gif\" ALIGN=right BORDER=0></A>";
255 function update_module_icon($moduleid, $courseid) {
256 global $CFG;
258 if (isteacher($courseid)) {
259 return "<A TITLE=\"".get_string("editthisactivity")."\" HREF=\"$CFG->wwwroot/course/mod.php?update=$moduleid&return=true\" TARGET=_top><IMG SRC=\"$CFG->wwwroot/pix/i/edit.gif\" ALIGN=right BORDER=0></A>";
264 function print_date_selector($day, $month, $year, $currenttime=0) {
265 // Currenttime is a default timestamp in GMT
266 // Prints form items with the names $day, $month and $year
268 if (!$currenttime) {
269 $currenttime = time();
271 $currentdate = usergetdate($currenttime);
273 for ($i=1; $i<=31; $i++) {
274 $days[$i] = "$i";
276 for ($i=1; $i<=12; $i++) {
277 $months[$i] = date("F", mktime(0,0,0,$i,1,2000));
279 for ($i=2000; $i<=2010; $i++) {
280 $years[$i] = $i;
282 choose_from_menu($days, $day, $currentdate[mday], "");
283 choose_from_menu($months, $month, $currentdate[mon], "");
284 choose_from_menu($years, $year, $currentdate[year], "");
287 function print_time_selector($hour, $minute, $currenttime=0) {
288 // Currenttime is a default timestamp in GMT
289 // Prints form items with the names $hour and $minute
291 if (!$currenttime) {
292 $currenttime = time();
294 $currentdate = usergetdate($currenttime);
295 for ($i=0; $i<=23; $i++) {
296 $hours[$i] = sprintf("%02d",$i);
298 for ($i=0; $i<=59; $i++) {
299 $minutes[$i] = sprintf("%02d",$i);
301 choose_from_menu($hours, $hour, $currentdate[hours], "");
302 choose_from_menu($minutes, $minute, $currentdate[minutes], "");
305 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0) {
306 // Given date parts in user time, produce a GMT timestamp
308 return mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
311 function format_time($totalsecs) {
312 // Given an amount of time in seconds, prints it
313 // nicely as months, days, hours etc as needed
315 $totalsecs = abs($totalsecs);
317 $days = floor($totalsecs/86400);
318 $remainder = $totalsecs - ($days*86400);
319 $hours = floor($remainder/3600);
320 $remainder = $remainder - ($hours*3600);
321 $mins = floor($remainder/60);
322 $secs = $remainder - ($mins*60);
324 if ($secs != 1) $ss = "s";
325 if ($mins != 1) $ms = "s";
326 if ($hours != 1) $hs = "s";
327 if ($days != 1) $ds = "s";
329 if ($days) $odays = "$days day$ds";
330 if ($hours) $ohours = "$hours hr$hs";
331 if ($mins) $omins = "$mins min$ms";
332 if ($secs) $osecs = "$secs sec$ss";
334 if ($days) return "$odays $ohours";
335 if ($hours) return "$ohours $omins";
336 if ($mins) return "$omins $osecs";
337 if ($secs) return "$osecs";
338 return get_string("now");
341 function userdate($date, $format="", $timezone=99) {
342 // Returns a formatted string that represents a date in user time
343 // WARNING: note that the format is for strftime(), not date().
345 global $USER;
347 if ($format == "") {
348 $format = "%A, %e %B %Y, %I:%M %p";
350 if ($timezone == 99) {
351 if (isset($USER->timezone)) {
352 $timezone = (float)$USER->timezone;
355 if (abs($timezone) > 12) {
356 return strftime("$format", $date);
358 return gmstrftime($format, $date + (int)($timezone * 3600));
361 function usergetdate($date, $timezone=99) {
362 // Given a $date timestamp in GMT, returns an array
363 // that represents the date in user time
365 global $USER;
367 if ($timezone == 99) {
368 $timezone = (float)$USER->timezone;
370 if (abs($timezone) > 12) {
371 return getdate($date);
373 //There is no gmgetdate so I have to fake it...
374 $date = $date + (int)($timezone * 3600);
375 $getdate["seconds"] = gmstrftime("%S", $date);
376 $getdate["minutes"] = gmstrftime("%M", $date);
377 $getdate["hours"] = gmstrftime("%H", $date);
378 $getdate["mday"] = gmstrftime("%d", $date);
379 $getdate["wday"] = gmstrftime("%u", $date);
380 $getdate["mon"] = gmstrftime("%m", $date);
381 $getdate["year"] = gmstrftime("%Y", $date);
382 $getdate["yday"] = gmstrftime("%j", $date);
383 $getdate["weekday"] = gmstrftime("%A", $date);
384 $getdate["month"] = gmstrftime("%B", $date);
385 return $getdate;
388 function usertime($date, $timezone=99) {
389 // Given a GMT timestamp (seconds since epoch), offsets it by
390 // the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
391 global $USER;
393 if ($timezone == 99) {
394 $timezone = (float)$USER->timezone;
396 if (abs($timezone) > 12) {
397 return $date;
399 return $date - (int)($timezone * 3600);
402 function usergetmidnight($date, $timezone=99) {
403 // Given a time, return the GMT timestamp of the most recent midnight
404 // for the current user.
405 global $USER;
407 if ($timezone == 99) {
408 $timezone = (float)$USER->timezone;
411 $userdate = usergetdate($date, $timezone);
413 if (abs($timezone) > 12) {
414 return mktime(0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
417 $timemidnight = gmmktime (0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
418 return usertime($timemidnight, $timezone); // Time of midnight of this user's day, in GMT
422 function usertimezone($timezone=99) {
423 // returns a string that prints the user's timezone
424 global $USER;
426 if ($timezone == 99) {
427 $timezone = (float)$USER->timezone;
429 if (abs($timezone) > 12) {
430 return "server time";
432 if (abs($timezone) < 0.5) {
433 return "GMT";
435 if ($timezone > 0) {
436 return "GMT+$timezone";
437 } else {
438 return "GMT$timezone";
443 function error ($message, $link="") {
444 global $CFG, $SESSION;
446 print_header(get_string("error"));
447 echo "<BR>";
448 print_simple_box($message, "center", "", "#FFBBBB");
450 if (!$link) {
451 if ( !empty($SESSION->fromurl) ) {
452 $link = "$SESSION->fromurl";
453 unset($SESSION->fromurl);
454 save_session("SESSION");
455 } else {
456 $link = "$CFG->wwwroot";
459 print_continue($link);
460 print_footer();
461 die;
464 function helpbutton ($page, $title="", $module="moodle", $image=true, $text="") {
465 // $page = the keyword that defines a help page
466 // $title = the title of links, rollover tips, alt tags etc
467 // $module = which module is the page defined in
468 // $image = use a help image for the link? (otherwise uses text)
469 // $text = if defined then this text is used in the page, and
470 // the $page variable is ignored.
471 global $CFG;
472 if ($module == "") {
473 $module = "moodle";
475 if ($image) {
476 $linkobject = "<IMG BORDER=0 ALT=\"$title\" SRC=\"$CFG->wwwroot/pix/help.gif\">";
477 } else {
478 $linkobject = $title;
480 if ($text) {
481 $url = "/help.php?module=$module&text=$text";
482 } else {
483 $url = "/help.php?module=$module&file=$page.html";
485 link_to_popup_window ($url, "popup", $linkobject, 400, 500, $title);
488 function notice ($message, $link="") {
489 global $THEME, $HTTP_REFERER;
491 if (!$link) {
492 $link = $HTTP_REFERER;
495 echo "<BR>";
496 print_simple_box($message, "center", "", "$THEME->cellheading");
497 print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
498 print_footer();
499 die;
502 function notice_yesno ($message, $linkyes, $linkno) {
503 global $THEME;
505 print_simple_box_start("center", "", "$THEME->cellheading");
506 echo "<P ALIGN=CENTER><FONT SIZE=3>$message</FONT></P>";
507 echo "<P ALIGN=CENTER><FONT SIZE=3><B>";
508 echo "<A HREF=\"$linkyes\">".get_string("yes")."</A>";
509 echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
510 echo "<A HREF=\"$linkno\">".get_string("no")."</A>";
511 echo "</B></FONT></P>";
512 print_simple_box_end();
515 function redirect($url, $message="", $delay=0) {
516 // Uses META tags to redirect the user, after printing a notice
518 echo "<META HTTP-EQUIV='Refresh' CONTENT='$delay; URL=$url'>";
520 if (!empty($message)) {
521 print_header();
522 echo "<CENTER>";
523 echo "<P>$message</P>";
524 echo "<P>( <A HREF=\"$url\">".get_string("continue")."</A> )</P>";
525 echo "</CENTER>";
527 die;
530 function notify ($message) {
531 echo "<P align=center><B><FONT COLOR=#FF0000>$message</FONT></B></P>\n";
536 /// PARAMETER HANDLING ////////////////////////////////////////////////////
538 function require_variable($var) {
539 if (! isset($var)) {
540 error("A required parameter was missing");
544 function optional_variable(&$var, $default=0) {
545 if (! isset($var)) {
546 $var = $default;
553 /// DATABASE HANDLING ////////////////////////////////////////////////
555 function execute_sql($command) {
556 // Completely general
558 global $db;
560 $result = $db->Execute("$command");
562 if ($result) {
563 echo "<P><FONT COLOR=green><B>".get_string("success")."</B></FONT></P>";
564 return true;
565 } else {
566 echo "<P><FONT COLOR=red><B>".get_string("error")."</B></FONT></P>";
567 return false;
571 function modify_database($sqlfile) {
572 // Assumes that the input text file consists of a number
573 // of SQL statements ENDING WITH SEMICOLONS. The semicolons
574 // MUST be the last character in a line.
575 // Lines that are blank or that start with "#" are ignored.
576 // Only tested with mysql dump files (mysqldump -p -d moodle)
579 if (file_exists($sqlfile)) {
580 $success = true;
581 $lines = file($sqlfile);
582 $command = "";
584 while ( list($i, $line) = each($lines) ) {
585 $line = chop($line);
586 $length = strlen($line);
588 if ($length && substr($line, 0, 1) <> "#") {
589 if (substr($line, $length-1, 1) == ";") {
590 $line = substr($line, 0, $length-1); // strip ;
591 $command .= $line;
592 if (! execute_sql($command)) {
593 $success = false;
595 $command = "";
596 } else {
597 $command .= $line;
602 } else {
603 $success = false;
604 echo "<P>Tried to modify database, but \"$sqlfile\" doesn't exist!</P>";
607 return $success;
611 function record_exists($table, $field, $value) {
612 global $db;
614 $rs = $db->Execute("SELECT * FROM $table WHERE $field = '$value' LIMIT 1");
615 if (!$rs) return false;
617 if ( $rs->RecordCount() ) {
618 return true;
619 } else {
620 return false;
624 function record_exists_sql($sql) {
625 global $db;
627 $rs = $db->Execute($sql);
628 if (!$rs) return false;
630 if ( $rs->RecordCount() ) {
631 return true;
632 } else {
633 return false;
638 function count_records($table, $selector, $value) {
639 // Get all the records and count them
640 global $db;
642 $rs = $db->Execute("SELECT COUNT(*) FROM $table WHERE $selector = '$value'");
643 if (!$rs) return 0;
645 return $rs->fields[0];
648 function count_records_sql($sql) {
649 // Get all the records and count them
650 global $db;
652 $rs = $db->Execute("$sql");
653 if (!$rs) return 0;
655 return $rs->fields[0];
658 function get_record($table, $selector, $value) {
659 // Get a single record as an object
660 global $db;
662 $rs = $db->Execute("SELECT * FROM $table WHERE $selector = '$value'");
663 if (!$rs) return false;
665 if ( $rs->RecordCount() == 1 ) {
666 return (object)$rs->fields;
667 } else {
668 return false;
672 function get_record_sql($sql) {
673 // Get a single record as an object
674 // The sql statement is provided as a string.
676 global $db;
678 $rs = $db->Execute("$sql");
679 if (!$rs) return false;
681 if ( $rs->RecordCount() == 1 ) {
682 return (object)$rs->fields;
683 } else {
684 return false;
688 function get_records($table, $selector, $value, $sort="") {
689 // Get a number of records as an array of objects
690 // Can optionally be sorted eg "time ASC" or "time DESC"
691 // The "key" is the first column returned, eg usually "id"
692 global $db;
694 if ($sort) {
695 $sortorder = "ORDER BY $sort";
697 $sql = "SELECT * FROM $table WHERE $selector = '$value' $sortorder";
699 return get_records_sql($sql);
702 function get_records_sql($sql) {
703 // Get a number of records as an array of objects
704 // The "key" is the first column returned, eg usually "id"
705 // The sql statement is provided as a string.
707 global $db;
709 $rs = $db->Execute("$sql");
710 if (!$rs) return false;
712 if ( $rs->RecordCount() > 0 ) {
713 if ($records = $rs->GetAssoc(true)) {
714 foreach ($records as $key => $record) {
715 $objects[$key] = (object) $record;
717 return $objects;
718 } else {
719 return false;
721 } else {
722 return false;
726 function get_records_sql_menu($sql) {
727 // Given an SQL select, this function returns an associative
728 // array of the first two columns. This is most useful in
729 // combination with the choose_from_menu function to create
730 // a form menu.
732 global $db;
734 $rs = $db->Execute("$sql");
735 if (!$rs) return false;
737 if ( $rs->RecordCount() > 0 ) {
738 while (!$rs->EOF) {
739 $menu[$rs->fields[0]] = $rs->fields[1];
740 $rs->MoveNext();
742 return $menu;
744 } else {
745 return false;
749 function get_field($table, $field, $selector, $value) {
750 global $db;
752 $rs = $db->Execute("SELECT $field FROM $table WHERE $selector = '$value'");
753 if (!$rs) return false;
755 if ( $rs->RecordCount() == 1 ) {
756 return $rs->fields["$field"];
757 } else {
758 return false;
762 function set_field($table, $field, $newvalue, $selector, $value) {
763 global $db;
765 return $db->Execute("UPDATE $table SET $field = '$newvalue' WHERE $selector = '$value'");
769 function delete_records($table, $selector, $value) {
770 // Delete one or more records from a table
771 global $db;
773 return $db->Execute("DELETE FROM $table WHERE $selector = '$value'");
776 function insert_record($table, $dataobject) {
777 // Insert a record into a table and return the "id" field
778 // $dataobject is an object containing needed data
780 global $db;
782 // Determine all the fields needed
783 if (! $columns = $db->MetaColumns("$table")) {
784 return false;
787 $data = (array)$dataobject;
789 // Pull out data matching these fields
790 foreach ($columns as $column) {
791 if ($column->name <> "id" && isset($data[$column->name]) ) {
792 $ddd[$column->name] = $data[$column->name];
796 // Construct SQL queries
797 if (! $numddd = count($ddd)) {
798 return 0;
801 $count = 0;
802 $insert = "";
803 $select = "";
805 foreach ($ddd as $key => $value) {
806 $count++;
807 $insert .= "$key = '$value'";
808 $select .= "$key = '$value'";
809 if ($count < $numddd) {
810 $insert .= ", ";
811 $select .= " AND ";
815 if (! $rs = $db->Execute("INSERT INTO $table SET $insert")) {
816 return false;
819 // Pull it out again to find the id. This is the most cross-platform method.
820 if ($rs = $db->Execute("SELECT id FROM $table WHERE $select")) {
821 return $rs->fields[0];
822 } else {
823 return false;
828 function update_record($table, $dataobject) {
829 // Update a record in a table
830 // $dataobject is an object containing needed data
832 global $db;
834 if (! isset($dataobject->id) ) {
835 return false;
838 // Determine all the fields in the table
839 if (!$columns = $db->MetaColumns($table)) {
840 return false;
842 $data = (array)$dataobject;
844 // Pull out data matching these fields
845 foreach ($columns as $column) {
846 if ($column->name <> "id" && isset($data[$column->name]) ) {
847 $ddd[$column->name] = $data[$column->name];
851 // Construct SQL queries
852 $numddd = count($ddd);
853 $count = 0;
854 $update = "";
856 foreach ($ddd as $key => $value) {
857 $count++;
858 $update .= "$key = '$value'";
859 if ($count < $numddd) {
860 $update .= ", ";
864 if ($rs = $db->Execute("UPDATE $table SET $update WHERE id = '$dataobject->id'")) {
865 return true;
866 } else {
867 return false;
872 function print_object($object) {
873 // Mostly just for debugging
875 $array = (array)$object;
876 foreach ($array as $key => $item) {
877 echo "$key -> $item <BR>";
883 /// USER DATABASE ////////////////////////////////////////////////
885 function get_user_info_from_db($field, $value) {
887 global $db;
889 if (!$field || !$value)
890 return false;
892 $result = $db->Execute("SELECT * FROM user WHERE $field = '$value'");
894 if ( $result->RecordCount() == 1 ) {
895 $user = (object)$result->fields;
897 $rs = $db->Execute("SELECT course FROM user_students WHERE user = '$user->id' ");
898 while (!$rs->EOF) {
899 $course = $rs->fields["course"];
900 $user->student["$course"] = true;
901 $rs->MoveNext();
904 $rs = $db->Execute("SELECT course FROM user_teachers WHERE user = '$user->id' ");
905 while (!$rs->EOF) {
906 $course = $rs->fields["course"];
907 $user->teacher["$course"] = true;
908 $rs->MoveNext();
911 $rs = $db->Execute("SELECT * FROM user_admins WHERE user = '$user->id' ");
912 while (!$rs->EOF) {
913 $user->admin = true;
914 $rs->MoveNext();
917 if ($course = get_site()) {
918 // Everyone is always a member of the top course
919 $user->student["$course->id"] = true;
922 return $user;
924 } else {
925 return false;
929 function update_user_in_db() {
931 global $db, $USER, $REMOTE_ADDR;
933 if (!isset($USER->id))
934 return false;
936 $timenow = time();
937 if ($db->Execute("UPDATE LOW_PRIORITY user SET lastIP='$REMOTE_ADDR', lastaccess='$timenow'
938 WHERE id = '$USER->id' ")) {
939 return true;
940 } else {
941 return false;
945 function require_login($courseid=0) {
946 // This function checks that the current user is logged in, and optionally
947 // whether they are "logged in" or allowed to be in a particular course.
948 // If not, then it redirects them to the site login or course enrolment.
950 global $CFG, $SESSION, $USER, $FULLME, $HTTP_REFERER, $PHPSESSID;
952 // First check that the user is logged in to the site.
954 if (! (isset($USER->loggedin) and $USER->confirmed) ) { // They're not
955 $SESSION->wantsurl = $FULLME;
956 $SESSION->fromurl = $HTTP_REFERER;
957 save_session("SESSION");
958 if ($PHPSESSID) { // Cookies not enabled.
959 redirect("$CFG->wwwroot/login/?PHPSESSID=$PHPSESSID");
960 } else {
961 redirect("$CFG->wwwroot/login/");
963 die;
966 // Next, check if the user can be in a particular course
967 if ($courseid) {
968 if ($USER->student[$courseid] || $USER->teacher[$courseid] || $USER->admin) {
969 if (!isset($USER->realuser)) { // Don't update if this isn't a realuser
970 update_user_in_db();
972 return; // user is a member of this course.
974 if (! $course = get_record("course", "id", $courseid)) {
975 error("That course doesn't exist");
977 if ($USER->username == "guest") {
978 switch ($course->guest) {
979 case 0: // Guests not allowed
980 print_header();
981 notice(get_string("guestsnotallowed", "", $course->fullname));
982 break;
983 case 1: // Guests allowed
984 update_user_in_db();
985 return;
986 case 2: // Guests allowed with key (drop through)
987 break;
991 // Currently not enrolled in the course, so see if they want to enrol
992 $SESSION->wantsurl = $FULLME;
993 save_session("SESSION");
994 redirect("$CFG->wwwroot/course/enrol.php?id=$courseid");
995 die;
1001 function update_login_count() {
1002 global $SESSION;
1004 $max_logins = 10;
1006 if (empty($SESSION->logincount)) {
1007 $SESSION->logincount = 1;
1008 } else {
1009 $SESSION->logincount++;
1011 save_session("SESSION");
1013 if ($SESSION->logincount > $max_logins) {
1014 unset($SESSION->wantsurl);
1015 save_session("SESSION");
1016 error("Sorry, you have exceeded the allowed number of login attempts. Restart your browser.");
1021 function isadmin($userid=0) {
1022 global $USER;
1024 if (!$userid) {
1025 return $USER->admin;
1028 return record_exists_sql("SELECT * FROM user_admins WHERE user='$userid'");
1031 function isteacher($courseid, $userid=0) {
1032 global $USER;
1034 if (isadmin($userid)) { // admins can do anything the teacher can
1035 return true;
1038 if (!$userid) {
1039 return $USER->teacher[$courseid];
1042 return record_exists_sql("SELECT * FROM user_teachers WHERE user='$userid' AND course='$courseid'");
1046 function isstudent($courseid, $userid=0) {
1047 global $USER;
1049 if (!$userid) {
1050 return $USER->student[$courseid];
1053 $timenow = time(); // todo: add time check below
1055 return record_exists_sql("SELECT * FROM user_students WHERE user='$userid' AND course='$courseid'");
1058 function isguest($userid=0) {
1059 global $USER;
1061 if (!$userid) {
1062 return ($USER->username == "guest");
1065 return record_exists_sql("SELECT * FROM user WHERE id='$userid' AND username = 'guest' ");
1068 function isediting($courseid, $user=NULL) {
1069 global $USER;
1070 if (!$user){
1071 $user = $USER;
1073 return ($user->editing and isteacher($courseid, $user->id));
1076 function reset_login_count() {
1077 global $SESSION;
1079 $SESSION->logincount = 0;
1080 save_session("SESSION");
1084 function set_moodle_cookie($thing) {
1086 $days = 60;
1087 $seconds = 60*60*24*$days;
1089 setCookie ('MOODLEID', "", time() - 3600, "/");
1090 setCookie ('MOODLEID', rc4encrypt($thing), time()+$seconds, "/");
1094 function get_moodle_cookie() {
1095 global $MOODLEID;
1096 return rc4decrypt($MOODLEID);
1100 function save_session($VAR) {
1101 // Copies temporary session variable to permanent sesson variable
1102 // eg $_SESSION["USER"] = $USER;
1103 global $$VAR;
1104 $_SESSION[$VAR] = $$VAR;
1108 function verify_login($username, $password) {
1110 $user = get_user_info_from_db("username", $username);
1112 if (! $user) {
1113 return false;
1114 } else if ( $user->password == md5($password) ) {
1115 return $user;
1116 } else {
1117 return false;
1121 function get_site () {
1122 // Returns $course object of the top-level site.
1123 if ( $course = get_record("course", "category", 0)) {
1124 return $course;
1125 } else {
1126 return false;
1130 function get_admin () {
1131 // Returns $user object of the main admin user
1133 if ( $admins = get_records_sql("SELECT u.* FROM user u, user_admins a WHERE a.user = u.id ORDER BY u.id ASC")) {
1134 foreach ($admins as $admin) {
1135 return $admin; // ie the first one (yeah I know it's bodgy)
1137 } else {
1138 return false;
1142 function get_teacher($courseid) {
1143 // Returns $user object of the main teacher for a course
1144 if ( $teachers = get_records_sql("SELECT u.* FROM user u, user_teachers t
1145 WHERE t.user = u.id AND t.course = '$courseid'
1146 ORDER BY t.authority ASC")) {
1147 foreach ($teachers as $teacher) {
1148 return $teacher; // ie the first one (yeah I know it's bodgy)
1150 } else {
1151 return false;
1155 function get_course_students($courseid, $sort="u.lastaccess DESC") {
1156 return get_records_sql("SELECT u.* FROM user u, user_students s
1157 WHERE s.course = '$courseid' AND s.user = u.id
1158 ORDER BY $sort");
1161 function get_course_teachers($courseid, $sort="t.authority ASC") {
1162 return get_records_sql("SELECT u.* FROM user u, user_teachers t
1163 WHERE t.course = '$courseid' AND t.user = u.id
1164 ORDER BY $sort");
1167 function get_course_users($courseid, $sort="u.lastaccess DESC") {
1168 // Using this method because the direct SQL just would not always work!
1170 $teachers = get_course_teachers($courseid, $sort);
1171 $students = get_course_students($courseid, $sort);
1173 if ($teachers and $students) {
1174 return array_merge($teachers, $students);
1175 } else if ($teachers) {
1176 return $teachers;
1177 } else {
1178 return $students;
1181 // return get_records_sql("SELECT u.* FROM user u, user_students s, user_teachers t
1182 // WHERE (s.course = '$courseid' AND s.user = u.id) OR
1183 // (t.course = '$courseid' AND t.user = u.id)
1184 // ORDER BY $sort");
1189 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1191 function get_coursemodule_from_instance($modulename, $instance, $courseid) {
1192 // Given an instance of a module, finds the coursemodule description
1194 return get_record_sql("SELECT cm.*, m.name
1195 FROM course_modules cm, modules md, $modulename m
1196 WHERE cm.course = '$courseid' AND
1197 cm.deleted = '0' AND
1198 cm.instance = m.id AND
1199 md.name = '$modulename' AND
1200 md.id = cm.module AND
1201 m.id = '$instance'");
1205 function get_all_instances_in_course($modulename, $courseid, $sort="cw.section") {
1206 // Returns an array of all the active instances of a particular
1207 // module in a given course. Returns false on any errors.
1209 return get_records_sql("SELECT m.*,cw.section,cm.id as coursemodule
1210 FROM course_modules cm, course_sections cw, modules md, $modulename m
1211 WHERE cm.course = '$courseid' AND
1212 cm.instance = m.id AND
1213 cm.deleted = '0' AND
1214 cm.section = cw.id AND
1215 md.name = '$modulename' AND
1216 md.id = cm.module
1217 ORDER BY $sort");
1224 /// CORRESPONDENCE ////////////////////////////////////////////////
1226 function email_to_user($user, $from, $subject, $messagetext, $messagehtml="", $attachment="", $attachname="") {
1227 // user - a user record as an object
1228 // from - a user record as an object
1229 // subject - plain text subject line of the email
1230 // messagetext - plain text version of the message
1231 // messagehtml - complete html version of the message (optional)
1232 // attachment - a file on the filesystem, relative to $CFG->dataroot
1233 // attachname - the name of the file (extension indicates MIME)
1235 global $CFG, $_SERVER;
1237 include_once("$CFG->libdir/phpmailer/class.phpmailer.php");
1239 if (!$user) {
1240 return false;
1243 $mail = new phpmailer;
1245 $mail->Version = "Moodle $CFG->moodleversion"; // mailer version
1246 $mail->PluginDir = "$CFG->libdir/phpmailer/"; // plugin directory (eg smtp plugin)
1247 if ($CFG->smtphosts) {
1248 $mail->IsSMTP(); // use SMTP directly
1249 $mail->Host = "$CFG->smtphosts"; // specify main and backup servers
1250 } else {
1251 $mail->IsMail(); // use PHP mail() = sendmail
1254 $mail->From = "$from->email";
1255 $mail->FromName = "$from->firstname $from->lastname";
1256 $mail->Subject = stripslashes($subject);
1258 $mail->AddAddress("$user->email", "$user->firstname $user->lastname");
1260 $mail->WordWrap = 70; // set word wrap
1262 if ($messagehtml) {
1263 $mail->IsHTML(true);
1264 $mail->Body = $messagehtml;
1265 $mail->AltBody = "\n$messagetext\n";
1266 } else {
1267 $mail->IsHTML(false);
1268 $mail->Body = "\n$messagetext\n";
1271 if ($attachment && $attachname) {
1272 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
1273 $adminuser = get_admin();
1274 $mail->AddAddress("$adminuser->email", "$adminuser->firstname $adminuser->lastname");
1275 $mail->AddStringAttachment("Error in attachment. User attempted to attach a filename with a unsafe name.", "error.txt", "8bit", "text/plain");
1276 } else {
1277 include_once("$CFG->dirroot/files/mimetypes.php");
1278 $mimetype = mimeinfo("type", $attachname);
1279 $mail->AddAttachment("$CFG->dataroot/$attachment", "$attachname", "base64", "$mimetype");
1283 if ($mail->Send()) {
1284 return true;
1285 } else {
1286 echo "ERROR: $mail->ErrorInfo\n";
1287 $site = get_site();
1288 add_to_log($site->id, "library", "mailer", $_SERVER["REQUEST_URI"], "ERROR: $mail->ErrorInfo");
1289 return false;
1294 /// FILE HANDLING /////////////////////////////////////////////
1296 function make_upload_directory($directory) {
1297 // $directory = a string of directory names under $CFG->dataroot
1298 // eg stuff/assignment/1
1299 // Returns full directory if successful, false if not
1301 global $CFG;
1303 $currdir = $CFG->dataroot;
1304 if (!file_exists($currdir)) {
1305 if (! mkdir($currdir, 0750)) {
1306 notify("ERROR: You need to create the directory $currdir with web server write access");
1307 return false;
1311 $dirarray = explode("/", $directory);
1313 foreach ($dirarray as $dir) {
1314 $currdir = "$currdir/$dir";
1315 if (! file_exists($currdir)) {
1316 if (! mkdir($currdir, 0750)) {
1317 notify("ERROR: Could not find or create a directory ($currdir)");
1318 return false;
1323 return $currdir;
1327 function get_directory_list( $rootdir ) {
1328 // Returns an array with all the filenames in
1329 // all subdirectories, relative to the given rootdir.
1331 $dirs = array();
1333 $dir = opendir( $rootdir );
1335 while( $file = readdir( $dir ) ) {
1336 $fullfile = $rootdir."/".$file;
1337 if ($file != "." and $file != "..") {
1338 if (filetype($fullfile) == "dir") {
1339 $subdirs = get_directory_list($fullfile);
1340 foreach ($subdirs as $subdir) {
1341 $dirs[] = $file."/".$subdir;
1343 } else {
1344 $dirs[] = $file;
1349 return $dirs;
1352 function get_real_size($size=0) {
1353 // Converts numbers like 10M into bytes
1354 if (!$size) {
1355 return 0;
1357 $scan['MB'] = 1048576;
1358 $scan['M'] = 1048576;
1359 $scan['KB'] = 1024;
1360 $scan['K'] = 1024;
1362 while (list($key) = each($scan)) {
1363 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1364 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1365 break;
1368 return $size;
1371 function clean_filename($string) {
1372 $string = eregi_replace("\.\.", "", $string);
1373 $string = eregi_replace("[^([:alnum:]|\.)]", "_", $string);
1374 return eregi_replace("_+", "_", $string);
1378 /// STRING TRANSLATION ////////////////////////////////////////
1380 function print_string($identifier, $module="", $a=NULL) {
1381 echo get_string($identifier, $module, $a);
1385 function get_string($identifier, $module="", $a=NULL) {
1386 // Return the translated string specified by $identifier as
1387 // for $module. Uses the same format files as STphp.
1388 // $a is an object, string or number that can be used
1389 // within translation strings
1391 // eg "hello \$a->firstname \$a->lastname"
1392 // or "hello \$a"
1394 global $CFG, $USER;
1396 if (isset($USER->lang)) { // User language can override site language
1397 $lang = $USER->lang;
1398 } else {
1399 $lang = $CFG->lang;
1402 if ($module == "") {
1403 $module = "moodle";
1406 $langpath = "$CFG->dirroot/lang";
1407 $langfile = "$langpath/$lang/$module.php";
1409 if (!file_exists($langfile)) { // try English instead
1410 $langfile = "$langpath/en/$module.php";
1411 if (!file_exists($langfile)) {
1412 return "ERROR: No lang file ($langpath/en/$module.php)!";
1416 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1418 eval($result);
1419 return $resultstring;
1421 } else {
1422 if ($lang == "en") {
1423 return "ERROR: '$identifier' is missing!";
1425 } else { // Try looking in the english file.
1426 $langfile = "$langpath/en/$module.php";
1427 if (!file_exists($langfile)) {
1428 return "ERROR: No lang file ($langpath/en/$module.php)!";
1430 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1431 eval($result);
1432 return $resultstring;
1433 } else {
1434 return "ERROR: '$identifier' is missing!";
1441 function get_string_from_file($identifier, $langfile, $destination) {
1442 // This function is only used from get_string().
1443 include ($langfile);
1445 if (!isset ($string[$identifier])) {
1446 return false;
1449 return "$destination = sprintf(\"".$string[$identifier]."\");";
1453 /// ENCRYPTION ////////////////////////////////////////////////
1455 function rc4encrypt($data) {
1456 $password = "nfgjeingjk";
1457 return endecrypt($password, $data, "");
1460 function rc4decrypt($data) {
1461 $password = "nfgjeingjk";
1462 return endecrypt($password, $data, "de");
1465 function endecrypt ($pwd, $data, $case) {
1466 // Based on a class by Mukul Sabharwal [mukulsabharwal@yahoo.com]
1468 if ($case == 'de') {
1469 $data = urldecode($data);
1472 $key[] = "";
1473 $box[] = "";
1474 $temp_swap = "";
1475 $pwd_length = 0;
1477 $pwd_length = strlen($pwd);
1479 for ($i = 0; $i <= 255; $i++) {
1480 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
1481 $box[$i] = $i;
1484 $x = 0;
1486 for ($i = 0; $i <= 255; $i++) {
1487 $x = ($x + $box[$i] + $key[$i]) % 256;
1488 $temp_swap = $box[$i];
1489 $box[$i] = $box[$x];
1490 $box[$x] = $temp_swap;
1493 $temp = "";
1494 $k = "";
1496 $cipherby = "";
1497 $cipher = "";
1499 $a = 0;
1500 $j = 0;
1502 for ($i = 0; $i < strlen($data); $i++) {
1503 $a = ($a + 1) % 256;
1504 $j = ($j + $box[$a]) % 256;
1505 $temp = $box[$a];
1506 $box[$a] = $box[$j];
1507 $box[$j] = $temp;
1508 $k = $box[(($box[$a] + $box[$j]) % 256)];
1509 $cipherby = ord(substr($data, $i, 1)) ^ $k;
1510 $cipher .= chr($cipherby);
1513 if ($case == 'de') {
1514 $cipher = urldecode(urlencode($cipher));
1515 } else {
1516 $cipher = urlencode($cipher);
1519 return $cipher;
1523 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
1525 function count_words($string) {
1526 $string = strip_tags($string);
1527 return count(preg_split("/\w\b/", $string)) - 1;
1530 function getweek ($startdate, $thedate) {
1531 // Given dates in seconds, how many weeks is the date from startdate
1532 // The first week is 1, the second 2 etc ...
1534 if ($thedate < $startdate) { // error
1535 return 0;
1538 return floor(($thedate - $startdate) / 604800.0) + 1;
1541 function add_to_log($course, $module, $action, $url="", $info="") {
1542 // Add an entry to the log table. These are "action" focussed rather
1543 // than web server hits, and provide a way to easily reconstruct what
1544 // any particular student has been doing.
1546 // course = the course id
1547 // module = forum, journal, reading, course, user etc
1548 // action = view, edit, post (often but not always the same as the file.php)
1549 // url = the file and parameters used to see the results of the action
1550 // info = additional description information
1553 global $db, $USER, $REMOTE_ADDR;
1555 if (isset($USER->realuser)) { // Don't log
1556 return;
1559 $timenow = time();
1560 $info = addslashes($info);
1562 $result = $db->Execute("INSERT INTO log
1563 SET time = '$timenow',
1564 user = '$USER->id',
1565 course = '$course',
1566 ip = '$REMOTE_ADDR',
1567 module = '$module',
1568 action = '$action',
1569 url = '$url',
1570 info = '$info'");
1571 if (!$result) {
1572 echo "<P>Error: Could not insert a new entry to the Moodle log</P>"; // Don't throw an error
1576 function generate_password($maxlen=10) {
1577 // returns a randomly generated password of length $maxlen. inspired by
1578 // http://www.phpbuilder.com/columns/jesus19990502.php3
1580 global $CFG;
1582 $fillers = "1234567890!$-+";
1583 $wordlist = file($CFG->wordlist);
1585 srand((double) microtime() * 1000000);
1586 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1587 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1588 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
1590 return substr($word1 . $filler1 . $word2, 0, $maxlen);
1593 function moodle_needs_upgrading() {
1594 // Checks version numbers of Main code and all modules to see
1595 // if there are any mismatches ... returns true or false
1596 global $CFG;
1598 include_once("$CFG->dirroot/version.php"); # defines $version and upgrades
1599 if ($dversion = get_field("config", "value", "name", "version")) {
1600 if ($version > $dversion) {
1601 return true;
1603 if ($mods = get_list_of_plugins("mod")) {
1604 foreach ($mods as $mod) {
1605 $fullmod = "$CFG->dirroot/mod/$mod";
1606 unset($module);
1607 include_once("$fullmod/version.php"); # defines $module with version etc
1608 if ($currmodule = get_record("modules", "name", $mod)) {
1609 if ($module->version > $currmodule->version) {
1610 return true;
1615 } else {
1616 return true;
1618 return false;
1622 function get_list_of_plugins($plugin="mod") {
1623 // Lists plugin directories within some directory
1625 global $CFG;
1627 $basedir = opendir("$CFG->dirroot/$plugin");
1628 while ($dir = readdir($basedir)) {
1629 if ($dir == "." || $dir == ".." || $dir == "CVS") {
1630 continue;
1632 if (filetype("$CFG->dirroot/$plugin/$dir") != "dir") {
1633 continue;
1635 $plugins[] = $dir;
1637 if ($plugins) {
1638 asort($plugins);
1640 return $plugins;
1644 function iswindows() {
1645 // True if this is Windows, False if not.
1647 global $WINDIR;
1649 return isset($WINDIR);
1652 function check_php_version($version="4.1.0") {
1653 // Returns true is the current version of PHP is greater that the specified one
1654 $minversion = intval(str_replace(".", "", $version));
1655 $curversion = intval(str_replace(".", "", phpversion()));
1656 return ($curversion >= $minversion);