6 // Large collection of useful functions used by many parts of Moodle.
8 // Martin Dougiamas, 2000
11 /// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
13 function print_header ($title="", $heading="", $navigation="", $focus="", $meta="", $cache=true, $button="") {
14 // $title - appears top of window
15 // $heading - appears top of page
16 // $navigation - premade navigation string
17 // $focus - indicates form element eg inputform.password
18 // $meta - meta tags in the header
19 // $cache - should this page be cacheable?
20 // $button - code for a button in the top-right
21 global $USER, $CFG, $THEME;
23 if (file_exists("$CFG->dirroot/theme/$CFG->theme/styles.css")) {
24 $styles = "$CFG->wwwroot/theme/$CFG->theme/styles.css";
26 $styles = "$CFG->wwwroot/theme/standard/styles.css";
29 if ($navigation == "home") {
34 if (!$button and $navigation) {
35 if (isset($USER->id)) {
36 $button = "<FONT SIZE=2><A HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A></FONT>";
38 $button = "<FONT SIZE=2><A HREF=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</A></FONT>";
42 // Specify character set ... default is iso-8859-1 but some languages might need something else
43 // Could be optimised by carrying the charset variable around in $USER
44 if (current_language() == "en") {
45 $meta .= "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">\n";
47 $meta .= "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=".get_string("thischarset")."\">\n";
50 if ($CFG->langdir == "RTL") {
51 $direction = " DIR=\"RTL\"";
53 $direction = " DIR=\"LTR\"";
56 if (!$cache) { // Do everything we can to prevent clients and proxies caching
57 @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
58 @header("Pragma: no-cache");
59 $meta .= "\n<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">";
60 $meta .= "\n<META HTTP-EQUIV=\"Expires\" CONTENT=\"0\">";
63 include ("$CFG->dirroot/theme/$CFG->theme/header.html");
66 function print_footer ($course=NULL) {
67 // Can provide a course object to make the footer contain a link to
68 // to the course home page, otherwise the link will go to the site home
69 global $USER, $CFG, $THEME;
72 if ($course == "home") { // special case for site home page - please do not remove
73 $homelink = "<P ALIGN=center><A TITLE=\"Moodle $CFG->release ($CFG->version)\" HREF=\"http://moodle.com/\">";
74 $homelink .= "<BR><IMG WIDTH=130 HEIGHT=19 SRC=\"pix/madewithmoodle2.gif\" BORDER=0></A></P>";
76 $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</A>";
79 $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot\">".get_string("home")."</A>";
81 if ($USER->realuser) {
82 if ($realuser = get_record("user", "id", $USER->realuser)) {
83 $realuserinfo = " [$realuser->firstname $realuser->lastname] ";
88 if ($course == "home") {
90 $username = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$USER->id&course=$site->id\">$USER->firstname $USER->lastname</A>";
92 $username = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id\">$USER->firstname $USER->lastname</A>";
95 $username = "$USER->firstname $USER->lastname";
97 $loggedinas = $realuserinfo.get_string("loggedinas", "moodle", "$username").
98 " (<A HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A>)";
100 $loggedinas = get_string("loggedinnot", "moodle").
101 " (<A HREF=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</A>)";
104 include ("$CFG->dirroot/theme/$CFG->theme/footer.html");
107 function print_navigation ($navigation) {
111 if (! $site = get_site()) {
112 $site->shortname = get_string("home");;
114 echo "<A TARGET=_top HREF=\"$CFG->wwwroot/\">$site->shortname</A> -> $navigation";
118 function print_heading($text, $align="CENTER", $size=3) {
119 echo "<P ALIGN=\"$align\"><FONT SIZE=\"$size\"><B>".stripslashes($text)."</B></FONT></P>";
122 function print_heading_with_help($text, $helppage, $module="moodle") {
123 // Centered heading with attached help button (same title text)
124 echo "<P ALIGN=\"CENTER\"><FONT SIZE=\"3\"><B>".stripslashes($text);
125 helpbutton($helppage, $text, $module);
126 echo "</B></FONT></P>";
129 function print_continue($link) {
130 global $HTTP_REFERER;
133 $link = $HTTP_REFERER;
136 print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
140 function print_simple_box($message, $align="", $width="", $color="#FFFFFF", $padding=5, $border=1) {
141 print_simple_box_start($align, $width, $color, $padding, $border);
142 echo "<P>".stripslashes($message)."</P>";
143 print_simple_box_end();
146 function print_simple_box_start($align="", $width="", $color="#FFFFFF", $padding=5, $border=1) {
150 $tablealign = "ALIGN=\"$align\"";
153 $tablewidth = "WIDTH=\"$width\"";
154 $innertablewidth = "WIDTH=\"100%\"";
156 echo "<TABLE $tablealign $tablewidth BORDER=0 CELLPADDING=\"$border\" CELLSPACING=0>";
157 echo "<TR><TD BGCOLOR=\"$THEME->borders\">\n";
158 echo "<TABLE $innertablewidth BORDER=0 CELLPADDING=\"$padding\" CELLSPACING=0><TR><TD BGCOLOR=\"$color\">";
161 function print_simple_box_end() {
162 echo "</TD></TR></TABLE>";
163 echo "</TD></TR></TABLE>";
166 function print_single_button($link, $options, $label="OK") {
167 echo "<FORM ACTION=\"$link\" METHOD=GET>";
169 foreach ($options as $name => $value) {
170 echo "<INPUT TYPE=hidden NAME=\"$name\" VALUE=\"$value\">";
173 echo "<INPUT TYPE=submit VALUE=\"$label\"></FORM>";
176 function print_spacer($height=1, $width=1, $br=true) {
178 echo "<IMG HEIGHT=\"$height\" WIDTH=\"$width\" SRC=\"$CFG->wwwroot/pix/spacer.gif\" ALT=\"\">";
184 function print_file_picture($path, $courseid=0, $height="", $width="", $link="") {
185 // Given the path to a picture file in a course, or a URL,
186 // this function includes the picture in the page.
190 $height = "HEIGHT=\"$height\"";
193 $width = "WIDTH=\"$width\"";
196 echo "<A HREF=\"$link\">";
198 if (substr(strtolower($path), 0, 7) == "http://") {
199 echo "<IMG BORDER=0 $height $width SRC=\"$path\">";
201 } else if ($courseid) {
202 echo "<IMG BORDER=0 $height $width SRC=\"";
203 if ($CFG->slasharguments) { // Use this method if possible for better caching
204 echo "$CFG->wwwroot/file.php/$courseid/$path";
206 echo "$CFG->wwwroot/file.php?file=$courseid/$path";
210 echo "Error: must pass URL or course";
217 function print_user_picture($userid, $courseid, $picture, $large=false, $returnstring=false) {
220 $output = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$userid&course=$courseid\">";
229 if ($CFG->slasharguments) { // Use this method if possible for better caching
230 $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
232 $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php?file=/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
235 $output .= "<IMG SRC=\"$CFG->wwwroot/user/default/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
246 function print_table($table) {
247 // Prints a nicely formatted table.
248 // $table is an object with several properties.
249 // $table->head is an array of heading names.
250 // $table->align is an array of column alignments
251 // $table->size is an array of column sizes
252 // $table->data[] is an array of arrays containing the data.
253 // $table->width is an percentage of the page
254 // $table->cellpadding padding on each cell
255 // $table->cellspacing spacing between cells
257 if (isset($table->align)) {
258 foreach ($table->align as $key => $aa) {
260 $align[$key] = " ALIGN=\"$aa\"";
266 if (isset($table->size)) {
267 foreach ($table->size as $key => $ss) {
269 $size[$key] = " WIDTH=\"$ss\"";
276 if (!$table->width) {
277 $table->width = "80%";
280 if (!$table->cellpadding) {
281 $table->cellpadding = "5";
284 if (!$table->cellspacing) {
285 $table->cellspacing = "1";
288 print_simple_box_start("CENTER", "$table->width", "#FFFFFF", 0);
289 echo "<TABLE WIDTH=100% BORDER=0 valign=top align=center ";
290 echo " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\">\n";
294 foreach ($table->head as $key => $heading) {
295 echo "<TH VALIGN=top ".$align[$key].$size[$key].">$heading</TH>";
300 foreach ($table->data as $row) {
301 echo "<TR VALIGN=TOP>";
302 foreach ($row as $key => $item) {
303 echo "<TD ".$align[$key].$size[$key].">$item</TD>";
308 print_simple_box_end();
313 function print_editing_switch($courseid) {
316 if (isteacher($courseid)) {
317 if ($USER->editing) {
318 echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=off\">Turn editing off</A>";
320 echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=on\">Turn editing on</A>";
325 function format_float($num, $places=0) {
326 return sprintf("%.$places"."f", $num);
329 function print_textarea($richedit, $rows, $cols, $width, $height, $name, $value="") {
333 echo "<object id=richedit style=\"BACKGROUND-COLOR: buttonface\"";
334 echo " data=\"$CFG->wwwroot/lib/rte/richedit.html\"";
335 echo " width=\"$width\" height=\"$height\" ";
336 echo " type=\"text/x-scriptlet\" VIEWASTEXT></object>\n";
337 echo "<TEXTAREA style=\"display:none\" NAME=\"$name\" ROWS=1 COLS=1>";
339 echo "</TEXTAREA>\n";
341 echo "<TEXTAREA name=\"$name\" rows=\"$rows\" cols=\"$cols\" wrap=virtual>";
343 echo "</TEXTAREA>\n";
347 function print_richedit_javascript($form, $name, $source="no") {
348 echo "<SCRIPT language=\"JavaScript\" event=\"onload\" for=\"window\">\n";
349 echo " document.richedit.options = \"history=no;source=$source\";";
350 echo " document.richedit.docHtml = $form.$name.innerText;";
355 function update_course_icon($courseid) {
356 // Used to be an icon, but it's now a simple form button
359 if (isteacher($courseid)) {
360 if ($USER->editing) {
361 $string = get_string("turneditingoff");
364 $string = get_string("turneditingon");
367 return "<FORM TARGET=_parent METHOD=GET ACTION=\"$CFG->wwwroot/course/view.php\">".
368 "<INPUT TYPE=hidden NAME=id VALUE=\"$courseid\">".
369 "<INPUT TYPE=hidden NAME=edit VALUE=\"$edit\">".
370 "<INPUT TYPE=submit VALUE=\"$string\"></FORM>";
374 function update_module_button($moduleid, $courseid, $string) {
375 // Prints the editing button on a module "view" page
378 if (isteacher($courseid)) {
379 $string = get_string("updatethis", "", $string);
380 return "<FORM TARGET=_parent METHOD=GET ACTION=\"$CFG->wwwroot/course/mod.php\">".
381 "<INPUT TYPE=hidden NAME=update VALUE=\"$moduleid\">".
382 "<INPUT TYPE=hidden NAME=return VALUE=\"true\">".
383 "<INPUT TYPE=submit VALUE=\"$string\"></FORM>";
388 function print_date_selector($day, $month, $year, $currenttime=0) {
389 // Currenttime is a default timestamp in GMT
390 // Prints form items with the names $day, $month and $year
393 $currenttime = time();
395 $currentdate = usergetdate($currenttime);
397 for ($i=1; $i<=31; $i++) {
400 for ($i=1; $i<=12; $i++) {
401 $months[$i] = date("F", mktime(0,0,0,$i,1,2000));
403 for ($i=2000; $i<=2010; $i++) {
406 choose_from_menu($days, $day, $currentdate[mday], "");
407 choose_from_menu($months, $month, $currentdate[mon], "");
408 choose_from_menu($years, $year, $currentdate[year], "");
411 function print_time_selector($hour, $minute, $currenttime=0) {
412 // Currenttime is a default timestamp in GMT
413 // Prints form items with the names $hour and $minute
416 $currenttime = time();
418 $currentdate = usergetdate($currenttime);
419 for ($i=0; $i<=23; $i++) {
420 $hours[$i] = sprintf("%02d",$i);
422 for ($i=0; $i<=59; $i++) {
423 $minutes[$i] = sprintf("%02d",$i);
425 choose_from_menu($hours, $hour, $currentdate[hours], "");
426 choose_from_menu($minutes, $minute, $currentdate[minutes], "");
429 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0) {
430 // Given date parts in user time, produce a GMT timestamp
432 return mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
435 function format_time($totalsecs, $str=NULL) {
436 // Given an amount of time in seconds, prints it
437 // nicely as months, days, hours etc as needed
439 $totalsecs = abs($totalsecs);
441 if (!$str) { // Create the str structure the slow way
442 $str->day = get_string("day");
443 $str->days = get_string("days");
444 $str->hour = get_string("hour");
445 $str->hours = get_string("hours");
446 $str->min = get_string("min");
447 $str->mins = get_string("mins");
448 $str->sec = get_string("sec");
449 $str->secs = get_string("secs");
452 $days = floor($totalsecs/86400);
453 $remainder = $totalsecs - ($days*86400);
454 $hours = floor($remainder/3600);
455 $remainder = $remainder - ($hours*3600);
456 $mins = floor($remainder/60);
457 $secs = $remainder - ($mins*60);
459 $ss = ($secs == 1) ? $str->sec : $str->secs;
460 $sm = ($mins == 1) ? $str->min : $str->mins;
461 $sh = ($hours == 1) ? $str->hour : $str->hours;
462 $sd = ($days == 1) ? $str->day : $str->days;
464 if ($days) $odays = "$days $sd";
465 if ($hours) $ohours = "$hours $sh";
466 if ($mins) $omins = "$mins $sm";
467 if ($secs) $osecs = "$secs $ss";
469 if ($days) return "$odays $ohours";
470 if ($hours) return "$ohours $omins";
471 if ($mins) return "$omins $osecs";
472 if ($secs) return "$osecs";
473 return get_string("now");
476 function userdate($date, $format="", $timezone=99) {
477 // Returns a formatted string that represents a date in user time
478 // WARNING: note that the format is for strftime(), not date().
483 $format = "%A, %e %B %Y, %I:%M %p";
485 if ($timezone == 99) {
486 if (isset($USER->timezone)) {
487 $timezone = (float)$USER->timezone;
490 if (abs($timezone) > 12) {
491 return strftime("$format", $date);
493 return gmstrftime($format, $date + (int)($timezone * 3600));
496 function usergetdate($date, $timezone=99) {
497 // Given a $date timestamp in GMT, returns an array
498 // that represents the date in user time
502 if ($timezone == 99) {
503 $timezone = (float)$USER->timezone;
505 if (abs($timezone) > 12) {
506 return getdate($date);
508 //There is no gmgetdate so I have to fake it...
509 $date = $date + (int)($timezone * 3600);
510 $getdate["seconds"] = gmstrftime("%S", $date);
511 $getdate["minutes"] = gmstrftime("%M", $date);
512 $getdate["hours"] = gmstrftime("%H", $date);
513 $getdate["mday"] = gmstrftime("%d", $date);
514 $getdate["wday"] = gmstrftime("%u", $date);
515 $getdate["mon"] = gmstrftime("%m", $date);
516 $getdate["year"] = gmstrftime("%Y", $date);
517 $getdate["yday"] = gmstrftime("%j", $date);
518 $getdate["weekday"] = gmstrftime("%A", $date);
519 $getdate["month"] = gmstrftime("%B", $date);
523 function usertime($date, $timezone=99) {
524 // Given a GMT timestamp (seconds since epoch), offsets it by
525 // the timezone. eg 3pm in India is 3pm GMT - 7 * 3600 seconds
528 if ($timezone == 99) {
529 $timezone = (float)$USER->timezone;
531 if (abs($timezone) > 12) {
534 return $date - (int)($timezone * 3600);
537 function usergetmidnight($date, $timezone=99) {
538 // Given a time, return the GMT timestamp of the most recent midnight
539 // for the current user.
542 if ($timezone == 99) {
543 $timezone = (float)$USER->timezone;
546 $userdate = usergetdate($date, $timezone);
548 if (abs($timezone) > 12) {
549 return mktime(0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
552 $timemidnight = gmmktime (0, 0, 0, $userdate["mon"], $userdate["mday"], $userdate["year"]);
553 return usertime($timemidnight, $timezone); // Time of midnight of this user's day, in GMT
557 function usertimezone($timezone=99) {
558 // returns a string that prints the user's timezone
561 if ($timezone == 99) {
562 $timezone = (float)$USER->timezone;
564 if (abs($timezone) > 12) {
565 return "server time";
567 if (abs($timezone) < 0.5) {
571 return "GMT+$timezone";
573 return "GMT$timezone";
578 function error ($message, $link="") {
579 global $CFG, $SESSION;
581 print_header(get_string("error"));
583 print_simple_box($message, "center", "", "#FFBBBB");
586 if ( !empty($SESSION->fromurl) ) {
587 $link = "$SESSION->fromurl";
588 unset($SESSION->fromurl);
589 save_session("SESSION");
591 $link = "$CFG->wwwroot";
594 print_continue($link);
599 function helpbutton ($page, $title="", $module="moodle", $image=true, $text="") {
600 // $page = the keyword that defines a help page
601 // $title = the title of links, rollover tips, alt tags etc
602 // $module = which module is the page defined in
603 // $image = use a help image for the link? (otherwise uses text)
604 // $text = if defined then this text is used in the page, and
605 // the $page variable is ignored.
612 $linkobject = "<IMG BORDER=0 HEIGHT=17 WIDTH=22 ALT=\"$title\" SRC=\"$CFG->wwwroot/pix/help.gif\">";
614 $linkobject = $title;
617 $url = "/help.php?module=$module&text=$text";
619 $url = "/help.php?module=$module&file=$page.html";
621 link_to_popup_window ($url, "popup", $linkobject, 400, 500, $title);
624 function notice ($message, $link="") {
625 global $THEME, $HTTP_REFERER;
628 $link = $HTTP_REFERER;
632 print_simple_box($message, "center", "", "$THEME->cellheading");
633 print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
638 function notice_yesno ($message, $linkyes, $linkno) {
641 print_simple_box_start("center", "", "$THEME->cellheading");
642 echo "<P ALIGN=CENTER><FONT SIZE=3>$message</FONT></P>";
643 echo "<P ALIGN=CENTER><FONT SIZE=3><B>";
644 echo "<A HREF=\"$linkyes\">".get_string("yes")."</A>";
645 echo " ";
646 echo "<A HREF=\"$linkno\">".get_string("no")."</A>";
647 echo "</B></FONT></P>";
648 print_simple_box_end();
651 function redirect($url, $message="", $delay=0) {
652 // Uses META tags to redirect the user, after printing a notice
654 echo "<META HTTP-EQUIV='Refresh' CONTENT='$delay; URL=$url'>";
656 if (!empty($message)) {
659 echo "<P>$message</P>";
660 echo "<P>( <A HREF=\"$url\">".get_string("continue")."</A> )</P>";
666 function notify ($message) {
667 echo "<P align=center><B><FONT COLOR=#FF0000>$message</FONT></B></P>\n";
672 /// PARAMETER HANDLING ////////////////////////////////////////////////////
674 function require_variable($var) {
676 error("A required parameter was missing");
680 function optional_variable(&$var, $default=0) {
689 /// DATABASE HANDLING ////////////////////////////////////////////////
691 function execute_sql($command, $feedback=true) {
692 // Completely general
696 $result = $db->Execute("$command");
700 echo "<P><FONT COLOR=green><B>".get_string("success")."</B></FONT></P>";
705 echo "<P><FONT COLOR=red><B>".get_string("error")."</B></FONT></P>";
711 function modify_database($sqlfile) {
712 // Assumes that the input text file consists of a number
713 // of SQL statements ENDING WITH SEMICOLONS. The semicolons
714 // MUST be the last character in a line.
715 // Lines that are blank or that start with "#" are ignored.
716 // Only tested with mysql dump files (mysqldump -p -d moodle)
719 if (file_exists($sqlfile)) {
721 $lines = file($sqlfile);
724 while ( list($i, $line) = each($lines) ) {
726 $length = strlen($line);
728 if ($length && substr($line, 0, 1) <> "#") {
729 if (substr($line, $length-1, 1) == ";") {
730 $line = substr($line, 0, $length-1); // strip ;
732 if (! execute_sql($command)) {
744 echo "<P>Tried to modify database, but \"$sqlfile\" doesn't exist!</P>";
751 function record_exists($table, $field, $value) {
754 $rs = $db->Execute("SELECT * FROM $table WHERE $field = '$value' LIMIT 1");
755 if (!$rs) return false;
757 if ( $rs->RecordCount() ) {
764 function record_exists_sql($sql) {
767 $rs = $db->Execute($sql);
768 if (!$rs) return false;
770 if ( $rs->RecordCount() ) {
778 function count_records($table, $selector, $value) {
779 // Get all the records and count them
782 $rs = $db->Execute("SELECT COUNT(*) FROM $table WHERE $selector = '$value'");
785 return $rs->fields[0];
788 function count_records_sql($sql) {
789 // Get all the records and count them
792 $rs = $db->Execute("$sql");
795 return $rs->fields[0];
798 function get_record($table, $selector, $value) {
799 // Get a single record as an object
802 $rs = $db->Execute("SELECT * FROM $table WHERE $selector = '$value'");
803 if (!$rs) return false;
805 if ( $rs->RecordCount() == 1 ) {
806 return (object)$rs->fields;
812 function get_record_sql($sql) {
813 // Get a single record as an object
814 // The sql statement is provided as a string.
818 $rs = $db->Execute("$sql");
819 if (!$rs) return false;
821 if ( $rs->RecordCount() == 1 ) {
822 return (object)$rs->fields;
828 function get_records($table, $selector, $value, $sort="", $fields="*") {
829 // Get a number of records as an array of objects
830 // Can optionally be sorted eg "time ASC" or "time DESC"
831 // If "fields" is specified, only those fields are returned
832 // The "key" is the first column returned, eg usually "id"
836 $sortorder = "ORDER BY $sort";
838 $sql = "SELECT $fields FROM $table WHERE $selector = '$value' $sortorder";
840 return get_records_sql($sql);
844 function get_records_list($table, $selector, $values, $sort="", $fields="*") {
845 // Get a number of records as an array of objects
846 // Differs from get_records() in that the values variable
847 // can be a comma-separated list of values eg "4,5,6,10"
848 // Can optionally be sorted eg "time ASC" or "time DESC"
849 // The "key" is the first column returned, eg usually "id"
853 $sortorder = "ORDER BY $sort";
855 $sql = "SELECT $fields FROM $table WHERE $selector in ($values) $sortorder";
857 return get_records_sql($sql);
861 function get_records_sql($sql) {
862 // Get a number of records as an array of objects
863 // The "key" is the first column returned, eg usually "id"
864 // The sql statement is provided as a string.
868 $rs = $db->Execute("$sql");
869 if (!$rs) return false;
871 if ( $rs->RecordCount() > 0 ) {
872 if ($records = $rs->GetAssoc(true)) {
873 foreach ($records as $key => $record) {
874 $objects[$key] = (object) $record;
885 function get_records_sql_menu($sql) {
886 // Given an SQL select, this function returns an associative
887 // array of the first two columns. This is most useful in
888 // combination with the choose_from_menu function to create
893 $rs = $db->Execute("$sql");
894 if (!$rs) return false;
896 if ( $rs->RecordCount() > 0 ) {
898 $menu[$rs->fields[0]] = $rs->fields[1];
908 function get_field($table, $field, $selector, $value) {
911 $rs = $db->Execute("SELECT $field FROM $table WHERE $selector = '$value'");
912 if (!$rs) return false;
914 if ( $rs->RecordCount() == 1 ) {
915 return $rs->fields["$field"];
921 function set_field($table, $field, $newvalue, $selector, $value) {
924 return $db->Execute("UPDATE $table SET $field = '$newvalue' WHERE $selector = '$value'");
927 function set_config($name, $value) {
928 // No need for get_config because they are usually always available in $CFG
930 if (get_field("config", "value", "name", $name)) {
931 return set_field("config", "value", $value, "name", $name);
933 $config->name = $name;
934 $config->value = $value;
935 return insert_record("config", $config);
939 function delete_records($table, $selector, $value) {
940 // Delete one or more records from a table
943 return $db->Execute("DELETE FROM $table WHERE $selector = '$value'");
946 function insert_record($table, $dataobject) {
947 // Insert a record into a table and return the "id" field
948 // $dataobject is an object containing needed data
952 // Determine all the fields needed
953 if (! $columns = $db->MetaColumns("$table")) {
957 $data = (array)$dataobject;
959 // Pull out data matching these fields
960 foreach ($columns as $column) {
961 if ($column->name <> "id" && isset($data[$column->name]) ) {
962 $ddd[$column->name] = $data[$column->name];
966 // Construct SQL queries
967 if (! $numddd = count($ddd)) {
975 foreach ($ddd as $key => $value) {
977 $insert .= "$key = '$value'";
978 $select .= "$key = '$value'";
979 if ($count < $numddd) {
985 if (! $rs = $db->Execute("INSERT INTO $table SET $insert")) {
989 // Pull it out again to find the id. This is the most cross-platform method.
990 if ($rs = $db->Execute("SELECT id FROM $table WHERE $select")) {
991 return $rs->fields[0];
998 function update_record($table, $dataobject) {
999 // Update a record in a table
1000 // $dataobject is an object containing needed data
1004 if (! isset($dataobject->id) ) {
1008 // Determine all the fields in the table
1009 if (!$columns = $db->MetaColumns($table)) {
1012 $data = (array)$dataobject;
1014 // Pull out data matching these fields
1015 foreach ($columns as $column) {
1016 if ($column->name <> "id" && isset($data[$column->name]) ) {
1017 $ddd[$column->name] = $data[$column->name];
1021 // Construct SQL queries
1022 $numddd = count($ddd);
1026 foreach ($ddd as $key => $value) {
1028 $update .= "$key = '$value'";
1029 if ($count < $numddd) {
1034 if ($rs = $db->Execute("UPDATE $table SET $update WHERE id = '$dataobject->id'")) {
1042 function print_object($object) {
1043 // Mostly just for debugging
1045 $array = (array)$object;
1046 foreach ($array as $key => $item) {
1047 echo "$key -> $item <BR>";
1052 /// USER DATABASE ////////////////////////////////////////////////
1054 function get_user_info_from_db($field, $value) {
1058 if (!$field || !$value)
1061 if (! $result = $db->Execute("SELECT * FROM user WHERE $field = '$value' AND deleted <> '1'")) {
1062 error("Could not find any active users!");
1065 if ( $result->RecordCount() == 1 ) {
1066 $user = (object)$result->fields;
1068 $rs = $db->Execute("SELECT course FROM user_students WHERE user = '$user->id' ");
1070 $course = $rs->fields["course"];
1071 $user->student["$course"] = true;
1075 $rs = $db->Execute("SELECT course FROM user_teachers WHERE user = '$user->id' ");
1077 $course = $rs->fields["course"];
1078 $user->teacher["$course"] = true;
1082 $rs = $db->Execute("SELECT * FROM user_admins WHERE user = '$user->id' ");
1084 $user->admin = true;
1088 if ($course = get_site()) {
1089 // Everyone is always a member of the top course
1090 $user->student["$course->id"] = true;
1100 function update_user_in_db() {
1102 global $db, $USER, $REMOTE_ADDR;
1104 if (!isset($USER->id))
1108 if ($db->Execute("UPDATE user SET lastIP='$REMOTE_ADDR', lastaccess='$timenow' WHERE id = '$USER->id' ")) {
1115 function require_login($courseid=0) {
1116 // This function checks that the current user is logged in, and optionally
1117 // whether they are "logged in" or allowed to be in a particular course.
1118 // If not, then it redirects them to the site login or course enrolment.
1120 global $CFG, $SESSION, $USER, $FULLME, $HTTP_REFERER, $PHPSESSID;
1122 // First check that the user is logged in to the site.
1124 if (! (isset($USER->loggedin) and $USER->confirmed and ($USER->site == $CFG->wwwroot)) ) { // They're not
1125 $SESSION->wantsurl = $FULLME;
1126 $SESSION->fromurl = $HTTP_REFERER;
1127 save_session("SESSION");
1129 save_session("USER");
1130 if ($PHPSESSID) { // Cookies not enabled.
1131 redirect("$CFG->wwwroot/login/index.php?PHPSESSID=$PHPSESSID");
1133 redirect("$CFG->wwwroot/login/index.php");
1138 // Next, check if the user can be in a particular course
1140 if ($USER->student[$courseid] || $USER->teacher[$courseid] || $USER->admin) {
1141 if (!isset($USER->realuser)) { // Don't update if this isn't a realuser
1142 update_user_in_db();
1144 if (!$USER->email) { // User logged in, but has not set up profile!
1145 // This can occur with external authentication
1146 redirect("$CFG->wwwroot/user/edit.php?id=$USER->id&course=$courseid");
1149 return; // user is a member of this course.
1151 if (! $course = get_record("course", "id", $courseid)) {
1152 error("That course doesn't exist");
1154 if ($USER->username == "guest") {
1155 switch ($course->guest) {
1156 case 0: // Guests not allowed
1158 notice(get_string("guestsnotallowed", "", $course->fullname));
1160 case 1: // Guests allowed
1161 update_user_in_db();
1163 case 2: // Guests allowed with key (drop through)
1168 // Currently not enrolled in the course, so see if they want to enrol
1169 $SESSION->wantsurl = $FULLME;
1170 save_session("SESSION");
1171 redirect("$CFG->wwwroot/course/enrol.php?id=$courseid");
1178 function update_login_count() {
1183 if (empty($SESSION->logincount)) {
1184 $SESSION->logincount = 1;
1186 $SESSION->logincount++;
1188 save_session("SESSION");
1190 if ($SESSION->logincount > $max_logins) {
1191 unset($SESSION->wantsurl);
1192 save_session("SESSION");
1193 error("Sorry, you have exceeded the allowed number of login attempts. Restart your browser.");
1197 function remove_admin($user) {
1200 return $db->Execute("DELETE FROM user_admins WHERE user = '$user'");
1203 function remove_teacher($user, $course=0) {
1207 /// First delete any crucial stuff that might still send mail
1208 if ($forums = get_records("forum", "course", $course)) {
1209 foreach ($forums as $forum) {
1210 $db->Execute("DELETE FROM forum_subscriptions WHERE forum = '$forum->id' AND user = '$user'");
1213 return $db->Execute("DELETE FROM user_teachers WHERE user = '$user' AND course = '$course'");
1215 delete_records("forum_subscriptions", "user", $user);
1216 return delete_records("user_teachers", "user", $user);
1221 function enrol_student($user, $course) {
1226 $rs = $db->Execute("INSERT INTO user_students (user, course, start, end, time)
1227 VALUES ($user, $course, 0, 0, $timenow)");
1235 function unenrol_student($user, $course=0) {
1239 /// First delete any crucial stuff that might still send mail
1240 if ($forums = get_records("forum", "course", $course)) {
1241 foreach ($forums as $forum) {
1242 $db->Execute("DELETE FROM forum_subscriptions WHERE forum = '$forum->id' AND user = '$user'");
1245 return $db->Execute("DELETE FROM user_students WHERE user = '$user' AND course = '$course'");
1248 delete_records("forum_subscriptions", "user", $user);
1249 return delete_records("user_students", "user", $user);
1254 function isadmin($userid=0) {
1258 return $USER->admin;
1261 return record_exists_sql("SELECT * FROM user_admins WHERE user='$userid'");
1264 function isteacher($courseid, $userid=0) {
1267 if (isadmin($userid)) { // admins can do anything the teacher can
1272 return $USER->teacher[$courseid];
1275 return record_exists_sql("SELECT * FROM user_teachers WHERE user='$userid' AND course='$courseid'");
1279 function isstudent($courseid, $userid=0) {
1283 return $USER->student[$courseid];
1286 $timenow = time(); // todo: add time check below
1288 return record_exists_sql("SELECT * FROM user_students WHERE user='$userid' AND course='$courseid'");
1291 function isguest($userid=0) {
1295 return ($USER->username == "guest");
1298 return record_exists_sql("SELECT * FROM user WHERE id='$userid' AND username = 'guest' ");
1301 function isediting($courseid, $user=NULL) {
1306 return ($user->editing and isteacher($courseid, $user->id));
1309 function reset_login_count() {
1312 $SESSION->logincount = 0;
1313 save_session("SESSION");
1317 function set_moodle_cookie($thing) {
1320 $seconds = 60*60*24*$days;
1322 setCookie ('MOODLEID', "", time() - 3600, "/");
1323 setCookie ('MOODLEID', rc4encrypt($thing), time()+$seconds, "/");
1327 function get_moodle_cookie() {
1329 return rc4decrypt($MOODLEID);
1333 function save_session($VAR) {
1334 // Copies temporary session variable to permanent sesson variable
1335 // eg $_SESSION["USER"] = $USER;
1337 $_SESSION[$VAR] = $$VAR;
1341 function create_user_record($username, $password) {
1342 // Creates a bare-bones user record
1343 global $REMOTE_ADDR, $CFG;
1345 if ($CFG->auth_update_userinfo and function_exists(auth_get_userinfo)) {
1346 if ($newinfo = auth_get_userinfo($username)) {
1347 foreach ($newinfo as $key=>$value){
1348 $newuser->$key = $value;
1353 $newuser->username = $username;
1354 $newuser->password = md5($password);
1355 $newuser->lang = $CFG->lang;
1356 $newuser->confirmed = 1;
1357 $newuser->lastIP = $REMOTE_ADDR;
1358 $newuser->timemodified = time();
1360 if (insert_record("user", $newuser)) {
1361 return get_user_info_from_db("username", $username);
1366 function authenticate_user_login($username, $password) {
1367 // Given a username and password, this function looks them
1368 // up using the currently selected authentication mechanism,
1369 // and if the authentication is successful, it returns a
1370 // valid $user object from the 'user' table.
1372 // Uses auth_ functions from the currently active auth module
1376 if (!isset($CFG->auth)) {
1377 $CFG->auth = "email"; // Default authentication module
1380 require_once("$CFG->dirroot/auth/$CFG->auth/lib.php");
1382 if (auth_user_login($username, $password)) { // Successful authentication
1384 if ($user = get_user_info_from_db("username", $username)) {
1385 if (md5($password) <> $user->password) {
1386 set_field("user", "password", md5($password), "username", $username);
1391 return create_user_record($username, $password);
1398 function get_site () {
1399 // Returns $course object of the top-level site.
1400 if ( $course = get_record("course", "category", 0)) {
1407 function get_admin () {
1408 // Returns $user object of the main admin user
1410 if ( $admins = get_records_sql("SELECT u.* FROM user u, user_admins a WHERE a.user = u.id ORDER BY u.id ASC")) {
1411 foreach ($admins as $admin) {
1412 return $admin; // ie the first one
1419 function get_teacher($courseid) {
1420 // Returns $user object of the main teacher for a course
1421 if ( $teachers = get_records_sql("SELECT u.* FROM user u, user_teachers t
1422 WHERE t.user = u.id AND t.course = '$courseid'
1423 ORDER BY t.authority ASC")) {
1424 foreach ($teachers as $teacher) {
1425 if ($teacher->authority) {
1426 return $teacher; // the highest authority teacher
1434 function get_course_students($courseid, $sort="u.lastaccess DESC") {
1435 return get_records_sql("SELECT u.* FROM user u, user_students s
1436 WHERE s.course = '$courseid' AND s.user = u.id AND u.deleted = '0'
1440 function get_course_teachers($courseid, $sort="t.authority ASC") {
1441 return get_records_sql("SELECT u.*,t.authority,t.role FROM user u, user_teachers t
1442 WHERE t.course = '$courseid' AND t.user = u.id AND u.deleted = '0'
1446 function get_course_users($courseid, $sort="u.lastaccess DESC") {
1447 // Using this method because the direct SQL just would not always work!
1449 $teachers = get_course_teachers($courseid, $sort);
1450 $students = get_course_students($courseid, $sort);
1452 if ($teachers and $students) {
1453 return array_merge($teachers, $students);
1454 } else if ($teachers) {
1460 // return get_records_sql("SELECT u.* FROM user u, user_students s, user_teachers t
1461 // WHERE (s.course = '$courseid' AND s.user = u.id) OR
1462 // (t.course = '$courseid' AND t.user = u.id)
1463 // ORDER BY $sort");
1468 /// MODULE FUNCTIONS /////////////////////////////////////////////////
1470 function get_coursemodule_from_instance($modulename, $instance, $courseid) {
1471 // Given an instance of a module, finds the coursemodule description
1473 return get_record_sql("SELECT cm.*, m.name
1474 FROM course_modules cm, modules md, $modulename m
1475 WHERE cm.course = '$courseid' AND
1476 cm.deleted = '0' AND
1477 cm.instance = m.id AND
1478 md.name = '$modulename' AND
1479 md.id = cm.module AND
1480 m.id = '$instance'");
1484 function get_all_instances_in_course($modulename, $courseid, $sort="cw.section") {
1485 // Returns an array of all the active instances of a particular
1486 // module in a given course. Returns false on any errors.
1488 return get_records_sql("SELECT m.*,cw.section,cm.id as coursemodule
1489 FROM course_modules cm, course_sections cw, modules md, $modulename m
1490 WHERE cm.course = '$courseid' AND
1491 cm.instance = m.id AND
1492 cm.deleted = '0' AND
1493 cm.section = cw.id AND
1494 md.name = '$modulename' AND
1503 /// CORRESPONDENCE ////////////////////////////////////////////////
1505 function email_to_user($user, $from, $subject, $messagetext, $messagehtml="", $attachment="", $attachname="") {
1506 // user - a user record as an object
1507 // from - a user record as an object
1508 // subject - plain text subject line of the email
1509 // messagetext - plain text version of the message
1510 // messagehtml - complete html version of the message (optional)
1511 // attachment - a file on the filesystem, relative to $CFG->dataroot
1512 // attachname - the name of the file (extension indicates MIME)
1514 global $CFG, $_SERVER;
1516 include_once("$CFG->libdir/phpmailer/class.phpmailer.php");
1522 $mail = new phpmailer;
1524 $mail->Version = "Moodle $CFG->version"; // mailer version
1525 $mail->PluginDir = "$CFG->libdir/phpmailer/"; // plugin directory (eg smtp plugin)
1527 if ($CFG->smtphosts) {
1528 $mail->IsSMTP(); // use SMTP directly
1529 $mail->Host = "$CFG->smtphosts"; // specify main and backup servers
1531 if ($CFG->smtpuser) { // Use SMTP authentication
1532 $mail->SMTPAuth = true;
1533 $mail->Username = $CFG->smtpuser;
1534 $mail->Password = $CFG->smtppass;
1537 $mail->IsMail(); // use PHP mail() = sendmail
1540 $mail->From = "$from->email";
1541 $mail->FromName = "$from->firstname $from->lastname";
1542 $mail->Subject = stripslashes($subject);
1544 $mail->AddAddress("$user->email", "$user->firstname $user->lastname");
1546 $mail->WordWrap = 70; // set word wrap
1549 $mail->IsHTML(true);
1550 $mail->Body = $messagehtml;
1551 $mail->AltBody = "\n$messagetext\n";
1553 $mail->IsHTML(false);
1554 $mail->Body = "\n$messagetext\n";
1557 if ($attachment && $attachname) {
1558 if (ereg( "\\.\\." ,$attachment )) { // Security check for ".." in dir path
1559 $adminuser = get_admin();
1560 $mail->AddAddress("$adminuser->email", "$adminuser->firstname $adminuser->lastname");
1561 $mail->AddStringAttachment("Error in attachment. User attempted to attach a filename with a unsafe name.", "error.txt", "8bit", "text/plain");
1563 include_once("$CFG->dirroot/files/mimetypes.php");
1564 $mimetype = mimeinfo("type", $attachname);
1565 $mail->AddAttachment("$CFG->dataroot/$attachment", "$attachname", "base64", "$mimetype");
1569 if ($mail->Send()) {
1572 echo "ERROR: $mail->ErrorInfo\n";
1574 add_to_log($site->id, "library", "mailer", $_SERVER["REQUEST_URI"], "ERROR: $mail->ErrorInfo");
1580 /// FILE HANDLING /////////////////////////////////////////////
1582 function make_upload_directory($directory) {
1583 // $directory = a string of directory names under $CFG->dataroot
1584 // eg stuff/assignment/1
1585 // Returns full directory if successful, false if not
1589 $currdir = $CFG->dataroot;
1590 if (!file_exists($currdir)) {
1591 if (! mkdir($currdir, 0750)) {
1592 notify("ERROR: You need to create the directory $currdir with web server write access");
1597 $dirarray = explode("/", $directory);
1599 foreach ($dirarray as $dir) {
1600 $currdir = "$currdir/$dir";
1601 if (! file_exists($currdir)) {
1602 if (! mkdir($currdir, 0750)) {
1603 notify("ERROR: Could not find or create a directory ($currdir)");
1612 function make_mod_upload_directory($courseid) {
1615 if (! $moddata = make_upload_directory("$courseid/$CFG->moddata")) {
1619 $strreadme = get_string("readme");
1621 if (file_exists("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt")) {
1622 copy("$CFG->dirroot/lang/$CFG->lang/docs/module_files.txt", "$moddata/$strreadme.txt");
1624 copy("$CFG->dirroot/lang/en/docs/module_files.txt", "$moddata/$strreadme.txt");
1630 function valid_uploaded_file($newfile) {
1631 // Returns current name of file on disk if true
1632 if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
1633 return $newfile['tmp_name'];
1639 function get_max_upload_file_size() {
1640 if (! $filesize = ini_get("upload_max_filesize")) {
1643 return get_real_size($filesize);
1646 function get_directory_list($rootdir, $excludefile="", $descend=true) {
1647 // Returns an array with all the filenames in
1648 // all subdirectories, relative to the given rootdir.
1649 // If excludefile is defined, then that file/directory is ignored
1653 $dir = opendir($rootdir);
1655 while ($file = readdir($dir)) {
1656 if ($file != "." and $file != ".." and $file != "CVS" and $file != $excludefile) {
1657 $fullfile = $rootdir."/".$file;
1658 if ($descend and filetype($fullfile) == "dir") {
1659 $subdirs = get_directory_list($fullfile, $excludefile, $descend);
1660 foreach ($subdirs as $subdir) {
1661 $dirs[] = $file."/".$subdir;
1675 function get_real_size($size=0) {
1676 // Converts numbers like 10M into bytes
1680 $scan['MB'] = 1048576;
1681 $scan['M'] = 1048576;
1685 while (list($key) = each($scan)) {
1686 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1687 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1694 function display_size($size) {
1695 // Converts bytes into display form
1696 if ($size >= 1073741824) {
1697 $size = round($size / 1073741824 * 10) / 10 . "Gb";
1698 } else if ($size >= 1048576) {
1699 $size = round($size / 1048576 * 10) / 10 . "Mb";
1700 } else if ($size >= 1024) {
1701 $size = round($size / 1024 * 10) / 10 . "Kb";
1703 $size = $size . "b";
1708 function clean_filename($string) {
1709 $string = eregi_replace("\.\.", "", $string);
1710 $string = eregi_replace("[^([:alnum:]|\.)]", "_", $string);
1711 return eregi_replace("_+", "_", $string);
1715 /// STRING TRANSLATION ////////////////////////////////////////
1717 function print_string($identifier, $module="", $a=NULL) {
1718 echo get_string($identifier, $module, $a);
1721 function current_language() {
1722 // Returns the code for the current language
1725 if (isset($USER->lang)) { // User language can override site language
1732 function get_string($identifier, $module="", $a=NULL) {
1733 // Return the translated string specified by $identifier as
1734 // for $module. Uses the same format files as STphp.
1735 // $a is an object, string or number that can be used
1736 // within translation strings
1738 // eg "hello \$a->firstname \$a->lastname"
1743 $lang = current_language();
1745 if ($module == "") {
1749 $langpath = "$CFG->dirroot/lang";
1750 $langfile = "$langpath/$lang/$module.php";
1752 if (!file_exists($langfile)) { // try English instead
1753 $langfile = "$langpath/en/$module.php";
1754 if (!file_exists($langfile)) {
1755 return "ERROR: No lang file ($langpath/en/$module.php)!";
1759 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1762 return $resultstring;
1765 if ($lang == "en") {
1766 return "[['$identifier']]";
1768 } else { // Try looking in the english file.
1769 $langfile = "$langpath/en/$module.php";
1770 if (!file_exists($langfile)) {
1771 return "ERROR: No lang file ($langpath/en/$module.php)!";
1773 if ($result = get_string_from_file($identifier, $langfile, "\$resultstring")) {
1775 return $resultstring;
1777 return "[['$identifier']]";
1784 function get_string_from_file($identifier, $langfile, $destination) {
1785 // This function is only used from get_string().
1786 include ($langfile);
1788 if (!isset ($string[$identifier])) {
1792 return "$destination = sprintf(\"".$string[$identifier]."\");";
1796 function get_list_of_languages() {
1797 /// Returns a list of language codes and their full names
1800 if (!$langdirs = get_list_of_plugins("lang")) {
1804 foreach ($langdirs as $lang) {
1805 include("$CFG->dirroot/lang/$lang/moodle.php");
1806 $languages[$lang] = $string["thislanguage"]." ($lang)";
1813 /// ENCRYPTION ////////////////////////////////////////////////
1815 function rc4encrypt($data) {
1816 $password = "nfgjeingjk";
1817 return endecrypt($password, $data, "");
1820 function rc4decrypt($data) {
1821 $password = "nfgjeingjk";
1822 return endecrypt($password, $data, "de");
1825 function endecrypt ($pwd, $data, $case) {
1826 // Based on a class by Mukul Sabharwal [mukulsabharwal@yahoo.com]
1828 if ($case == 'de') {
1829 $data = urldecode($data);
1837 $pwd_length = strlen($pwd);
1839 for ($i = 0; $i <= 255; $i++) {
1840 $key[$i] = ord(substr($pwd, ($i % $pwd_length), 1));
1846 for ($i = 0; $i <= 255; $i++) {
1847 $x = ($x + $box[$i] + $key[$i]) % 256;
1848 $temp_swap = $box[$i];
1849 $box[$i] = $box[$x];
1850 $box[$x] = $temp_swap;
1862 for ($i = 0; $i < strlen($data); $i++) {
1863 $a = ($a + 1) % 256;
1864 $j = ($j + $box[$a]) % 256;
1866 $box[$a] = $box[$j];
1868 $k = $box[(($box[$a] + $box[$j]) % 256)];
1869 $cipherby = ord(substr($data, $i, 1)) ^ $k;
1870 $cipher .= chr($cipherby);
1873 if ($case == 'de') {
1874 $cipher = urldecode(urlencode($cipher));
1876 $cipher = urlencode($cipher);
1883 /// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
1885 function count_words($string) {
1886 $string = strip_tags($string);
1887 return count(preg_split("/\w\b/", $string)) - 1;
1890 function getweek ($startdate, $thedate) {
1891 // Given dates in seconds, how many weeks is the date from startdate
1892 // The first week is 1, the second 2 etc ...
1894 if ($thedate < $startdate) { // error
1898 return floor(($thedate - $startdate) / 604800.0) + 1;
1901 function add_to_log($course, $module, $action, $url="", $info="") {
1902 // Add an entry to the log table. These are "action" focussed rather
1903 // than web server hits, and provide a way to easily reconstruct what
1904 // any particular student has been doing.
1906 // course = the course id
1907 // module = forum, journal, resource, course, user etc
1908 // action = view, edit, post (often but not always the same as the file.php)
1909 // url = the file and parameters used to see the results of the action
1910 // info = additional description information
1913 global $db, $USER, $REMOTE_ADDR;
1915 if (isset($USER->realuser)) { // Don't log
1920 $info = addslashes($info);
1922 $result = $db->Execute("INSERT INTO log
1923 SET time = '$timenow',
1926 ip = '$REMOTE_ADDR',
1932 echo "<P>Error: Could not insert a new entry to the Moodle log</P>"; // Don't throw an error
1936 function generate_password($maxlen=10) {
1937 // returns a randomly generated password of length $maxlen. inspired by
1938 // http://www.phpbuilder.com/columns/jesus19990502.php3
1942 $fillers = "1234567890!$-+";
1943 $wordlist = file($CFG->wordlist);
1945 srand((double) microtime() * 1000000);
1946 $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1947 $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
1948 $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
1950 return substr($word1 . $filler1 . $word2, 0, $maxlen);
1953 function moodle_needs_upgrading() {
1954 // Checks version numbers of Main code and all modules to see
1955 // if there are any mismatches ... returns true or false
1958 include_once("$CFG->dirroot/version.php"); # defines $version and upgrades
1959 if ($CFG->version) {
1960 if ($version > $CFG->version) {
1963 if ($mods = get_list_of_plugins("mod")) {
1964 foreach ($mods as $mod) {
1965 $fullmod = "$CFG->dirroot/mod/$mod";
1967 include_once("$fullmod/version.php"); # defines $module with version etc
1968 if ($currmodule = get_record("modules", "name", $mod)) {
1969 if ($module->version > $currmodule->version) {
1982 function get_list_of_plugins($plugin="mod") {
1983 // Lists plugin directories within some directory
1987 $basedir = opendir("$CFG->dirroot/$plugin");
1988 while ($dir = readdir($basedir)) {
1989 if ($dir == "." || $dir == ".." || $dir == "CVS") {
1992 if (filetype("$CFG->dirroot/$plugin/$dir") != "dir") {
2004 function check_php_version($version="4.1.0") {
2005 // Returns true is the current version of PHP is greater that the specified one
2006 $minversion = intval(str_replace(".", "", $version));
2007 $curversion = intval(str_replace(".", "", phpversion()));
2008 return ($curversion >= $minversion);
2011 function check_browser_version($brand="MSIE", $version=5.5) {
2012 // Checks to see if is a browser matches the specified
2013 // brand and is equal or better version.
2014 global $HTTP_USER_AGENT;
2016 if (!$HTTP_USER_AGENT) {
2019 $string = explode(";", $HTTP_USER_AGENT);
2020 if (!isset($string[1])) {
2023 $string = explode(" ", trim($string[1]));
2024 if (!isset($string[0]) and !isset($string[1])) {
2027 if ($string[0] == $brand and (float)$string[1] >= $version ) {
2033 function can_use_richtext_editor() {
2035 if ($USER->htmleditor and $CFG->htmleditor) {
2036 return check_browser_version("MSIE", 5.5);
2042 function check_gd_version() {
2045 $phpinfo = ob_get_contents();
2048 $phpinfo = explode("\n",$phpinfo);
2052 foreach ($phpinfo as $text) {
2053 $parts = explode('</b>',$text);
2054 foreach ($parts as $key => $val) {
2055 $parts[$key] = strip_tags($val);
2057 if ($parts[0]=="GD Version") {
2058 $gdversion = intval($parts[1]);
2062 return $gdversion; // 1, 2 or 0