Many many changes lumped in here ... not finished yet either.
authormoodler <moodler>
Fri, 20 Dec 2002 14:44:14 +0000 (14:44 +0000)
committermoodler <moodler>
Fri, 20 Dec 2002 14:44:14 +0000 (14:44 +0000)
Basically all the Database functions are in lib/datalib.php
and the web functions are all in lib/weblib.php, so
moodlelib.php is much thinner than it was.

Data functions have been extended ... most old calls will
still work, but now many more SQL commands can be performed
using the datalib functions rather than using SQL.  I'm
currently moving through the whole tree replacing SQL
calls or at least concentrating them in one section of
mod/xxx/lib.php

Still working on forums, quizzes, surveys, resources.

The tree is currently not full working ... some things are
half-completed ... will resume tomorrow.

43 files changed:
admin/admin.php
admin/cron.php
admin/index.php
admin/user.php
config-dist.php
course/categories.php
course/delete.php
course/edit.php
course/index.php
course/lib.php
course/loggraph.php
course/teacher.php
course/teachers.php
course/view.php
index.php
lang/en/moodle.php
lib/datalib.php [moved from lib/database.php with 64% similarity]
lib/db/mysql.sql
lib/moodlelib.php
lib/setup.php
lib/weblib.php
mod/assignment/db/mysql.sql
mod/assignment/lib.php
mod/assignment/view.php
mod/choice/db/mysql.sql
mod/choice/index.php
mod/choice/lib.php
mod/choice/view.php
mod/forum/db/mysql.sql
mod/forum/lib.php
mod/forum/post.php
mod/forum/rate.php
mod/forum/report.php
mod/forum/search.php
mod/journal/db/mysql.sql
mod/journal/edit.php
mod/journal/index.php
mod/journal/lib.php
mod/journal/report.php
mod/journal/view.php
mod/quiz/db/mysql.sql
mod/resource/db/mysql.sql
mod/survey/db/mysql.sql

index d2d32b345e3b03e5398d96cfa5b08e1e5a23afd8..84c2c5aab5d9b2c3bfd955cef8359808c2ce8a72 100644 (file)
 /// Print list of potential admins
 
     if ($search) {
-        $users = get_records_sql("SELECT * from user WHERE confirmed = 1 AND deleted = 0
-                                  AND (firstname LIKE '%$search%' OR 
-                                       lastname LIKE '%$search%' OR 
-                                       email LIKE '%$search%')
-                                  AND username <> 'guest' AND username <> 'changeme'");
+        $users = get_users_search($search);
     } else {
-        $users = get_records_sql("SELECT * from user WHERE confirmed = 1 AND deleted = 0
-                                  AND username <> 'guest' AND username <> 'changeme'");
+        $users = get_users_confirmed();
     }
 
     
index 3d510cd5f0f19543839a227991f4b1b677cce8ca..aca529fc1f6cc7347f8025dfdd698a70a8f691dc 100644 (file)
@@ -11,7 +11,7 @@
 // eg   wget -q -O /dev/null 'http://moodle.somewhere.edu/admin/cron.php'
 // or   php /web/moodle/admin/cron.php 
 
-    $FULLME = "we don't care";
+    $FULLME = "cron";
 
     require("../config.php");
 
@@ -21,7 +21,7 @@
 
 //  Run all cron jobs for each module
 
-    if ($mods = get_records_sql("SELECT * FROM modules WHERE cron > 0 AND (($timenow - lastcron) > cron)")) {
+    if ($mods = get_records_select("modules", "cron > 0 AND (($timenow - lastcron) > cron)")) {
         foreach ($mods as $mod) {
             $libfile = "$CFG->dirroot/mod/$mod->name/lib.php";
             if (file_exists($libfile)) {
 // Unenrol users who haven't logged in for $CFG->longtimenosee
 
     if ($CFG->longtimenosee) { // value in days
-        $cutofftime = $timenow - ($CFG->longtimenosee * 3600 * 24);
-        if ($users = get_records_sql("SELECT u.* FROM user u, user_students s
-                                       WHERE lastaccess > '0' AND 
-                                             lastaccess < '$cutofftime' AND
-                                             u.id = s.user GROUP BY u.id")) {
+        $longtime = $timenow - ($CFG->longtimenosee * 3600 * 24);
+        if ($users = get_users_longtimenosee($longtime)) {
             foreach ($users as $user) {
                 if (unenrol_student($user->id)) {
                     echo "Deleted student enrolment for $user->firstname $user->lastname ($user->id)\n";
 
 // Delete users who haven't confirmed within seven days
 
-    $cutofftime = $timenow - (7 * 24 * 3600);
-    if ($users = get_records_sql("SELECT * FROM user 
-                                  WHERE confirmed = '0' AND 
-                                        firstaccess > '0' AND 
-                                        firstaccess < '$cutofftime'")) {
+    $oneweek = $timenow - (7 * 24 * 3600);
+    if ($users = get_users_unconfirmed($oneweek)) {
         foreach ($users as $user) {
             if (delete_records("user", "id", $user->id)) {
                 echo "Deleted unconfirmed user for $user->firstname $user->lastname ($user->id)\n";
index 057229e93f77394b0a2ff9ca7c4cf2cdfdc0b440..dcff806264c3d780690bac0c4150c343dc3b631c 100644 (file)
 
     include_once("$CFG->dirroot/lib/defaults.php");
 
-    $CFG = (array)$CFG;
     foreach ($defaults as $name => $value) {
-        if (!isset($CFG[$name])) {
-            $config->name  = $name;
-            $config->value = $CFG[$name] = $value;
-            insert_record("config", $config);
+        if (!isset($CFG->$name)) {
+            $CFG->$name = $value;
+            set_config($name, $value);
             $configchange = true;
         }
     }
-    $CFG = (object)$CFG;
+
 
 /// If any new configurations were found then send to the config page to check
 
     }
 
 /// Set up the admin user
-    if (! record_exists_sql("SELECT * FROM user_admins")) {   // No admin user yet
+    if (! record_exists("user_admins")) {   // No admin user yet
         redirect("user.php");
     }
 
index 1bb968de8a5074471fadd0a92b9d5f49a7decc1d..e8f1fbe384f041378073cfc5ea9266f91275af27 100644 (file)
@@ -13,7 +13,7 @@
     optional_variable($dir, "ASC");
     optional_variable($page, 0);
 
-    if (! record_exists_sql("SELECT * FROM user_admins")) {   // No admin user yet
+    if (! record_exists("user_admins")) {   // No admin user yet
         $user->firstname = "Admin";
         $user->lastname  = "User";
         $user->username  = "admin";
 
         // Carry on with the user listing
 
-        if (!$user = get_record_sql("SELECT count(*) as count FROM user WHERE username <> 'guest' AND deleted <> '1'")) {
-            error("Could not search for users?");
-        }
-
-        $usercount = $user->count;
+        $usercount = get_users_count();
 
         $columns = array("name", "email", "city", "country", "lastaccess");
 
             $sort = "firstname";
         }
 
-        if ($users = get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess  from user WHERE username <> 'guest' 
-                                      AND deleted <> '1' ORDER BY $sort $dir LIMIT $page,$recordsperpage")) {
-
+        if ($users = get_users_listing($sort, $dir, $page, $recordsperpage)) {
             print_heading("$usercount ".get_string("users"));
             
             $a->start = $page;
index 09a46019de9e2c9d1a4f9cb4493bb45ce4d0e8f1..48b2b5c2fd16390aaa6813835b2a1e4331dafd82 100644 (file)
 // a different database you will need to set up all your tables by hand  //\r
 // which could be a big job.    See doc/install.html                     //\r
 \r
-$CFG->dbtype    = "mysql";     // eg mysql (postgres7, oracle, access etc)\r
+$CFG->dbtype    = "mysql";     // mysql or postgres7 \r
 $CFG->dbhost    = "localhost"; // eg localhost \r
-$CFG->dbname    = "moodle";    // eg moodle\r
+$CFG->dbname    = "moodletest";    // eg moodle\r
 $CFG->dbuser    = "username";\r
 $CFG->dbpass    = "password";\r
 \r
+$CFG->prefix    = "mdl_";      // Prefix value to use for all table names\r
+\r
 \r
 ///////////////////////////////////////////////////////////////////////////\r
 // Now you need to tell Moodle where it is located. Specify the full\r
index 031a39018c5830c0981532ca846014eb1f3b89b5..921455003aba59a15bcb67dfcb7a181294b7f1c2 100644 (file)
@@ -57,7 +57,7 @@
 
 
 /// Get the existing categories
-    if (!$categories = get_all_categories()) {
+    if (!$categories = get_categories()) {
         // Try and make one
         $cat->name = get_string("miscellaneous");
         if ($cat->id = insert_record("course_categories", $cat)) {
@@ -86,7 +86,7 @@
     }
 
 /// Find any orphan courses that don't yet have a valid category and set to default
-    if ($courses = get_records_sql("SELECT * FROM course WHERE category > 0")) {
+    if ($courses = get_courses()) {
         foreach ($courses as $course) {
             if (!isset( $categories[$course->category] )) {
                 set_field("course", "category", $default, "id", $course->id);
index 45f9a8fc2fb1ec1cbd4be02b4239f634211e48ad..e81599c369bdbd6e4d0f0cb9595780f88307770b 100644 (file)
@@ -23,7 +23,7 @@
            print_header("$site->shortname: $strdeletecourse", $site->fullname, 
                      "<A HREF=\"$CFG->wwwroot/admin\">$stradministration</A> -> $strdeletecourse");
 
-        if ($courses = get_records_sql("SELECT * from course WHERE category > 0 ORDER BY fullname")) {
+        if ($courses = get_courses()) {
             print_heading(get_string("choosecourse"));
             print_simple_box_start("CENTER");
             foreach ($courses as $course) {
@@ -71,7 +71,7 @@
     $strdeleted = get_string("deleted");
     // First delete every instance of every module
 
-    if ($allmods = get_records_sql("SELECT * FROM modules") ) {
+    if ($allmods = get_records("modules") ) {
         foreach ($allmods as $mod) {
             $modname = $mod->name;
             $modfile = "../mod/$modname/lib.php";
index 80bf02002a92cd08854b49e15fe3883a044e5a52..156dcf7c68c5ae407785abfb58906464d54bb475 100644 (file)
@@ -96,7 +96,7 @@
         }
     }
 
-    $form->categories = get_records_sql_menu("SELECT id,name FROM course_categories");
+    $form->categories = get_records_select_menu("course_categories", "", "name", "id,name");
     
     $form->courseformats = array (
              "weeks"  => get_string("formatweeks"),
index d49849fcfb67c8b7cb86f431c288096da31b1e1e..a26cb44f91a408e910ac7f4f1d239212ee1659aa 100644 (file)
@@ -11,7 +11,7 @@
     $strmycourses = get_string("mycourses");
     $strfulllistofcourses = get_string("fulllistofcourses");
 
-    if (!$categories = get_all_categories()) {
+    if (!$categories = get_categories()) {
         error("Could not find any course categories!");
     }
 
index f5a35ddd6e04aa30a30829056f680c447ed6b2f2..01afff49c582635448ad34779ffeb841720474f1 100644 (file)
@@ -17,27 +17,16 @@ function print_log_selector_form($course, $selecteduser=0, $selecteddate="today"
     $users = array();
 
     if ($course->category) {
-        if ($students = get_records_sql("SELECT u.* FROM user u, user_students s 
-                                         WHERE s.course = '$course->id' AND s.user = u.id
-                                         ORDER BY u.lastaccess DESC")) {
-            foreach ($students as $student) {
-                $users["$student->id"] = "$student->firstname $student->lastname";
-            }
-        }
-        if ($teachers = get_records_sql("SELECT u.* FROM user u, user_teachers t 
-                                         WHERE t.course = '$course->id' AND t.user = u.id
-                                         ORDER BY u.lastaccess DESC")) {
-            foreach ($teachers as $teacher) {
-                $users["$teacher->id"] = "$teacher->firstname $teacher->lastname";
-            }
+        if (!$users = get_course_users($course->id, "u.lastaccess DESC")) {
+            $users = array();
         }
-        if ($guest = get_user_info_from_db("username", "guest")) {
+        if ($guest = get_guest()) {
             $users["$guest->id"] = "$guest->firstname $guest->lastname";
         }
     }
 
     if (isadmin()) {
-        if ($ccc = get_records_sql("SELECT * FROM course ORDER BY fullname")) {
+        if ($ccc = get_records("course", "", "", "fullname")) {
             foreach ($ccc as $cc) {
                 if ($cc->category) {
                     $courses["$cc->id"] = "$cc->fullname";
@@ -121,7 +110,7 @@ function print_log($course, $user=0, $date=0, $order="ORDER BY l.time ASC") {
 
     } else {
         $selector = "WHERE l.user = u.id";  // Show all courses
-        if ($ccc = get_records_sql("SELECT * FROM course ORDER BY fullname")) {
+        if ($ccc = get_courses(-1)) {
             foreach ($ccc as $cc) {
                 $courses[$cc->id] = "$cc->shortname";
             }
@@ -137,8 +126,7 @@ function print_log($course, $user=0, $date=0, $order="ORDER BY l.time ASC") {
         $selector .= " AND l.time > '$date' AND l.time < '$enddate'";
     }
 
-    if (!$logs = get_records_sql("SELECT l.*, u.firstname, u.lastname, u.picture 
-                                  FROM log l, user u $selector $order")){
+    if (!$logs = get_logs($select, $order)) {
         notify("No logs found!");
         print_footer($course);
         exit;
@@ -147,11 +135,13 @@ function print_log($course, $user=0, $date=0, $order="ORDER BY l.time ASC") {
     $count=0;
     $tt = getdate(time());
     $today = mktime (0, 0, 0, $tt["mon"], $tt["mday"], $tt["year"]);
-    echo "<P ALIGN=CENTER>Displaying ".count($logs)." records</P>";
+    echo "<P ALIGN=CENTER>";
+    print_string("displayingrecords", "", count($logs));
+    echo "</P>";
     echo "<TABLE BORDER=0 ALIGN=center CELLPADDING=3 CELLSPACING=3>";
     foreach ($logs as $log) {
 
-        if ($ld = get_record_sql("SELECT * FROM log_display WHERE module='$log->module' AND action='$log->action'")) {
+        if ($ld = get_record("log_display", "module", "$log->module", "action", "$log->action")) {
             $log->info = get_field($ld->mtable, $ld->field, "id", $log->info);
         }
 
@@ -179,11 +169,11 @@ function print_all_courses($category="all", $style="full", $maxcount=999, $width
     global $CFG, $USER;
 
     if ($category == "all") {
-        $courses = get_records_sql("SELECT * FROM course WHERE category > 0 ORDER BY fullname ASC");
+        $courses = get_courses();
 
     } else if ($category == "my") {
         if (isset($USER->id)) {
-            if ($courses = get_records_sql("SELECT * FROM course WHERE category > 0 ORDER BY fullname ASC")) {
+            if ($courses = get_courses()) {
                 foreach ($courses as $key => $course) {
                     if (!isteacher($course->id) and !isstudent($course->id)) {
                         unset($courses[$key]);
@@ -193,7 +183,7 @@ function print_all_courses($category="all", $style="full", $maxcount=999, $width
         }
 
     } else {
-        $courses = get_records("course", "category", $category, "fullname ASC");
+        $courses = get_courses($category);
     }
 
     if ($style == "minimal") {
@@ -297,7 +287,7 @@ function print_recent_activity($course) {
         echo "</FONT></P>";
     }
 
-    if (! $logs = get_records_sql("SELECT * FROM log WHERE time > '$USER->lastlogin' AND course = '$course->id' ORDER BY time ASC")) {
+    if (! $logs = get_records_select("log", "time > '$USER->lastlogin' AND course = '$course->id'", "time ASC")) {
         return;
     }
 
@@ -400,11 +390,7 @@ function get_array_of_activities($courseid) {
 
     $mod = array();
 
-    if (!$rawmods = get_records_sql("SELECT cm.*, m.name as modname
-                                     FROM modules m, course_modules cm
-                                     WHERE cm.course = '$courseid' 
-                                       AND cm.deleted = '0'
-                                       AND cm.module = m.id ") ) {
+    if (!$rawmods = get_course_mods($courseid)) {
         return NULL;
     }
 
@@ -435,7 +421,7 @@ function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modname
     $modnamesplural= NULL;    // all course module names (plural form)
     $modnamesused  = NULL;    // course module names used
 
-    if ($allmods = get_records_sql("SELECT * FROM modules") ) {
+    if ($allmods = get_records("modules")) {
         foreach ($allmods as $mod) {
             $modnames[$mod->name] = get_string("modulename", "$mod->name");
             $modnamesplural[$mod->name] = get_string("modulenameplural", "$mod->name");
@@ -445,11 +431,7 @@ function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modname
         error("No modules are installed!");
     }
 
-    if ($rawmods = get_records_sql("SELECT cm.*, m.name as modname
-                                     FROM modules m, course_modules cm
-                                     WHERE cm.course = '$courseid' 
-                                       AND cm.deleted = '0'
-                                       AND cm.module = m.id ") ) {
+    if ($rawmods = get_course_mods($courseid)) {
         foreach($rawmods as $mod) {    // Index the mods
             $mods[$mod->id] = $mod;
             $mods[$mod->id]->modfullname = $modnames[$mod->modname];
@@ -459,17 +441,13 @@ function get_all_mods($courseid, &$mods, &$modnames, &$modnamesplural, &$modname
     }
 }
 
+
 function get_all_sections($courseid) {
     
-    return get_records_sql("SELECT section, id, course, summary, sequence
-                            FROM course_sections 
-                            WHERE course = '$courseid' 
-                            ORDER BY section");
+    return get_records("course_sections", "course", "$courseid", "sections", 
+                       "section, id, course, summary, sequence");
 }
 
-function get_all_categories() {
-    return get_records_sql("SELECT * FROM course_categories ORDER by name");
-}
 
 function print_section_block($heading, $course, $section, $mods, $modnames, $modnamesused, 
                              $absolute=true, $width="100%", $isediting=false) {
@@ -684,7 +662,7 @@ function print_course_categories($categories, $selected="none", $width=180) {
     $strrequireskey = get_string("requireskey");
 
     if ($selected == "index") {  // Print comprehensive index of categories with courses
-        if ($courses = get_records_sql("SELECT * FROM course WHERE category > 0 ORDER BY shortname")) {
+        if ($courses = get_courses()) {
             if (isset($USER->id) and !isadmin()) {
                 print_simple_box_start("CENTER", "100%", $THEME->cellheading);
                 print_heading("<A HREF=\"course/index.php?category=my\">".get_string("mycourses")."</A>", "LEFT");
@@ -773,9 +751,7 @@ function add_mod_to_section($mod) {
 // Returns the course_sections ID where the mod is inserted
     GLOBAL $db;
 
-    if ($section = get_record_sql("SELECT * FROM course_sections 
-                                   WHERE course = '$mod->course' AND section = '$mod->section'") ) {
-
+    if ($section = get_record("course_sections", "course", "$mod->course", "section", "$mod->section")) {
         if ($section->sequence) {
             $newsequence = "$section->sequence,$mod->coursemodule";
         } else {
@@ -857,9 +833,8 @@ function move_module($cm, $move) {
                 return true;
             } else {               // Push onto end of previous section
                 $prevsectionnumber = $thissection->section - 1;
-                if (! $prevsection = get_record_sql("SELECT * FROM course_sections 
-                                                  WHERE course='$thissection->course'
-                                                  AND section='$prevsectionnumber' ")) {
+                if (! $prevsection = get_record("course_sections", "course", "$thissection->course", 
+                                                                   "section", "$prevsectionnumber")) {
                     error("Previous section ($prevsection->id) doesn't exist");
                 }
 
@@ -902,9 +877,8 @@ function move_module($cm, $move) {
 
         if ($last) {
             $nextsectionnumber = $thissection->section + 1;
-            if ($nextsection = get_record_sql("SELECT * FROM course_sections 
-                                            WHERE course='$thissection->course'
-                                            AND section='$nextsectionnumber' ")) {
+            if ($nextsection = get_record("course_sections", "course", "$thissection->course", 
+                                                               "section", "$nextsectionnumber")) {
 
                 if ($nextsection->sequence) {
                     $newsequence = "$cm->id,$nextsection->sequence";
index 58f77cad2b8674e3bd5e8534f7d3bed1f297ac38..481b18f6eb6e3eada57e79b0e62e99ce101d1bd1 100644 (file)
            $timestart = $timefinish;
        }
 
-       if ($rawlogs = get_records_sql("SELECT floor((`time` - $coursestart)/86400) as day, 
-                                              count(*) as num FROM log 
-                                       WHERE user = '$user->id' 
-                                         AND course = '$course->id'
-                                         AND `time` > '$coursestart'
-                                       GROUP BY day ")) {
+       if ($rawlogs = get_logs_usercourse($user->id, $course->id, $coursestart)) {
            foreach ($rawlogs as $rawlog) {
                $logs[$rawlog->day] = $rawlog->num;
            }
            $hours[$i] = userdate($hour, "$hh %p");
        }
 
-       if ($rawlogs = get_records_sql("SELECT floor((`time` - $daystart)/3600) as hour, 
-                                              count(*) as num FROM log 
-                                       WHERE user = '$user->id' 
-                                         AND course = '$course->id'
-                                         AND `time` > '$daystart'
-                                       GROUP BY hour ")) {
+       if ($rawlogs = get_logs_userday($user->id, $course->id, $daystart)) {
            foreach ($rawlogs as $rawlog) {
                $logs[$rawlog->hour] = $rawlog->num;
            }
index 9718df5f58cd9265c01994443affe86f8d58b6d6..4764e965e56a4f66c4f8e2b8f691aeea045c3213 100644 (file)
@@ -32,7 +32,7 @@
            print_header("$site->shortname: $strassignteachers", "$site->fullname", 
                      "<A HREF=\"$CFG->wwwroot/admin\">$stradministration</A> -> $strassignteachers");
 
-        if ($courses = get_records_sql("SELECT * from course WHERE category > 0 ORDER BY fullname")) {
+        if ($courses = get_courses()) {
 
             print_heading(get_string("choosecourse"));
             print_simple_box_start("CENTER");
 /// Print list of potential teachers
 
     if ($search) {
-        $users = get_records_sql("SELECT * from user WHERE confirmed = 1 AND deleted = 0
-                                  AND (firstname LIKE '%$search%' OR 
-                                       lastname LIKE '%$search%' OR 
-                                       email LIKE '%$search%')
-                                  AND username <> 'guest' AND username <> 'changeme'");
+        $users = get_users_search($search);
     } else {
-        $users = get_records_sql("SELECT * from user WHERE confirmed = 1 AND deleted = 0
-                                  AND username <> 'guest' AND username <> 'changeme'");
+        $users = get_users_confirmed();
     }
 
     
index d81f8634115f8df2c782ca7e712acb832198d709..fcf6275ba8e23bdcd7ab04a3eea83d2d3cb29110 100644 (file)
@@ -33,7 +33,7 @@
         }
 
         foreach ($rank as $num => $vals) {
-            if (! $teacher = get_record_sql("SELECT * FROM user_teachers WHERE course='$course->id' and user='$num'")) {
+            if (! $teacher = get_record("user_teachers", "course", "$course->id", "user", "$num")) {
                 error("No such teacher in course $course->shortname with user id $num");
             }
             $teacher->role = $vals[r];
index 9cb0610a5fff1e62e6b249e79d5e611da6139322..7c3dac1ce80ca294f29fdd21f7971458f639ec6e 100644 (file)
@@ -2,8 +2,8 @@
 
 //  Display the course home page.
 
-    require("../config.php");
-    require("lib.php");
+    include_once("../config.php");
+    include_once("lib.php");
 
     optional_variable($id);
     optional_variable($name);
index 8133898ca796fbda2023f2da4e763f18a64a849a..a453883737e2c41837fc972fb551b21a405c483d 100644 (file)
--- a/index.php
+++ b/index.php
@@ -47,7 +47,7 @@
          }
 
          if ($site->newsitems > 0 ) {
-             $categories = get_all_categories();
+             $categories = get_categories();
              if (count($categories) > 1) {
                  print_course_categories($categories, "none", $side);
              } else {
@@ -73,7 +73,7 @@
      if ($site->newsitems == 0 ) {
          print_heading_block(get_string("availablecourses"));
          print_spacer(8,1);
-         $categories = get_all_categories();
+         $categories = get_categories();
          if (count($categories) > 1) {
              print_course_categories($categories, "index");
          } else {
index 6ba911c13faee29ebc914a3f0b7c9397916b64b3..82b9803312d7dfb8deabeeb45b9e5b7919acdacb 100644 (file)
@@ -111,6 +111,7 @@ $string['deletednot'] = "Could not delete \$a !";
 $string['deletingcourse'] = "Deleting \$a";
 $string['department'] = "Department";
 $string['description'] = "Description";
+$string['displayingrecords'] = "Displaying \$a records";
 $string['displayingusers'] = "Displaying users \$a->start to \$a->end";
 $string['documentation'] = "Moodle Documentation";
 $string['downloadexcel'] = "Download in Excel format";
similarity index 64%
rename from lib/database.php
rename to lib/datalib.php
index 4ec59405f0f9b394d15c06aeb40087adf6b89a55..1fdea66b1d85717eb17ddc1aebb2f2ca781de20d 100644 (file)
@@ -69,11 +69,11 @@ function record_exists($table, $field="", $value="", $field2="", $value2="", $fi
 
     global $CFG;
 
-    if ($field and $value) {
+    if ($field) {
         $select = "WHERE $field = '$value'";
-        if ($field2 and $value2) {
+        if ($field2) {
             $select .= " AND $field2 = '$value2'";
-            if ($field3 and $value3) {
+            if ($field3) {
                 $select .= " AND $field3 = '$value3'";
             }
         }
@@ -105,11 +105,11 @@ function count_records($table, $field="", $value="", $field2="", $value2="", $fi
 
     global $CFG;
 
-    if ($field and $value) {
+    if ($field) {
         $select = "WHERE $field = '$value'";
-        if ($field2 and $value2) {
+        if ($field2) {
             $select .= " AND $field2 = '$value2'";
-            if ($field3 and $value3) {
+            if ($field3) {
                 $select .= " AND $field3 = '$value3'";
             }
         }
@@ -118,6 +118,15 @@ function count_records($table, $field="", $value="", $field2="", $value2="", $fi
     return count_records_sql("SELECT COUNT(*) FROM $CFG->prefix$table $select");
 }
 
+function count_records_select($table, $select="") {
+/// Get all the records and count them
+
+    global $CFG;
+
+    return count_records_sql("SELECT COUNT(*) FROM $CFG->prefix$table $select");
+}
+
+
 function count_records_sql($sql) {
 /// Get all the records and count them
 /// The sql statement is provided as a string.
@@ -137,9 +146,9 @@ function get_record($table, $field, $value, $field2="", $value2="", $field3="",
 
     $select = "WHERE $field = '$value'";
 
-    if ($field2 and $value2) {
+    if ($field2) {
         $select .= " AND $field2 = '$value2'";
-        if ($field3 and $value3) {
+        if ($field3) {
             $select .= " AND $field3 = '$value3'";
         }
     }
@@ -171,7 +180,7 @@ function get_records($table, $field="", $value="", $sort="", $fields="*") {
 
     global $CFG;
 
-    if ($field and $value) {
+    if ($field) {
         $select = "WHERE $field = '$value'";
     }
     if ($sort) {
@@ -181,17 +190,32 @@ function get_records($table, $field="", $value="", $sort="", $fields="*") {
     return get_records_sql("SELECT $fields FROM $CFG->prefix$table $select $sortorder");
 }
 
+function get_records_select($table, $select="", $sort="", $fields="*") {
+/// Get a number of records as an array of objects
+/// Can optionally be sorted eg "time ASC" or "time DESC"
+/// "select" is a fragment of SQL to define the selection criteria
+/// The "key" is the first column returned, eg usually "id"
+
+    global $CFG;
+
+    if ($sort) {
+        $sortorder = "ORDER BY $sort";
+    }
+
+    return get_records_sql("SELECT $fields FROM $CFG->prefix$table $select $sortorder");
+}
+
 
 function get_records_list($table, $field="", $values="", $sort="", $fields="*") {
-// Get a number of records as an array of objects
-// Differs from get_records() in that the values variable 
-// can be a comma-separated list of values eg  "4,5,6,10"
-// Can optionally be sorted eg "time ASC" or "time DESC"
-// The "key" is the first column returned, eg usually "id"
+/// Get a number of records as an array of objects
+/// Differs from get_records() in that the values variable 
+/// can be a comma-separated list of values eg  "4,5,6,10"
+/// Can optionally be sorted eg "time ASC" or "time DESC"
+/// The "key" is the first column returned, eg usually "id"
 
     global $CFG;
 
-    if ($field and $value) {
+    if ($field) {
         $select = "WHERE $field in ($values)";
     }
     if ($sort) {
@@ -202,10 +226,11 @@ function get_records_list($table, $field="", $values="", $sort="", $fields="*")
 }
 
 
+
 function get_records_sql($sql) {
-// Get a number of records as an array of objects
-// The "key" is the first column returned, eg usually "id"
-// The sql statement is provided as a string.
+/// Get a number of records as an array of objects
+/// The "key" is the first column returned, eg usually "id"
+/// The sql statement is provided as a string.
 
     global $db;
 
@@ -226,11 +251,45 @@ function get_records_sql($sql) {
     }
 }
 
+function get_records_menu($table, $field="", $value="", $sort="", $fields="*") {
+/// Get a number of records as an array of objects
+/// Can optionally be sorted eg "time ASC" or "time DESC"
+/// If "fields" is specified, only those fields are returned
+/// The "key" is the first column returned, eg usually "id"
+
+    global $CFG;
+
+    if ($field) {
+        $select = "WHERE $field = '$value'";
+    }
+    if ($sort) {
+        $sortorder = "ORDER BY $sort";
+    }
+
+    return get_records_sql_menu("SELECT $fields FROM $CFG->prefix$table $select $sortorder");
+}
+
+function get_records_select_menu($table, $select="", $sort="", $fields="*") {
+/// Get a number of records as an array of objects
+/// Can optionally be sorted eg "time ASC" or "time DESC"
+/// "select" is a fragment of SQL to define the selection criteria
+/// Returns associative array of first two fields
+
+    global $CFG;
+
+    if ($sort) {
+        $sortorder = "ORDER BY $sort";
+    }
+
+    return get_records_sql_menu("SELECT $fields FROM $CFG->prefix$table $select $sortorder");
+}
+
+
 function get_records_sql_menu($sql) {
-// Given an SQL select, this function returns an associative 
-// array of the first two columns.  This is most useful in 
-// combination with the choose_from_menu function to create 
-// a form menu.
+/// Given an SQL select, this function returns an associative 
+/// array of the first two columns.  This is most useful in 
+/// combination with the choose_from_menu function to create 
+/// a form menu.
 
     global $db;
 
@@ -278,11 +337,11 @@ function delete_records($table, $field="", $value="", $field2="", $value2="", $f
 
     global $db, $CFG;
 
-    if ($field and $value) {
+    if ($field) {
         $select = "WHERE $field = '$value'";
-        if ($field2 and $value2) {
+        if ($field2) {
             $select .= " AND $field2 = '$value2'";
-            if ($field3 and $value3) {
+            if ($field3) {
                 $select .= " AND $field3 = '$value3'";
             }
         }
@@ -482,7 +541,9 @@ function adminlogin($username, $md5password) {
 
     global $CFG;
 
-    return record_exists_sql("SELECT u.id FROM {$CFG->prefix}user u, {$CFG->prefix}user_admins a 
+    return record_exists_sql("SELECT u.id 
+                                FROM {$CFG->prefix}user u, 
+                                     {$CFG->prefix}user_admins a 
                               WHERE u.id = a.user 
                                 AND u.username = '$username' 
                                 AND u.password = '$md5password'");
@@ -499,6 +560,31 @@ function get_site () {
     }
 }
 
+
+function get_courses($category=0, $sort="fullname ASC") {
+/// Returns list of courses
+
+    if ($category > 0) {          // Return all courses in one category
+        return get_records("course", "category", $category, $sort);
+
+    } else if ($category < 0) {   // Return all courses, even the site
+        return get_records("course", "", "", $sort);
+
+    } else {                      // Return all courses, except site
+        return get_records_select("course", "category > 0", $sort);
+    }
+}
+
+function get_categories() {
+    return get_records("course_categories", "", "", "name");
+}
+
+
+function get_guest() {
+    return get_user_info_from_db("username", "guest");
+}
+
+
 function get_admin () {
 /// Returns $user object of the main admin user
 
@@ -581,9 +667,82 @@ function get_course_users($courseid, $sort="u.lastaccess DESC") {
 }
 
 
+function get_users_search($search, $sort="u.firstname ASC") {
+    global $CFG;
+
+    return get_records_sql("SELECT * from {$CFG->prefix}user 
+                             WHERE confirmed = 1 
+                               AND deleted = 0
+                               AND (firstname LIKE '%$search%' OR 
+                                    lastname LIKE '%$search%' OR 
+                                    email LIKE '%$search%')
+                               AND username <> 'guest' 
+                               AND username <> 'changeme'");
+}
+
+
+function get_users_count() {
+    return count_record_select("user", "username <> 'guest' AND deleted <> 1");
+}
+
+function get_users_listing($sort, $dir="ASC", $page=1, $recordsperpage=20) {
+    global $CFG;
+    return get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess  
+                              FROM {$CFG->prefix}user 
+                             WHERE username <> 'guest' 
+                               AND deleted <> '1' 
+                          ORDER BY $sort $dir 
+                             LIMIT $page,$recordsperpage");
+
+}
+
+function get_users_confirmed() {
+    global $CFG;
+    return get_records_sql("SELECT * 
+                              FROM {$CFG->prefix}user 
+                             WHERE confirmed = 1 
+                               AND deleted = 0
+                               AND username <> 'guest' 
+                               AND username <> 'changeme'");
+}
+
+
+function get_users_unconfirmed($cutofftime=999999999) {
+    global $CFG;
+    return get_records_sql("SELECT * 
+                             FROM {$CFG->prefix}user 
+                            WHERE confirmed = 0
+                              AND firstaccess > 0 
+                              AND firstaccess < '$cutofftime'");
+}
+
+
+function get_users_longtimenosee($cutofftime) {
+    global $CFG;
+    return get_records_sql("SELECT u.* 
+                              FROM {$CFG->prefix}user u, 
+                                   {$CFG->prefix}user_students s
+                             WHERE lastaccess > '0' 
+                               AND lastaccess < '$cutofftime' 
+                               AND u.id = s.user 
+                          GROUP BY u.id");
+}
+
+
 
 /// MODULE FUNCTIONS /////////////////////////////////////////////////
 
+function get_course_mods($courseid) {
+/// Just gets a raw list of all modules in a course
+    global $CFG;
+
+    return get_records_sql("SELECT cm.*, m.name as modname
+                            FROM {$CFG->prefix}modules m, {$CFG->prefix}course_modules cm
+                            WHERE cm.course = '$courseid' 
+                            AND cm.deleted = '0'
+                            AND cm.module = m.id ");
+}
+
 function get_coursemodule_from_instance($modulename, $instance, $courseid) {
 /// Given an instance of a module, finds the coursemodule description
 
@@ -619,4 +778,75 @@ function get_all_instances_in_course($modulename, $courseid, $sort="cw.section")
 
 }
 
+
+/// LOG FUNCTIONS /////////////////////////////////////////////////////
+
+
+function add_to_log($course, $module, $action, $url="", $info="") {
+/// Add an entry to the log table.  These are "action" focussed rather
+/// than web server hits, and provide a way to easily reconstruct what 
+/// any particular student has been doing.
+///
+/// course = the course id
+/// module = forum, journal, resource, course, user etc
+/// action = view, edit, post (often but not always the same as the file.php)
+/// url    = the file and parameters used to see the results of the action
+/// info   = additional description information 
+
+    global $db, $USER, $REMOTE_ADDR;
+
+    if (isset($USER->realuser)) {  // Don't log
+        return;
+    }
+
+    $timenow = time();
+    $info = addslashes($info);
+
+    $result = $db->Execute("INSERT INTO log
+                            SET time = '$timenow', 
+                                user = '$USER->id',
+                                course = '$course',
+                                ip = '$REMOTE_ADDR', 
+                                module = '$module',
+                                action = '$action',
+                                url = '$url',
+                                info = '$info'");
+    if (!$result) {
+        echo "<P>Error: Could not insert a new entry to the Moodle log</P>";  // Don't throw an error
+    }    
+}
+
+
+function get_logs($select, $order) {
+    global $CFG;
+
+    return get_records_sql("SELECT l.*, u.firstname, u.lastname, u.picture 
+                              FROM {$CFG->prefix}log l, 
+                                   {$CFG->prefix}user u 
+                                   $select $order");
+}
+
+function get_logs_usercourse($userid, $courseid, $coursestart) {
+    global $CFG;
+
+    return get_records_sql("SELECT floor((`time` - $coursestart)/86400) as day, count(*) as num 
+                            FROM {$CFG->prefix}log 
+                           WHERE user = '$userid' 
+                             AND course = '$courseid'
+                             AND `time` > '$coursestart'
+                        GROUP BY day ");
+}
+
+function get_logs_userday($userid, $courseid, $daystart) {
+    global $CFG;
+
+    return get_records_sql("SELECT floor((`time` - $daystart)/3600) as hour, count(*) as num
+                            FROM {$CFG->prefix}log
+                           WHERE user = '$userid' 
+                             AND course = '$courseid'
+                             AND `time` > '$daystart'
+                        GROUP BY hour ");
+}
+
+
 ?>
index 724495f6433791c72e24c0e3e7a0a2bacd1b3d17..f2e134fd5d6736c2fd642641b9d6187d269ee773 100644 (file)
@@ -14,7 +14,7 @@
 # Table structure for table `config`
 #
 
-CREATE TABLE `config` (
+CREATE TABLE `prefix_config` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `name` varchar(255) NOT NULL default '',
   `value` varchar(255) NOT NULL default '',
@@ -27,7 +27,7 @@ CREATE TABLE `config` (
 # Table structure for table `course`
 #
 
-CREATE TABLE `course` (
+CREATE TABLE `prefix_course` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `category` int(10) unsigned NOT NULL default '0',
   `password` varchar(50) NOT NULL default '',
@@ -56,7 +56,7 @@ CREATE TABLE `course` (
 # Table structure for table `course_categories`
 #
 
-CREATE TABLE `course_categories` (
+CREATE TABLE `prefix_course_categories` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `name` varchar(255) NOT NULL default '',
   PRIMARY KEY  (`id`),
@@ -68,7 +68,7 @@ CREATE TABLE `course_categories` (
 # Table structure for table `course_modules`
 #
 
-CREATE TABLE `course_modules` (
+CREATE TABLE `prefix_course_modules` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `course` int(10) unsigned NOT NULL default '0',
   `module` int(10) unsigned NOT NULL default '0',
@@ -86,7 +86,7 @@ CREATE TABLE `course_modules` (
 # Table structure for table `course_sections`
 #
 
-CREATE TABLE `course_sections` (
+CREATE TABLE `prefix_course_sections` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `course` int(10) unsigned NOT NULL default '0',
   `section` int(10) unsigned NOT NULL default '0',
@@ -100,7 +100,7 @@ CREATE TABLE `course_sections` (
 # Table structure for table `log`
 #
 
-CREATE TABLE `log` (
+CREATE TABLE `prefix_log` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `time` int(10) unsigned NOT NULL default '0',
   `user` int(10) unsigned NOT NULL default '0',
@@ -118,7 +118,7 @@ CREATE TABLE `log` (
 # Table structure for table `log_display`
 #
 
-CREATE TABLE `log_display` (
+CREATE TABLE `prefix_log_display` (
   `module` varchar(20) NOT NULL default '',
   `action` varchar(20) NOT NULL default '',
   `mtable` varchar(20) NOT NULL default '',
@@ -130,7 +130,7 @@ CREATE TABLE `log_display` (
 # Table structure for table `modules`
 #
 
-CREATE TABLE `modules` (
+CREATE TABLE `prefix_modules` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `name` varchar(20) NOT NULL default '',
   `version` int(10) NOT NULL default '0',
@@ -146,7 +146,7 @@ CREATE TABLE `modules` (
 # Table structure for table `user`
 #
 
-CREATE TABLE `user` (
+CREATE TABLE `prefix_user` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `confirmed` tinyint(1) NOT NULL default '0',
   `deleted` tinyint(1) NOT NULL default '0',
@@ -189,7 +189,7 @@ CREATE TABLE `user` (
 # Table structure for table `user_admins`
 #
 
-CREATE TABLE `user_admins` (
+CREATE TABLE `prefix_user_admins` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `user` int(10) unsigned NOT NULL default '0',
   PRIMARY KEY  (`id`),
@@ -201,7 +201,7 @@ CREATE TABLE `user_admins` (
 # Table structure for table `user_students`
 #
 
-CREATE TABLE `user_students` (
+CREATE TABLE `prefix_user_students` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `user` int(10) unsigned NOT NULL default '0',
   `course` int(10) unsigned NOT NULL default '0',
@@ -217,7 +217,7 @@ CREATE TABLE `user_students` (
 # Table structure for table `user_teachers`
 #
 
-CREATE TABLE `user_teachers` (
+CREATE TABLE `prefix_user_teachers` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `user` int(10) unsigned NOT NULL default '0',
   `course` int(10) unsigned NOT NULL default '0',
index 1bf01f178fa96bbff21147cff111243678775535..b72d0849fbe1b8a91b0c86d3595e18e9fcab7b54 100644 (file)
 <?PHP // $Id$
 
-//
-// moodlelib.php
-//
-// Large collection of useful functions used by many parts of Moodle.
-//
-// Martin Dougiamas, 2000
-//
-
-/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
-
-function print_header ($title="", $heading="", $navigation="", $focus="", $meta="", $cache=true, $button="&nbsp;", $menu="") {
-// $title - appears top of window
-// $heading - appears top of page
-// $navigation - premade navigation string
-// $focus - indicates form element eg  inputform.password
-// $meta - meta tags in the header
-// $cache - should this page be cacheable?
-// $button - HTML code for a button (usually for module editing)
-// $menu - HTML code for a popup menu 
-    global $USER, $CFG, $THEME;
-
-    if (file_exists("$CFG->dirroot/theme/$CFG->theme/styles.php")) {
-        $styles = $CFG->stylesheet;
-    } else {
-        $styles = "$CFG->wwwroot/theme/standard/styles.php";
-    }
-
-    if ($navigation == "home") {
-        $home = true;
-        $navigation = "";
-    }
-
-    if ($button == "") {
-        $button = "&nbsp;";
-    }
-
-    if (!$menu and $navigation) {
-        if (isset($USER->id)) {
-            $menu = "<FONT SIZE=2><A TARGET=_parent HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A></FONT>";
-        } else {
-            $menu = "<FONT SIZE=2><A TARGET=_parent HREF=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</A></FONT>";
-        }
-    }
-
-    // Specify character set ... default is iso-8859-1 but some languages might need something else
-    // Could be optimised by carrying the charset variable around in $USER
-    if (current_language() == "en") {
-        $meta .= "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">\n";
-    } else {
-        $meta .= "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=".get_string("thischarset")."\">\n";
-    }
-
-    if ($CFG->langdir == "RTL") {
-        $direction = " DIR=\"RTL\"";
-    } else {
-        $direction = " DIR=\"LTR\"";
-    }
-    if (!$cache) {   // Do everything we can to prevent clients and proxies caching
-        @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
-        @header("Pragma: no-cache");
-        $meta .= "\n<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">";
-        $meta .= "\n<META HTTP-EQUIV=\"Expires\" CONTENT=\"0\">";
-    }
-
-    include ("$CFG->dirroot/theme/$CFG->theme/header.html");
-}
-
-function print_footer ($course=NULL) {
-// Can provide a course object to make the footer contain a link to 
-// to the course home page, otherwise the link will go to the site home
-    global $USER, $CFG, $THEME;
-
-
-/// Course links
-    if ($course) {
-        if ($course == "home") {   // special case for site home page - please do not remove
-            $homelink  = "<P ALIGN=center><A TITLE=\"Moodle $CFG->release ($CFG->version)\" HREF=\"http://moodle.com/\">";
-            $homelink .= "<BR><IMG WIDTH=130 HEIGHT=19 SRC=\"pix/madewithmoodle2.gif\" BORDER=0></A></P>";
-            $course = get_site();
-            $homepage = true;
-        } else {
-            $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</A>";
-        }
-    } else {
-        $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot\">".get_string("home")."</A>";
-        $course = get_site();
-    }
-
-/// User links
-    if ($USER->realuser) {
-        if ($realuser = get_record("user", "id", $USER->realuser)) {
-            $realuserinfo = " [<A HREF=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=$realuser->id\">$realuser->firstname $realuser->lastname</A>] ";
-        }
-    }
+///////////////////////////////////////////////////////////////////////////
+//                                                                       //
+// moodlelib.php                                                         //
+//                                                                       //
+// Main library file of miscellaneous general-purpose Moodle functions   //
+//                                                                       //
+// Other main libraries:                                                 //
+//                                                                       //
+//   weblib.php      - functions that produce web output                 //
+//   datalib.php     - functions that access the database                //
+//                                                                       //
+///////////////////////////////////////////////////////////////////////////
+//                                                                       //
+// NOTICE OF COPYRIGHT                                                   //
+//                                                                       //
+// Moodle - Modular Object-Oriented Dynamic Learning Environment         //
+//          http://moodle.com                                            //
+//                                                                       //
+// Copyright (C) 2001-2003  Martin Dougiamas  http://dougiamas.com       //
+//                                                                       //
+// This program is free software; you can redistribute it and/or modify  //
+// it under the terms of the GNU General Public License as published by  //
+// the Free Software Foundation; either version 2 of the License, or     //
+// (at your option) any later version.                                   //
+//                                                                       //
+// This program is distributed in the hope that it will be useful,       //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of        //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
+// GNU General Public License for more details:                          //
+//                                                                       //
+//          http://www.gnu.org/copyleft/gpl.html                         //
+//                                                                       //
+///////////////////////////////////////////////////////////////////////////
 
-    if ($USER->id) {
-        $username = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id\">$USER->firstname $USER->lastname</A>";
-        $loggedinas = $realuserinfo.get_string("loggedinas", "moodle", "$username").
-                      " (<A HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A>)";
-    } else {
-        $loggedinas = get_string("loggedinnot", "moodle").
-                      " (<A HREF=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</A>)";
-    }
-
-    include ("$CFG->dirroot/theme/$CFG->theme/footer.html");
-}
-
-
-
-function print_navigation ($navigation) {
-   global $CFG;
-
-   if ($navigation) {
-       if (! $site = get_site()) {
-           $site->shortname = get_string("home");;
-       }
-       echo "<A TARGET=_top HREF=\"$CFG->wwwroot/\">$site->shortname</A> -> $navigation";
-   }
-}
-
-function print_heading($text, $align="CENTER", $size=3) {
-    echo "<P ALIGN=\"$align\"><FONT SIZE=\"$size\"><B>".stripslashes($text)."</B></FONT></P>";
-}
-
-function print_heading_with_help($text, $helppage, $module="moodle") {
-// Centered heading with attached help button (same title text)
-    echo "<P ALIGN=\"CENTER\"><FONT SIZE=\"3\"><B>".stripslashes($text);
-    helpbutton($helppage, $text, $module);
-    echo "</B></FONT></P>";
-}
-    
-function print_continue($link) {
-    global $HTTP_REFERER;
-
-    if (!$link) {
-        $link = $HTTP_REFERER;
-    }
-
-    print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
-}
-
-
-function print_simple_box($message, $align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
-    print_simple_box_start($align, $width, $color, $padding, $class);
-    echo stripslashes($message);
-    print_simple_box_end();
-}
-
-function print_simple_box_start($align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
-    global $THEME;
-
-    if ($align) {
-        $tablealign = "ALIGN=\"$align\"";
-    }
-    if ($width) {
-        $tablewidth = "WIDTH=\"$width\"";
-    }
-    echo "<table $tablealign $tablewidth class=\"$class\" border=\"0\" cellpadding=\"$padding\" cellspacing=\"0\"><tr><td bgcolor=\"$color\" class=\"$class"."content\">";
-}
-
-function print_simple_box_end() {
-    echo "</td></tr></table>";
-}
-
-function print_single_button($link, $options, $label="OK") {
-    echo "<FORM ACTION=\"$link\" METHOD=GET>";
-    if ($options) {
-        foreach ($options as $name => $value) {
-            echo "<INPUT TYPE=hidden NAME=\"$name\" VALUE=\"$value\">";
-        }
-    }
-    echo "<INPUT TYPE=submit VALUE=\"$label\"></FORM>";
-}
-
-function print_spacer($height=1, $width=1, $br=true) {
-    global $CFG;
-    echo "<IMG HEIGHT=\"$height\" WIDTH=\"$width\" SRC=\"$CFG->wwwroot/pix/spacer.gif\" ALT=\"\">";
-    if ($br) {
-        echo "<BR \>\n";
-    }
-}
-
-function print_file_picture($path, $courseid=0, $height="", $width="", $link="") {
-// Given the path to a picture file in a course, or a URL,
-// this function includes the picture in the page.
-    global $CFG;
-
-    if ($height) {
-        $height = "HEIGHT=\"$height\"";
-    }
-    if ($width) {
-        $width = "WIDTH=\"$width\"";
-    }
-    if ($link) {
-        echo "<A HREF=\"$link\">";
-    }
-    if (substr(strtolower($path), 0, 7) == "http://") {
-        echo "<IMG BORDER=0 $height $width SRC=\"$path\">";
-
-    } else if ($courseid) {
-        echo "<IMG BORDER=0 $height $width SRC=\"";
-        if ($CFG->slasharguments) {        // Use this method if possible for better caching
-            echo "$CFG->wwwroot/file.php/$courseid/$path";
-        } else {
-            echo "$CFG->wwwroot/file.php?file=$courseid/$path";
-        }
-        echo "\">";
-    } else {
-        echo "Error: must pass URL or course";
-    }
-    if ($link) {
-        echo "</A>";
-    }
-}
-
-function print_user_picture($userid, $courseid, $picture, $large=false, $returnstring=false, $link=true) {
-    global $CFG;
-
-    if ($link) {
-        $output = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$userid&course=$courseid\">";
-    } else {
-        $output = "";
-    }
-    if ($large) {
-        $file = "f1.jpg";
-        $size = 100;
-    } else {
-        $file = "f2.jpg";
-        $size = 35;
-    }
-    if ($picture) {
-        if ($CFG->slasharguments) {        // Use this method if possible for better caching
-            $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
-        } else {
-            $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php?file=/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
-        }
-    } else {
-        $output .= "<IMG SRC=\"$CFG->wwwroot/user/default/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
-    }
-    if ($link) {
-        $output .= "</A>";
-    }
-
-    if ($returnstring) {
-        return $output;
-    } else {
-        echo $output;
-    }
-}
-
-function print_table($table) {
-// Prints a nicely formatted table.
-// $table is an object with several properties.
-//     $table->head      is an array of heading names.
-//     $table->align     is an array of column alignments
-//     $table->size      is an array of column sizes
-//     $table->data[]    is an array of arrays containing the data.
-//     $table->width     is an percentage of the page
-//     $table->cellpadding    padding on each cell
-//     $table->cellspacing    spacing between cells
-
-    if (isset($table->align)) {
-        foreach ($table->align as $key => $aa) {
-            if ($aa) {
-                $align[$key] = " ALIGN=\"$aa\"";
-            } else {
-                $align[$key] = "";
-            }
-        }
-    }
-    if (isset($table->size)) {
-        foreach ($table->size as $key => $ss) {
-            if ($ss) {
-                $size[$key] = " WIDTH=\"$ss\"";
-            } else {
-                $size[$key] = "";
-            }
-        }
-    }
-
-    if (!$table->width) {
-        $table->width = "80%";
-    }
-
-    if (!$table->cellpadding) {
-        $table->cellpadding = "5";
-    }
-
-    if (!$table->cellspacing) {
-        $table->cellspacing = "1";
-    }
-
-    print_simple_box_start("CENTER", "$table->width", "#FFFFFF", 0);
-    echo "<TABLE WIDTH=100% BORDER=0 valign=top align=center ";
-    echo " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"generaltable\">\n";
-
-    if ($table->head) {
-        echo "<TR>";
-        foreach ($table->head as $key => $heading) {
-            echo "<TH VALIGN=top ".$align[$key].$size[$key]." NOWRAP class=\"generaltableheader\">$heading</TH>";
-        }
-        echo "</TR>\n";
-    }
-
-    foreach ($table->data as $row) {
-        echo "<TR VALIGN=TOP>";
-        foreach ($row as $key => $item) {
-            echo "<TD ".$align[$key].$size[$key]." class=\"generaltablecell\">$item</TD>";
-        }
-        echo "</TR>\n";
-    }
-    echo "</TABLE>\n";
-    print_simple_box_end();
-
-    return true;
-}
 
-function print_editing_switch($courseid) {
-    global $CFG, $USER;
-
-    if (isteacher($courseid)) {
-        if ($USER->editing) {
-            echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=off\">Turn editing off</A>";
-        } else {
-            echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=on\">Turn editing on</A>";
-        }
-    }
-}
-
-function format_float($num, $places=0) {
-    return sprintf("%.$places"."f", $num);
-}
-
-function print_textarea($richedit, $rows, $cols, $width, $height, $name, $value="") {
-    global $CFG, $THEME;
-
-    if ($richedit) {
-        echo "<object id=richedit style=\"BACKGROUND-COLOR: buttonface\"";
-        echo " data=\"$CFG->wwwroot/lib/rte/richedit.html\"";
-        echo " width=\"$width\" height=\"$height\" ";
-        echo " type=\"text/x-scriptlet\" VIEWASTEXT></object>\n";
-        echo "<TEXTAREA style=\"display:none\" NAME=\"$name\" ROWS=1 COLS=1>";
-        p($value);
-        echo "</TEXTAREA>\n";
-    } else {
-        echo "<TEXTAREA name=\"$name\" rows=\"$rows\" cols=\"$cols\" wrap=virtual>";
-        p($value);
-        echo "</TEXTAREA>\n";
-    }
-}
-
-function print_richedit_javascript($form, $name, $source="no") {
-    echo "<SCRIPT language=\"JavaScript\" event=\"onload\" for=\"window\">\n";
-    echo "   document.richedit.options = \"history=no;source=$source\";";
-    echo "   document.richedit.docHtml = $form.$name.innerText;";
-    echo "</SCRIPT>";
-}
-
-
-function update_course_icon($courseid) {
-// Used to be an icon, but it's now a simple form button
-    global $CFG, $USER;
+/// PARAMETER HANDLING ////////////////////////////////////////////////////
 
-    if (isteacher($courseid)) {
-        if ($USER->editing) {
-            $string = get_string("turneditingoff");
-            $edit = "off";
-        } else {
-            $string = get_string("turneditingon");
-            $edit = "on";
-        }
-        return "<FORM TARGET=_parent METHOD=GET ACTION=\"$CFG->wwwroot/course/view.php\">".
-               "<INPUT TYPE=hidden NAME=id VALUE=\"$courseid\">".
-               "<INPUT TYPE=hidden NAME=edit VALUE=\"$edit\">".
-               "<INPUT TYPE=submit VALUE=\"$string\"></FORM>";
+function require_variable($var) {
+/// Variable must be present
+    if (! isset($var)) {
+        error("A required parameter was missing");
     }
 }
 
-function update_module_button($moduleid, $courseid, $string) {
-// Prints the editing button on a module "view" page
-    global $CFG;
-
-    if (isteacher($courseid)) {
-        $string = get_string("updatethis", "", $string);
-        return "<FORM TARGET=_parent METHOD=GET ACTION=\"$CFG->wwwroot/course/mod.php\">".
-               "<INPUT TYPE=hidden NAME=update VALUE=\"$moduleid\">".
-               "<INPUT TYPE=hidden NAME=return VALUE=\"true\">".
-               "<INPUT TYPE=submit VALUE=\"$string\"></FORM>";
+function optional_variable(&$var, $default=0) {
+/// Variable may be present, if not then set a default
+    if (! isset($var)) {
+        $var = $default;
     }
 }
 
 
-function navmenu($course, $cm=NULL) {
-// Given a course and a (current) coursemodule
-// This function returns a small popup menu with all the 
-// course activity modules in it, as a navigation menu
-// The data is taken from the serialised array stored in 
-// the course record
-
-    global $CFG;
-
-    if ($cm) {
-       $cm = $cm->id;
-    }
+function set_config($name, $value) {
+/// No need for get_config because they are usually always available in $CFG
 
-    if ($course->format == 'weeks') {
-        $strsection = get_string("week");
+    if (get_field("config", "name", "name", $name)) {
+        return set_field("config", "value", $value, "name", $name);
     } else {
-        $strsection = get_string("topic");
-    }
-
-    if (!$modinfo = unserialize($course->modinfo)) {
-        return "";
-    }
-    $section = -1;
-    $selected = "";
-    foreach ($modinfo as $mod) {
-        if ($mod->section > 0 and $section <> $mod->section) {
-            $menu[] = "-------------- $strsection $mod->section --------------";
-        }
-        $section = $mod->section;
-        $url = "$mod->mod/view.php?id=$mod->cm";
-        if ($cm == $mod->cm) {
-            $selected = $url;
-        }
-        $mod->name = urldecode($mod->name);
-        if (strlen($mod->name) > 55) {
-            $mod->name = substr($mod->name, 0, 50)."...";
-        }
-        $menu[$url] = $mod->name; 
-    }
-
-    return popup_form("$CFG->wwwroot/mod/", $menu, "navmenu", $selected, get_string("jumpto"), "", "", true);
-}   
-
-
-function print_date_selector($day, $month, $year, $currenttime=0) {
-// Currenttime is a default timestamp in GMT
-// Prints form items with the names $day, $month and $year
-
-    if (!$currenttime) {
-        $currenttime = time();
-    }
-    $currentdate = usergetdate($currenttime);
-
-    for ($i=1; $i<=31; $i++) {
-        $days[$i] = "$i";
-    }
-    for ($i=1; $i<=12; $i++) {
-        $months[$i] = date("F", mktime(0,0,0,$i,1,2000));
-    }
-    for ($i=2000; $i<=2010; $i++) {
-        $years[$i] = $i;
+        $config->name = $name;
+        $config->value = $value;
+        return insert_record("config", $config);
     }
-    choose_from_menu($days,   $day,   $currentdate[mday], "");
-    choose_from_menu($months, $month, $currentdate[mon],  "");
-    choose_from_menu($years,  $year,  $currentdate[year], "");
 }
 
-function print_time_selector($hour, $minute, $currenttime=0) {
-// Currenttime is a default timestamp in GMT
-// Prints form items with the names $hour and $minute
 
-    if (!$currenttime) {
-        $currenttime = time();
-    }
-    $currentdate = usergetdate($currenttime);
-    for ($i=0; $i<=23; $i++) {
-        $hours[$i] = sprintf("%02d",$i);
-    }
-    for ($i=0; $i<=59; $i++) {
-        $minutes[$i] = sprintf("%02d",$i);
-    }
-    choose_from_menu($hours,   $hour,   $currentdate[hours],   "");
-    choose_from_menu($minutes, $minute, $currentdate[minutes], "");
-}
+/// FUNCTIONS FOR HANDLING TIME ////////////////////////////////////////////
 
 function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0) {
-// Given date parts in user time, produce a GMT timestamp
+/// Given date parts in user time, produce a GMT timestamp
 
-   return mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
+    return mktime((int)$hour,(int)$minute,(int)$second,(int)$month,(int)$day,(int)$year);
 }
 
-
 function format_time($totalsecs, $str=NULL) {
-// Given an amount of time in seconds, prints it 
-// nicely as months, days, hours etc as needed
+/// Given an amount of time in seconds, returns string
+/// formatted nicely as months, days, hours etc as needed
 
     $totalsecs = abs($totalsecs);
 
@@ -527,12 +115,12 @@ function format_time($totalsecs, $str=NULL) {
 }
 
 function userdate($date, $format="", $timezone=99) {
-// Returns a formatted string that represents a date in user time
-// WARNING: note that the format is for strftime(), not date().
-// Because of a bug in most Windows time libraries, we can't use 
-// the nicer %e, so we have to use %d which has leading zeroes.
-// A lot of the fuss below is just getting rid of these leading 
-// zeroes as efficiently as possible.
+/// Returns a formatted string that represents a date in user time
+/// WARNING: note that the format is for strftime(), not date().
+/// Because of a bug in most Windows time libraries, we can't use 
+/// the nicer %e, so we have to use %d which has leading zeroes.
+/// A lot of the fuss below is just getting rid of these leading 
+/// zeroes as efficiently as possible.
 
     global $USER;
 
@@ -561,7 +149,7 @@ function userdate($date, $format="", $timezone=99) {
     } else {
         if ($fixday) {
             $datestring = gmstrftime($formatnoday, $date + (int)($timezone * 3600));
-            $daystring  = str_replace(" 0", "", strftime(" %d", $date));
+            $daystring  = str_replace(" 0", "", gmstrftime(" %d", $date));
             $datestring = str_replace("DD", $daystring, $datestring);
         } else {
             $datestring = gmstrftime($format, $date + (int)($timezone * 3600));
@@ -572,8 +160,8 @@ function userdate($date, $format="", $timezone=99) {
 }
 
 function usergetdate($date, $timezone=99) {
-// Given a $date timestamp in GMT, returns an array 
-// that represents the date in user time
+/// Given a $date timestamp in GMT, returns an array 
+/// that represents the date in user time
 
     global $USER;
 
@@ -599,8 +187,8 @@ function usergetdate($date, $timezone=99) {
 }
 
 function usertime($date, $timezone=99) {
-// Given a GMT timestamp (seconds since epoch), offsets it by 
-// the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
+/// Given a GMT timestamp (seconds since epoch), offsets it by 
+/// the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
     global $USER;
 
     if ($timezone == 99) {
@@ -613,8 +201,8 @@ function usertime($date, $timezone=99) {
 }
 
 function usergetmidnight($date, $timezone=99) {
-// Given a time, return the GMT timestamp of the most recent midnight
-// for the current user.
+/// Given a time, return the GMT timestamp of the most recent midnight
+/// for the current user.
     global $USER;
 
     if ($timezone == 99) {
@@ -633,7 +221,7 @@ function usergetmidnight($date, $timezone=99) {
 }
 
 function usertimezone($timezone=99) {
-// returns a string that prints the user's timezone
+/// Returns a string that prints the user's timezone
     global $USER;
 
     if ($timezone == 99) {
@@ -653,552 +241,12 @@ function usertimezone($timezone=99) {
 }
 
 
-function error ($message, $link="") {
-    global $CFG, $SESSION;
-
-    print_header(get_string("error"));
-    echo "<BR>";
-    print_simple_box($message, "center", "", "#FFBBBB");
-   
-    if (!$link) {
-        if ( !empty($SESSION->fromurl) ) {
-            $link = "$SESSION->fromurl";
-            unset($SESSION->fromurl);
-            save_session("SESSION");
-        } else {
-            $link = "$CFG->wwwroot";
-        }
-    }
-    print_continue($link);
-    print_footer();
-    die;
-}
-
-function helpbutton ($page, $title="", $module="moodle", $image=true, $linktext=false, $text="") {
-    // $page = the keyword that defines a help page
-    // $title = the title of links, rollover tips, alt tags etc
-    // $module = which module is the page defined in
-    // $image = use a help image for the link?  (true/false/"both")
-    // $text = if defined then this text is used in the page, and 
-    //         the $page variable is ignored.
-    global $CFG;
-
-    if ($module == "") {
-        $module = "moodle";
-    }
-
-    if ($image) {
-        if ($linktext) {
-            $linkobject = "$title<IMG align=\"absmiddle\" BORDER=0 HEIGHT=17 WIDTH=22 ALT=\"\" SRC=\"$CFG->wwwroot/pix/help.gif\">";
-        } else {
-            $linkobject = "<IMG align=\"absmiddle\" BORDER=0 HEIGHT=17 WIDTH=22 ALT=\"$title\" SRC=\"$CFG->wwwroot/pix/help.gif\">";
-        }
-    } else {
-        $linkobject = $title;
-    }
-    if ($text) {
-        $url = "/help.php?module=$module&text=".htmlentities(urlencode($text));
-    } else {
-        $url = "/help.php?module=$module&file=$page.html";
-    }
-    link_to_popup_window ($url, "popup", $linkobject, 400, 500, $title);
-}
-
-function notice ($message, $link="") {
-    global $THEME, $HTTP_REFERER;
-
-    if (!$link) {
-        $link = $HTTP_REFERER;
-    }
-
-    echo "<BR>";
-    print_simple_box($message, "center", "", "$THEME->cellheading");
-    print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
-    print_footer(get_site());
-    die;
-}
-
-function notice_yesno ($message, $linkyes, $linkno) {
-    global $THEME;
-
-    print_simple_box_start("center", "", "$THEME->cellheading");
-    echo "<P ALIGN=CENTER><FONT SIZE=3>$message</FONT></P>";
-    echo "<P ALIGN=CENTER><FONT SIZE=3><B>";
-    echo "<A HREF=\"$linkyes\">".get_string("yes")."</A>";
-    echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
-    echo "<A HREF=\"$linkno\">".get_string("no")."</A>";
-    echo "</B></FONT></P>";
-    print_simple_box_end();
-}
-
-function redirect($url, $message="", $delay=0) {
-// Uses META tags to redirect the user, after printing a notice
-
-    echo "<META HTTP-EQUIV='Refresh' CONTENT='$delay; URL=$url'>";
-
-    if (!empty($message)) {
-        print_header();
-        echo "<CENTER>";
-        echo "<P>$message</P>";
-        echo "<P>( <A HREF=\"$url\">".get_string("continue")."</A> )</P>";
-        echo "</CENTER>";
-    }
-    die; 
-}
-
-function notify ($message) {
-    echo "<P align=center><B><FONT COLOR=#FF0000>$message</FONT></B></P>\n";
-}
-
-
-
-/// PARAMETER HANDLING ////////////////////////////////////////////////////
-
-function require_variable($var) {
-    if (! isset($var)) {
-        error("A required parameter was missing");
-    }
-}
-
-function optional_variable(&$var, $default=0) {
-    if (! isset($var)) {
-        $var = $default;
-    }
-}
-
-
-
-
-/// DATABASE HANDLING ////////////////////////////////////////////////
-
-function execute_sql($command, $feedback=true) {
-// Completely general
-
-    global $db;
-    
-    $result = $db->Execute("$command");
-
-    if ($result) {
-        if ($feedback) {
-            echo "<P><FONT COLOR=green><B>".get_string("success")."</B></FONT></P>";
-        }
-        return true;
-    } else {
-        if ($feedback) {
-            echo "<P><FONT COLOR=red><B>".get_string("error")."</B></FONT></P>";
-        }
-        return false;
-    }
-}
-
-function modify_database($sqlfile) {
-// Assumes that the input text file consists of a number 
-// of SQL statements ENDING WITH SEMICOLONS.  The semicolons
-// MUST be the last character in a line.
-// Lines that are blank or that start with "#" are ignored.
-// Only tested with mysql dump files (mysqldump -p -d moodle)
-
-
-    if (file_exists($sqlfile)) {
-        $success = true;
-        $lines = file($sqlfile);
-        $command = "";
-
-        while ( list($i, $line) = each($lines) ) {
-            $line = chop($line);
-            $length = strlen($line);
-
-            if ($length  &&  substr($line, 0, 1) <> "#") { 
-                if (substr($line, $length-1, 1) == ";") {
-                    $line = substr($line, 0, $length-1);   // strip ;
-                    $command .= $line;
-                    if (! execute_sql($command)) {
-                        $success = false;
-                    }
-                    $command = "";
-                } else {
-                    $command .= $line;
-                }
-            }
-        }
-
-    } else {
-        $success = false;
-        echo "<P>Tried to modify database, but \"$sqlfile\" doesn't exist!</P>";
-    }
-
-    return $success;
-}
-
-
-function record_exists($table, $field, $value) {
-    global $db;
-
-    $rs = $db->Execute("SELECT * FROM $table WHERE $field = '$value' LIMIT 1");
-    if (!$rs) return false;
-
-    if ( $rs->RecordCount() ) {
-        return true;
-    } else {
-        return false;
-    }
-}
-
-function record_exists_sql($sql) {
-    global $db;
-
-    $rs = $db->Execute($sql);
-    if (!$rs) return false;
-
-    if ( $rs->RecordCount() ) {
-        return true;
-    } else {
-        return false;
-    }
-}
-
-
-function count_records($table, $selector, $value) {
-// Get all the records and count them
-    global $db;
-
-    $rs = $db->Execute("SELECT COUNT(*) FROM $table WHERE $selector = '$value'");
-    if (!$rs) return 0;
-
-    return $rs->fields[0];
-}
-
-function count_records_sql($sql) {
-// Get all the records and count them
-    global $db;
-
-    $rs = $db->Execute("$sql");
-    if (!$rs) return 0;
-
-    return $rs->fields[0];
-}
-
-function get_record($table, $selector, $value) {
-// Get a single record as an object
-    global $db;
-
-    $rs = $db->Execute("SELECT * FROM $table WHERE $selector = '$value'");
-    if (!$rs) return false;
-
-    if ( $rs->RecordCount() == 1 ) {
-        return (object)$rs->fields;
-    } else {
-        return false;
-    }
-}
-
-function get_record_sql($sql) {
-// Get a single record as an object
-// The sql statement is provided as a string.
-
-    global $db;
-
-    $rs = $db->Execute("$sql");
-    if (!$rs) return false;
-
-    if ( $rs->RecordCount() == 1 ) {
-        return (object)$rs->fields;
-    } else {
-        return false;
-    }
-}
-
-function get_records($table, $selector, $value, $sort="", $fields="*") {
-// Get a number of records as an array of objects
-// Can optionally be sorted eg "time ASC" or "time DESC"
-// If "fields" is specified, only those fields are returned
-// The "key" is the first column returned, eg usually "id"
-    global $db;
-
-    if ($sort) {
-        $sortorder = "ORDER BY $sort";
-    }
-    $sql = "SELECT $fields FROM $table WHERE $selector = '$value' $sortorder";
-
-    return get_records_sql($sql);
-}
-
-
-function get_records_list($table, $selector, $values, $sort="", $fields="*") {
-// Get a number of records as an array of objects
-// Differs from get_records() in that the values variable 
-// can be a comma-separated list of values eg  "4,5,6,10"
-// Can optionally be sorted eg "time ASC" or "time DESC"
-// The "key" is the first column returned, eg usually "id"
-    global $db;
-
-    if ($sort) {
-        $sortorder = "ORDER BY $sort";
-    }
-    $sql = "SELECT $fields FROM $table WHERE $selector in ($values) $sortorder";
-
-    return get_records_sql($sql);
-}
-
-
-function get_records_sql($sql) {
-// Get a number of records as an array of objects
-// The "key" is the first column returned, eg usually "id"
-// The sql statement is provided as a string.
-
-    global $db;
-
-    $rs = $db->Execute("$sql");
-    if (!$rs) return false;
-
-    if ( $rs->RecordCount() > 0 ) {
-        if ($records = $rs->GetAssoc(true)) {
-            foreach ($records as $key => $record) {
-                $objects[$key] = (object) $record;
-            }
-            return $objects;
-        } else {
-            return false;
-        }
-    } else {
-        return false;
-    }
-}
-
-function get_records_sql_menu($sql) {
-// Given an SQL select, this function returns an associative 
-// array of the first two columns.  This is most useful in 
-// combination with the choose_from_menu function to create 
-// a form menu.
-
-    global $db;
-
-    $rs = $db->Execute("$sql");
-    if (!$rs) return false;
-
-    if ( $rs->RecordCount() > 0 ) {
-        while (!$rs->EOF) {
-            $menu[$rs->fields[0]] = $rs->fields[1];
-            $rs->MoveNext();
-        }
-        return $menu;
-        
-    } else {
-        return false;
-    }
-}
-
-function get_field($table, $field, $selector, $value) {
-    global $db;
-
-    $rs = $db->Execute("SELECT $field FROM $table WHERE $selector = '$value'");
-    if (!$rs) return false;
-
-    if ( $rs->RecordCount() == 1 ) {
-        return $rs->fields["$field"];
-    } else {
-        return false;
-    }
-}
-
-function set_field($table, $field, $newvalue, $selector, $value) {
-    global $db;
-
-    return $db->Execute("UPDATE $table SET $field = '$newvalue' WHERE $selector = '$value'");
-}
-
-function set_config($name, $value) {
-// No need for get_config because they are usually always available in $CFG
-
-    if (get_field("config", "name", "name", $name)) {
-        return set_field("config", "value", $value, "name", $name);
-    } else {
-        $config->name = $name;
-        $config->value = $value;
-        return insert_record("config", $config);
-    }
-}
-
-function delete_records($table, $selector, $value) {
-// Delete one or more records from a table
-    global $db;
-
-    return $db->Execute("DELETE FROM $table WHERE $selector = '$value'");
-}
-
-function insert_record($table, $dataobject) {
-// Insert a record into a table and return the "id" field
-// $dataobject is an object containing needed data
-
-    global $db;
-
-    // Determine all the fields needed
-    if (! $columns = $db->MetaColumns("$table")) {
-        return false;
-    }
-
-    $data = (array)$dataobject;
-
-    // Pull out data matching these fields
-    foreach ($columns as $column) {
-        if ($column->name <> "id" && isset($data[$column->name]) ) {
-            $ddd[$column->name] = $data[$column->name];
-        }
-    }
-
-    // Construct SQL queries
-    if (! $numddd = count($ddd)) {
-        return 0;
-    }
-
-    $count = 0;
-    $insert = "";
-    $select = "";
-
-    foreach ($ddd as $key => $value) {
-        $count++;
-        $insert .= "$key = '$value'";
-        $select .= "$key = '$value'";
-        if ($count < $numddd) {
-            $insert .= ", ";
-            $select .= " AND ";
-        }
-    }
-
-    if (! $rs = $db->Execute("INSERT INTO $table SET $insert")) {
-        return false;
-    } 
-
-    // Pull it out again to find the id.  This is the most cross-platform method.
-    if ($rs = $db->Execute("SELECT id FROM $table WHERE $select")) {
-        return $rs->fields[0];
-    } else {
-        return false;
-    }
-}
-
-
-function update_record($table, $dataobject) {
-// Update a record in a table
-// $dataobject is an object containing needed data
-
-    global $db;
-
-    if (! isset($dataobject->id) ) {
-        return false;
-    }
-
-    // Determine all the fields in the table
-    if (!$columns = $db->MetaColumns($table)) {
-        return false;
-    }
-    $data = (array)$dataobject;
-
-    // Pull out data matching these fields
-    foreach ($columns as $column) {
-        if ($column->name <> "id" && isset($data[$column->name]) ) {
-            $ddd[$column->name] = $data[$column->name];
-        }
-    }
-
-    // Construct SQL queries
-    $numddd = count($ddd);
-    $count = 0;
-    $update = "";
-
-    foreach ($ddd as $key => $value) {
-        $count++;
-        $update .= "$key = '$value'";
-        if ($count < $numddd) {
-            $update .= ", ";
-        }
-    }
-
-    if ($rs = $db->Execute("UPDATE $table SET $update WHERE id = '$dataobject->id'")) {
-        return true;
-    } else {
-        return false;
-    }
-}
-
-
-function print_object($object) {
-// Mostly just for debugging
-
-    $array = (array)$object;
-    foreach ($array as $key => $item) {
-        echo "$key -> $item <BR>";
-    }
-}
-
-
-/// USER DATABASE ////////////////////////////////////////////////
-
-function get_user_info_from_db($field, $value) {
-
-    global $db;
-
-    if (!$field || !$value) 
-        return false;
-
-    if (! $result = $db->Execute("SELECT * FROM user WHERE $field = '$value' AND deleted <> '1'")) {
-        error("Could not find any active users!");
-    }
-
-    if ( $result->RecordCount() == 1 ) {
-        $user = (object)$result->fields;
-
-        $rs = $db->Execute("SELECT course FROM user_students WHERE user = '$user->id' ");
-        while (!$rs->EOF) {
-            $course = $rs->fields["course"];
-            $user->student["$course"] = true;
-            $rs->MoveNext();
-        }
-
-        $rs = $db->Execute("SELECT course FROM user_teachers WHERE user = '$user->id' ");
-        while (!$rs->EOF) {
-            $course = $rs->fields["course"];
-            $user->teacher["$course"] = true;
-            $rs->MoveNext();
-        }
-
-        $rs = $db->Execute("SELECT * FROM user_admins WHERE user = '$user->id' ");
-        while (!$rs->EOF) {
-            $user->admin = true;
-            $rs->MoveNext();
-        }
-
-        if ($course = get_site()) {
-            // Everyone is always a member of the top course
-            $user->student["$course->id"] = true;
-        }
-
-        return $user;
-
-    } else {
-        return false;
-    }
-}
-
-function update_user_in_db() {
-
-   global $db, $USER, $REMOTE_ADDR;
-
-   if (!isset($USER->id)) 
-       return false;
-
-   $timenow = time();
-   if ($db->Execute("UPDATE user SET lastIP='$REMOTE_ADDR', lastaccess='$timenow' WHERE id = '$USER->id' ")) {
-       return true;
-   } else {
-       return false;
-   }
-}
+/// USER AUTHENTICATION AND LOGIN ////////////////////////////////////////
 
 function require_login($courseid=0) {
-// This function checks that the current user is logged in, and optionally
-// whether they are "logged in" or allowed to be in a particular course.
-// If not, then it redirects them to the site login or course enrolment.
+/// This function checks that the current user is logged in, and optionally
+/// whether they are "logged in" or allowed to be in a particular course.
+/// If not, then it redirects them to the site login or course enrolment.
 
     global $CFG, $SESSION, $USER, $FULLME, $HTTP_REFERER, $PHPSESSID;
       
@@ -1263,8 +311,9 @@ function require_login($courseid=0) {
 }
 
 
-
 function update_login_count() {
+/// Keeps track of login attempts
+
     global $SESSION;
 
     $max_logins = 10;
@@ -1277,80 +326,36 @@ function update_login_count() {
     save_session("SESSION");
 
     if ($SESSION->logincount > $max_logins) {
-        unset($SESSION->wantsurl);
-        save_session("SESSION");
-        error("Sorry, you have exceeded the allowed number of login attempts. Restart your browser.");
-    }
-}
-
-function remove_admin($user) {
-    global $db;
-
-    return $db->Execute("DELETE FROM user_admins WHERE user = '$user'");
-}
-
-function remove_teacher($user, $course=0) {
-    global $db;
-
-    if ($course) {
-        /// First delete any crucial stuff that might still send mail
-        if ($forums = get_records("forum", "course", $course)) {
-            foreach ($forums as $forum) {
-                $db->Execute("DELETE FROM forum_subscriptions WHERE forum = '$forum->id' AND user = '$user'");
-            }
-        }
-        return $db->Execute("DELETE FROM user_teachers WHERE user = '$user' AND course = '$course'");
-    } else {
-        delete_records("forum_subscriptions", "user", $user);
-        return delete_records("user_teachers", "user", $user);
+        unset($SESSION->wantsurl);
+        save_session("SESSION");
+        error("Sorry, you have exceeded the allowed number of login attempts. Restart your browser.");
     }
 }
 
+function reset_login_count() {
+/// Resets login attempts
+    global $SESSION;
 
-function enrol_student($user, $course) {
-    global $db;
-
-       $timenow = time();
-
-       $rs = $db->Execute("INSERT INTO user_students (user, course, start, end, time) 
-                        VALUES ($user, $course, 0, 0, $timenow)");
-       if ($rs) {
-               return true;
-       } else {
-           return false;
-       }
+    $SESSION->logincount = 0;
+    save_session("SESSION");
 }
 
-function unenrol_student($user, $course=0) {
-    global $db;
-
-    if ($course) {
-        /// First delete any crucial stuff that might still send mail
-        if ($forums = get_records("forum", "course", $course)) {
-            foreach ($forums as $forum) {
-                $db->Execute("DELETE FROM forum_subscriptions WHERE forum = '$forum->id' AND user = '$user'");
-            }
-        }
-        return $db->Execute("DELETE FROM user_students WHERE user = '$user' AND course = '$course'");
-
-    } else {
-        delete_records("forum_subscriptions", "user", $user);
-        return delete_records("user_students", "user", $user);
-    }
-}
 
 
 function isadmin($userid=0) {
+/// Is the user an admin?
     global $USER;
 
     if (!$userid) {
-        return record_exists_sql("SELECT * FROM user_admins WHERE user='{$USER->id}'");
+        return record_exists("user_admins", "user", $USER->id);
     }
 
-    return record_exists_sql("SELECT * FROM user_admins WHERE user='$userid'");
+    return record_exists("user_admins", "user", $userid);
 }
 
+
 function isteacher($courseid, $userid=0) {
+/// Is the user a teacher or admin?
     global $USER;
 
     if (isadmin($userid)) {  // admins can do anything the teacher can
@@ -1361,11 +366,12 @@ function isteacher($courseid, $userid=0) {
         return $USER->teacher[$courseid];
     }
 
-    return record_exists_sql("SELECT * FROM user_teachers WHERE user='$userid' AND course='$courseid'");
+    return record_exists("user_teachers", "user", $userid, "course", $courseid);
 }
 
 
 function isstudent($courseid, $userid=0) {
+/// Is the user a student in this course?
     global $USER;
 
     if (!$userid) {
@@ -1374,20 +380,23 @@ function isstudent($courseid, $userid=0) {
 
     $timenow = time();   // todo:  add time check below
 
-    return record_exists_sql("SELECT * FROM user_students WHERE user='$userid' AND course='$courseid'");
+    return record_exists("user_students", "user", $userid, "course", $courseid);
 }
 
 function isguest($userid=0) {
+/// Is the user a guest?
     global $USER;
 
     if (!$userid) {
         return ($USER->username == "guest");
     }
 
-    return record_exists_sql("SELECT * FROM user WHERE id='$userid' AND username = 'guest' ");
+    return record_exists("user", "id", $userid, "username", "guest");
 }
 
+
 function isediting($courseid, $user=NULL) {
+/// Is the current user in editing mode?
     global $USER;
     if (!$user){
         $user = $USER;
@@ -1395,15 +404,9 @@ function isediting($courseid, $user=NULL) {
     return ($user->editing and isteacher($courseid, $user->id));
 }
 
-function reset_login_count() {
-    global $SESSION;
-
-    $SESSION->logincount = 0;
-    save_session("SESSION");
-}
-
 
 function set_moodle_cookie($thing) {
+/// Sets a moodle cookie with an encrypted string
 
     $days = 60;
     $seconds = 60*60*24*$days;
@@ -1414,21 +417,22 @@ function set_moodle_cookie($thing) {
 
 
 function get_moodle_cookie() {
+/// Gets a moodle cookie with an encrypted string
     global $MOODLEID;
     return rc4decrypt($MOODLEID);
 }
 
 
 function save_session($VAR) {
-// Copies temporary session variable to permanent sesson variable
-// eg $_SESSION["USER"] = $USER;
+/// Copies temporary session variable to permanent session variable
+/// eg $_SESSION["USER"] = $USER;
     global $$VAR;
     $_SESSION[$VAR] = $$VAR;
 }
 
 
 function create_user_record($username, $password) {
-// Creates a bare-bones user record 
+/// Creates a bare-bones user record 
     global $REMOTE_ADDR, $CFG;
 
     if (function_exists(auth_get_userinfo)) {
@@ -1453,12 +457,12 @@ function create_user_record($username, $password) {
 }
 
 function authenticate_user_login($username, $password) {
-// Given a username and password, this function looks them 
-// up using the currently selected authentication mechanism,
-// and if the authentication is successful, it returns a 
-// valid $user object from the 'user' table.
-//
-// Uses auth_ functions from the currently active auth module
+/// Given a username and password, this function looks them 
+/// up using the currently selected authentication mechanism,
+/// and if the authentication is successful, it returns a 
+/// valid $user object from the 'user' table.
+///
+/// Uses auth_ functions from the currently active auth module
 
     global $CFG;
 
@@ -1476,10 +480,7 @@ function authenticate_user_login($username, $password) {
     // Doing this first (even though it's less efficient) because 
     // the chosen authentication method might hang and lock the 
     // admin out.
-    if ($user = get_record_sql("SELECT u.id FROM user u, user_admins a 
-                                WHERE u.id = a.user 
-                                  AND u.username = '$username' 
-                                  AND u.password = '$md5password'")) {
+    if (adminlogin($username, $md5password)) {
         return get_user_info_from_db("username", $username);
     }
 
@@ -1503,128 +504,76 @@ function authenticate_user_login($username, $password) {
 }
 
 
-function get_site () {
-// Returns $course object of the top-level site.
-    if ( $course = get_record("course", "category", 0)) {
-        return $course;
-    } else {
-        return false;
-    }
-}
-
-function get_admin () {
-// Returns $user object of the main admin user
+function enrol_student($user, $course) {
+/// Enrols a student in a given course
+    global $db;
 
-    if ( $admins = get_records_sql("SELECT u.* FROM user u, user_admins a WHERE a.user = u.id ORDER BY u.id ASC")) {
-        foreach ($admins as $admin) {
-            return $admin;   // ie the first one 
-        }
-    } else {
-        return false;
-    }
-}
+    $record->user = $user;
+    $record->course = $course;
+    $record->start = 0;
+    $record->end = 0;
+    $record->time = time();
 
-function get_admins() {
-    return get_records_sql("SELECT u.* FROM user u, user_admins a
-                            WHERE a.user = u.id
-                            ORDER BY u.id ASC");
+    return insert_record("user", $record);
 }
 
+function unenrol_student($user, $course=0) {
+/// Unenrols a student from a given course
+    global $db;
 
-function get_teacher($courseid) {
-// Returns $user object of the main teacher for a course
-    if ( $teachers = get_records_sql("SELECT u.* FROM user u, user_teachers t 
-                                      WHERE t.user = u.id AND t.course = '$courseid' 
-                                      ORDER BY t.authority ASC")) {
-        foreach ($teachers as $teacher) {
-            if ($teacher->authority) {
-                return $teacher;   // the highest authority teacher
+    if ($course) {
+        /// First delete any crucial stuff that might still send mail
+        if ($forums = get_records("forum", "course", $course)) {
+            foreach ($forums as $forum) {
+                delete_records("forum_subscriptions", "forum", $forum->id, "user", $user);
             }
         }
+        return delete_records("user_students", "user", $user, "course", $course);
+
     } else {
-        return false;
+        delete_records("forum_subscriptions", "user", $user);
+        return delete_records("user_students", "user", $user);
     }
 }
 
-function get_course_students($courseid, $sort="u.lastaccess DESC") {
-    return get_records_sql("SELECT u.* FROM user u, user_students s
-                            WHERE s.course = '$courseid' AND s.user = u.id AND u.deleted = '0'
-                            ORDER BY $sort");
-}
-
-function get_course_teachers($courseid, $sort="t.authority ASC") {
-    return get_records_sql("SELECT u.*,t.authority,t.role FROM user u, user_teachers t
-                            WHERE t.course = '$courseid' AND t.user = u.id AND u.deleted = '0'
-                            ORDER BY $sort");
-}
-
-function get_course_users($courseid, $sort="u.lastaccess DESC") {
-// Using this method because the direct SQL just would not always work!
-
-    $teachers = get_course_teachers($courseid, $sort);
-    $students = get_course_students($courseid, $sort);
+function remove_teacher($user, $course=0) {
+/// Removes a teacher from a given course (or ALL courses)
+/// Does not delete the user account
+    global $db;
 
-    if ($teachers and $students) {
-        return array_merge($teachers, $students);
-    } else if ($teachers) {
-        return $teachers;
+    if ($course) {
+        /// First delete any crucial stuff that might still send mail
+        if ($forums = get_records("forum", "course", $course)) {
+            foreach ($forums as $forum) {
+                delete_records("forum_subscriptions", "forum", $forum->id, "user", $user);
+            }
+        }
+        return delete_records("user_teachers", "user", $user, "course", $course);
     } else {
-        return $students;
+        delete_records("forum_subscriptions", "user", $user);
+        return delete_records("user_teachers", "user", $user);
     }
-
-//    return get_records_sql("SELECT u.* FROM user u, user_students s, user_teachers t
-//                            WHERE (s.course = '$courseid' AND s.user = u.id) OR 
-//                                  (t.course = '$courseid' AND t.user = u.id)
-//                            ORDER BY $sort");
-}
-
-
-
-/// MODULE FUNCTIONS /////////////////////////////////////////////////
-
-function get_coursemodule_from_instance($modulename, $instance, $courseid) {
-// Given an instance of a module, finds the coursemodule description
-
-    return get_record_sql("SELECT cm.*, m.name
-                           FROM course_modules cm, modules md, $modulename m 
-                           WHERE cm.course = '$courseid' AND 
-                                 cm.deleted = '0' AND
-                                 cm.instance = m.id AND 
-                                 md.name = '$modulename' AND 
-                                 md.id = cm.module AND
-                                 m.id = '$instance'");
-
 }
 
-function get_all_instances_in_course($modulename, $courseid, $sort="cw.section") {
-// Returns an array of all the active instances of a particular
-// module in a given course.   Returns false on any errors.
-
-    return get_records_sql("SELECT m.*,cw.section,cm.id as coursemodule 
-                            FROM course_modules cm, course_sections cw, modules md, $modulename m 
-                            WHERE cm.course = '$courseid' AND 
-                                  cm.instance = m.id AND 
-                                  cm.deleted = '0' AND
-                                  cm.section = cw.id AND 
-                                  md.name = '$modulename' AND 
-                                  md.id = cm.module
-                            ORDER BY $sort");
+function remove_admin($user) {
+/// Removes an admin from a site
+    global $db;
 
+    return delete_records("user_admins", "user", $user);
 }
 
 
 
-
 /// CORRESPONDENCE  ////////////////////////////////////////////////
 
 function email_to_user($user, $from, $subject, $messagetext, $messagehtml="", $attachment="", $attachname="") {
-//  user        - a user record as an object
-//  from        - a user record as an object
-//  subject     - plain text subject line of the email
-//  messagetext - plain text version of the message
-//  messagehtml - complete html version of the message (optional)
-//  attachment  - a file on the filesystem, relative to $CFG->dataroot
-//  attachname  - the name of the file (extension indicates MIME)
+///  user        - a user record as an object
+///  from        - a user record as an object
+///  subject     - plain text subject line of the email
+///  messagetext - plain text version of the message
+///  messagehtml - complete html version of the message (optional)
+///  attachment  - a file on the filesystem, relative to $CFG->dataroot
+///  attachname  - the name of the file (extension indicates MIME)
 
     global $CFG, $_SERVER;
 
@@ -1700,9 +649,9 @@ function email_to_user($user, $from, $subject, $messagetext, $messagehtml="", $a
 /// FILE HANDLING  /////////////////////////////////////////////
 
 function make_upload_directory($directory) {
-// $directory = a string of directory names under $CFG->dataroot
-// eg  stuff/assignment/1
-// Returns full directory if successful, false if not
+/// $directory = a string of directory names under $CFG->dataroot
+/// eg  stuff/assignment/1
+/// Returns full directory if successful, false if not
 
     global $CFG;
 
@@ -1730,6 +679,7 @@ function make_upload_directory($directory) {
 }
 
 function make_mod_upload_directory($courseid) {
+/// Makes an upload directory for a particular module
     global $CFG;
 
     if (! $moddata = make_upload_directory("$courseid/$CFG->moddata")) {
@@ -1748,7 +698,7 @@ function make_mod_upload_directory($courseid) {
 
 
 function valid_uploaded_file($newfile) {
-// Returns current name of file on disk if true
+/// Returns current name of file on disk if true
     if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
         return $newfile['tmp_name'];
     } else {
@@ -1757,6 +707,7 @@ function valid_uploaded_file($newfile) {
 }
 
 function get_max_upload_file_size() {
+/// Returns the maximum size for uploading files
     if (! $filesize = ini_get("upload_max_filesize")) {
         $filesize = "5M";
     }
@@ -1764,9 +715,9 @@ function get_max_upload_file_size() {
 }
 
 function get_directory_list($rootdir, $excludefile="", $descend=true) {
-// Returns an array with all the filenames in 
-// all subdirectories, relative to the given rootdir.
-// If excludefile is defined, then that file/directory is ignored
+/// Returns an array with all the filenames in 
+/// all subdirectories, relative to the given rootdir.
+/// If excludefile is defined, then that file/directory is ignored
 
     $dirs = array();
    
@@ -1798,7 +749,7 @@ function get_directory_list($rootdir, $excludefile="", $descend=true) {
 }
 
 function get_real_size($size=0) {
-// Converts numbers like 10M into bytes
+/// Converts numbers like 10M into bytes
     if (!$size) {
         return 0; 
     }
@@ -1819,7 +770,7 @@ function get_real_size($size=0) {
 }
 
 function display_size($size) {
-// Converts bytes into display form
+/// Converts bytes into display form
     if ($size >= 1073741824) {
         $size = round($size / 1073741824 * 10) / 10 . "Gb";
     } else if ($size >= 1048576) {
@@ -1833,6 +784,7 @@ function display_size($size) {
 }
 
 function clean_filename($string) {
+/// Cleans a given filename by removing suspicious or troublesome characters
     $string = stripslashes($string);
     $string = eregi_replace("\.\.", "", $string);
     $string = eregi_replace("[^([:alnum:]|\.)]", "_", $string);
@@ -1842,12 +794,8 @@ function clean_filename($string) {
 
 /// STRING TRANSLATION  ////////////////////////////////////////
 
-function print_string($identifier, $module="", $a=NULL) {
-    echo get_string($identifier, $module, $a);
-}
-
 function current_language() {
-// Returns the code for the current language
+/// Returns the code for the current language
     global $CFG, $USER;
 
     if (isset($USER->lang)) {    // User language can override site language
@@ -1857,14 +805,19 @@ function current_language() {
     }
 }
 
+function print_string($identifier, $module="", $a=NULL) {
+/// Given a string to translate - prints it out.
+    echo get_string($identifier, $module, $a);
+}
+
 function get_string($identifier, $module="", $a=NULL) {
-// Return the translated string specified by $identifier as 
-// for $module.  Uses the same format files as STphp.
-// $a is an object, string or number that can be used
-// within translation strings
-//
-// eg "hello \$a->firstname \$a->lastname"
-// or "hello \$a"
+/// Return the translated string specified by $identifier as 
+/// for $module.  Uses the same format files as STphp.
+/// $a is an object, string or number that can be used
+/// within translation strings
+///
+/// eg "hello \$a->firstname \$a->lastname"
+/// or "hello \$a"
 
     global $CFG;
 
@@ -1910,7 +863,7 @@ function get_string($identifier, $module="", $a=NULL) {
 
 
 function get_string_from_file($identifier, $langfile, $destination) {
-// This function is only used from get_string().
+/// This function is only used from get_string().
     include ($langfile);
 
     if (!isset ($string[$identifier])) {
@@ -1937,6 +890,27 @@ function get_list_of_languages() {
     return $languages;
 }
 
+function get_list_of_plugins($plugin="mod") {
+/// Lists plugin directories within some directory
+
+    global $CFG;
+
+    $basedir = opendir("$CFG->dirroot/$plugin");
+    while ($dir = readdir($basedir)) {
+        if ($dir == "." || $dir == ".." || $dir == "CVS") {
+            continue;
+        }
+        if (filetype("$CFG->dirroot/$plugin/$dir") != "dir") {
+            continue;
+        }
+        $plugins[] = $dir;
+    }
+    if ($plugins) {
+        asort($plugins);
+    }
+    return $plugins;
+}
+
 
 /// ENCRYPTION  ////////////////////////////////////////////////
 
@@ -1951,7 +925,7 @@ function rc4decrypt($data) {
 }
 
 function endecrypt ($pwd, $data, $case) {
-// Based on a class by Mukul Sabharwal [mukulsabharwal@yahoo.com]
+/// Based on a class by Mukul Sabharwal [mukulsabharwal@yahoo.com]
 
     if ($case == 'de') {
         $data = urldecode($data);
@@ -2008,137 +982,18 @@ function endecrypt ($pwd, $data, $case) {
 }
 
 
-/// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
-
-function count_words($string) {
-    $string = strip_tags($string);
-    return count(preg_split("/\w\b/", $string)) - 1;
-}
-
-function getweek ($startdate, $thedate) {
-// Given dates in seconds, how many weeks is the date from startdate
-// The first week is 1, the second 2 etc ... 
-    
-    if ($thedate < $startdate) {   // error
-        return 0;  
-    }
-
-    return floor(($thedate - $startdate) / 604800.0) + 1;
-}
-
-function add_to_log($course, $module, $action, $url="", $info="") {
-// Add an entry to the log table.  These are "action" focussed rather
-// than web server hits, and provide a way to easily reconstruct what 
-// any particular student has been doing.
-//
-// course = the course id
-// module = forum, journal, resource, course, user etc
-// action = view, edit, post (often but not always the same as the file.php)
-// url    = the file and parameters used to see the results of the action
-// info   = additional description information 
-
-
-    global $db, $USER, $REMOTE_ADDR;
-
-    if (isset($USER->realuser)) {  // Don't log
-        return;
-    }
-
-    $timenow = time();
-    $info = addslashes($info);
-
-    $result = $db->Execute("INSERT INTO log
-                            SET time = '$timenow', 
-                                user = '$USER->id',
-                                course = '$course',
-                                ip = '$REMOTE_ADDR', 
-                                module = '$module',
-                                action = '$action',
-                                url = '$url',
-                                info = '$info'");
-    if (!$result) {
-        echo "<P>Error: Could not insert a new entry to the Moodle log</P>";  // Don't throw an error
-    }    
-}
-
-function generate_password($maxlen=10) {
-// returns a randomly generated password of length $maxlen.  inspired by
-// http://www.phpbuilder.com/columns/jesus19990502.php3 
-
-    global $CFG;
-
-    $fillers = "1234567890!$-+";
-    $wordlist = file($CFG->wordlist);
-
-    srand((double) microtime() * 1000000);
-    $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
-    $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
-    $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
-
-    return substr($word1 . $filler1 . $word2, 0, $maxlen);
-}
-
-function moodle_needs_upgrading() {
-// Checks version numbers of Main code and all modules to see
-// if there are any mismatches ... returns true or false
-    global $CFG;
-
-    include_once("$CFG->dirroot/version.php");  # defines $version and upgrades
-    if ($CFG->version) { 
-        if ($version > $CFG->version) {
-            return true;
-        }
-        if ($mods = get_list_of_plugins("mod")) {
-            foreach ($mods as $mod) {
-                $fullmod = "$CFG->dirroot/mod/$mod";
-                unset($module);
-                include_once("$fullmod/version.php");  # defines $module with version etc
-                if ($currmodule = get_record("modules", "name", $mod)) {
-                    if ($module->version > $currmodule->version) {
-                        return true;
-                    }
-                }
-            }
-        }
-    } else {
-        return true;
-    }
-    return false;
-}
-
-
-function get_list_of_plugins($plugin="mod") {
-// Lists plugin directories within some directory
-
-    global $CFG;
-
-    $basedir = opendir("$CFG->dirroot/$plugin");
-    while ($dir = readdir($basedir)) {
-        if ($dir == "." || $dir == ".." || $dir == "CVS") {
-            continue;
-        }
-        if (filetype("$CFG->dirroot/$plugin/$dir") != "dir") {
-            continue;
-        }
-        $plugins[] = $dir;
-    }
-    if ($plugins) {
-        asort($plugins);
-    }
-    return $plugins;
-}
-
+/// ENVIRONMENT CHECKING  ////////////////////////////////////////////////////////////
 
 function check_php_version($version="4.1.0") {
-// Returns true is the current version of PHP is greater that the specified one
+/// Returns true is the current version of PHP is greater that the specified one
     $minversion = intval(str_replace(".", "", $version));
     $curversion = intval(str_replace(".", "", phpversion()));
     return ($curversion >= $minversion);
 }
 
 function check_browser_version($brand="MSIE", $version=5.5) {
-// Checks to see if is a browser matches the specified
-// brand and is equal or better version.
+/// Checks to see if is a browser matches the specified
+/// brand and is equal or better version.
     global $HTTP_USER_AGENT;
 
     if (!$HTTP_USER_AGENT) {
@@ -2159,6 +1014,7 @@ function check_browser_version($brand="MSIE", $version=5.5) {
 }
 
 function can_use_richtext_editor() {
+/// Is the richedit editor enabled?
     global $USER, $CFG;
     if ($USER->htmleditor and $CFG->htmleditor) {
         return check_browser_version("MSIE", 5.5);
@@ -2166,8 +1022,8 @@ function can_use_richtext_editor() {
     return false;
 }
 
-
 function check_gd_version() {
+/// Hack to find out the GD version by parsing phpinfo output
     ob_start();
     phpinfo(8);
     $phpinfo = ob_get_contents();
@@ -2191,5 +1047,76 @@ function check_gd_version() {
 }
 
 
+function moodle_needs_upgrading() {
+/// Checks version numbers of Main code and all modules to see
+/// if there are any mismatches ... returns true or false
+    global $CFG;
+
+    include_once("$CFG->dirroot/version.php");  # defines $version and upgrades
+    if ($CFG->version) { 
+        if ($version > $CFG->version) {
+            return true;
+        }
+        if ($mods = get_list_of_plugins("mod")) {
+            foreach ($mods as $mod) {
+                $fullmod = "$CFG->dirroot/mod/$mod";
+                unset($module);
+                include_once("$fullmod/version.php");  # defines $module with version etc
+                if ($currmodule = get_record("modules", "name", $mod)) {
+                    if ($module->version > $currmodule->version) {
+                        return true;
+                    }
+                }
+            }
+        }
+    } else {
+        return true;
+    }
+    return false;
+}
+
+
+/// MISCELLANEOUS ////////////////////////////////////////////////////////////////////
+
+function count_words($string) {
+/// Words are defined as things between whitespace
+    $string = strip_tags($string);
+    return count(preg_split("/\w\b/", $string)) - 1;
+}
+
+function getweek ($startdate, $thedate) {
+/// Given dates in seconds, how many weeks is the date from startdate
+/// The first week is 1, the second 2 etc ... 
+    
+    if ($thedate < $startdate) {   // error
+        return 0;  
+    }
+
+    return floor(($thedate - $startdate) / 604800.0) + 1;
+}
+
+function generate_password($maxlen=10) {
+/// returns a randomly generated password of length $maxlen.  inspired by
+/// http://www.phpbuilder.com/columns/jesus19990502.php3 
+
+    global $CFG;
+
+    $fillers = "1234567890!$-+";
+    $wordlist = file($CFG->wordlist);
+
+    srand((double) microtime() * 1000000);
+    $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
+    $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
+    $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
+
+    return substr($word1 . $filler1 . $word2, 0, $maxlen);
+}
+
+function format_float($num, $places=0) {
+/// Given a float, prints it nicely
+    return sprintf("%.$places"."f", $num);
+}
+
+
 
 ?>
index 224953a7896ff642887a77d56b6a0240aa60daae..5bf03ba1f09da0231ac4c717e423a4a12c3b7976 100644 (file)
@@ -26,8 +26,9 @@
 
 /// Load up standard libraries 
 
-    require("$CFG->libdir/weblib.php");          // Standard web page functions
-    require("$CFG->libdir/moodlelib.php");       // Various Moodle functions
+    require("$CFG->libdir/weblib.php");          // Functions for producing HTML
+    require("$CFG->libdir/datalib.php");         // Functions for accessing databases
+    require("$CFG->libdir/moodlelib.php");       // Other general-purpose functions
 
 
 /// Set error reporting back to normal
@@ -36,7 +37,7 @@
 
 /// Load up any configuration from the config table
     
-    if ($configs = get_records_sql("SELECT * FROM config")) {
+    if ($configs = get_records("config")) {
         $CFG = (array)$CFG;
         foreach ($configs as $config) {
             $CFG[$config->name] = $config->value;
     if (! isset($_SESSION["USER"]))    { $_SESSION["USER"]    = new object; }
     extract($_SESSION);  // Makes $SESSION and $USER available for read-only access
 
-    $FULLME = qualified_me();
-    $ME     = strip_querystring($FULLME);
+    if (!$FULLME) {
+        $FULLME = qualified_me();
+    }
+    $ME = strip_querystring($FULLME);
 
 
 /// Set language/locale of printed times.  If user has chosen a language that 
index 5c9b8c40811214c6564b17a77dea848e3b6bc223..aaf6df54af0629e8149df56b14fd5174e822dedb 100644 (file)
@@ -1,10 +1,33 @@
 <?PHP // $Id$
 
-// weblib.php
-//
-// Library of useful PHP functions and constants related to web pages.
+///////////////////////////////////////////////////////////////////////////
+// weblib.php - functions for web output
 //
+// Library of all general-purpose Moodle PHP functions and constants
+// that produce HTML output
 //
+///////////////////////////////////////////////////////////////////////////
+//                                                                       //
+// NOTICE OF COPYRIGHT                                                   //
+//                                                                       //
+// Moodle - Modular Object-Oriented Dynamic Learning Environment         //
+//          http://moodle.com                                            //
+//                                                                       //
+// Copyright (C) 2001-2003  Martin Dougiamas  http://dougiamas.com       //
+//                                                                       //
+// This program is free software; you can redistribute it and/or modify  //
+// it under the terms of the GNU General Public License as published by  //
+// the Free Software Foundation; either version 2 of the License, or     //
+// (at your option) any later version.                                   //
+//                                                                       //
+// This program is distributed in the hope that it will be useful,       //
+// but WITHOUT ANY WARRANTY; without even the implied warranty of        //
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         //
+// GNU General Public License for more details:                          //
+//                                                                       //
+//          http://www.gnu.org/copyleft/gpl.html                         //
+//                                                                       //
+///////////////////////////////////////////////////////////////////////////
 
 /// Constants
 
@@ -496,4 +519,570 @@ function highlight($needle, $haystack) {
 }
 
 
+
+/// STANDARD WEB PAGE PARTS ///////////////////////////////////////////////////
+
+function print_header ($title="", $heading="", $navigation="", $focus="", $meta="", $cache=true, $button="&nbsp;", $menu="") {
+// $title - appears top of window
+// $heading - appears top of page
+// $navigation - premade navigation string
+// $focus - indicates form element eg  inputform.password
+// $meta - meta tags in the header
+// $cache - should this page be cacheable?
+// $button - HTML code for a button (usually for module editing)
+// $menu - HTML code for a popup menu 
+    global $USER, $CFG, $THEME;
+
+    if (file_exists("$CFG->dirroot/theme/$CFG->theme/styles.php")) {
+        $styles = $CFG->stylesheet;
+    } else {
+        $styles = "$CFG->wwwroot/theme/standard/styles.php";
+    }
+
+    if ($navigation == "home") {
+        $home = true;
+        $navigation = "";
+    }
+
+    if ($button == "") {
+        $button = "&nbsp;";
+    }
+
+    if (!$menu and $navigation) {
+        if (isset($USER->id)) {
+            $menu = "<FONT SIZE=2><A TARGET=_parent HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A></FONT>";
+        } else {
+            $menu = "<FONT SIZE=2><A TARGET=_parent HREF=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</A></FONT>";
+        }
+    }
+
+    // Specify character set ... default is iso-8859-1 but some languages might need something else
+    // Could be optimised by carrying the charset variable around in $USER
+    if (current_language() == "en") {
+        $meta = "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=iso-8859-1\">\n$meta\n";
+    } else {
+        $meta = "<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=".get_string("thischarset")."\">\n$meta\n";
+    }
+
+    if ($CFG->langdir == "RTL") {
+        $direction = " DIR=\"RTL\"";
+    } else {
+        $direction = " DIR=\"LTR\"";
+    }
+    if (!$cache) {   // Do everything we can to prevent clients and proxies caching
+        @header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
+        @header("Pragma: no-cache");
+        $meta .= "\n<META HTTP-EQUIV=\"Pragma\" CONTENT=\"no-cache\">";
+        $meta .= "\n<META HTTP-EQUIV=\"Expires\" CONTENT=\"0\">";
+    }
+
+    include ("$CFG->dirroot/theme/$CFG->theme/header.html");
+}
+
+function print_footer ($course=NULL) {
+// Can provide a course object to make the footer contain a link to 
+// to the course home page, otherwise the link will go to the site home
+    global $USER, $CFG, $THEME;
+
+
+/// Course links
+    if ($course) {
+        if ($course == "home") {   // special case for site home page - please do not remove
+            $homelink  = "<P ALIGN=center><A TITLE=\"Moodle $CFG->release ($CFG->version)\" HREF=\"http://moodle.com/\">";
+            $homelink .= "<BR><IMG WIDTH=130 HEIGHT=19 SRC=\"pix/madewithmoodle2.gif\" BORDER=0></A></P>";
+            $course = get_site();
+            $homepage = true;
+        } else {
+            $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</A>";
+        }
+    } else {
+        $homelink = "<A TARGET=_top HREF=\"$CFG->wwwroot\">".get_string("home")."</A>";
+        $course = get_site();
+    }
+
+/// User links
+    if ($USER->realuser) {
+        if ($realuser = get_record("user", "id", $USER->realuser)) {
+            $realuserinfo = " [<A HREF=\"$CFG->wwwroot/course/loginas.php?id=$course->id&return=$realuser->id\">$realuser->firstname $realuser->lastname</A>] ";
+        }
+    }
+
+    if ($USER->id) {
+        $username = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$USER->id&course=$course->id\">$USER->firstname $USER->lastname</A>";
+        $loggedinas = $realuserinfo.get_string("loggedinas", "moodle", "$username").
+                      " (<A HREF=\"$CFG->wwwroot/login/logout.php\">".get_string("logout")."</A>)";
+    } else {
+        $loggedinas = get_string("loggedinnot", "moodle").
+                      " (<A HREF=\"$CFG->wwwroot/login/index.php\">".get_string("login")."</A>)";
+    }
+
+    include ("$CFG->dirroot/theme/$CFG->theme/footer.html");
+}
+
+
+
+function print_navigation ($navigation) {
+   global $CFG;
+
+   if ($navigation) {
+       if (! $site = get_site()) {
+           $site->shortname = get_string("home");;
+       }
+       echo "<A TARGET=_top HREF=\"$CFG->wwwroot/\">$site->shortname</A> -> $navigation";
+   }
+}
+
+function print_heading($text, $align="CENTER", $size=3) {
+    echo "<P ALIGN=\"$align\"><FONT SIZE=\"$size\"><B>".stripslashes($text)."</B></FONT></P>";
+}
+
+function print_heading_with_help($text, $helppage, $module="moodle") {
+// Centered heading with attached help button (same title text)
+    echo "<P ALIGN=\"CENTER\"><FONT SIZE=\"3\"><B>".stripslashes($text);
+    helpbutton($helppage, $text, $module);
+    echo "</B></FONT></P>";
+}
+    
+function print_continue($link) {
+    global $HTTP_REFERER;
+
+    if (!$link) {
+        $link = $HTTP_REFERER;
+    }
+
+    print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
+}
+
+
+function print_simple_box($message, $align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
+    print_simple_box_start($align, $width, $color, $padding, $class);
+    echo stripslashes($message);
+    print_simple_box_end();
+}
+
+function print_simple_box_start($align="", $width="", $color="#FFFFFF", $padding=5, $class="generalbox") {
+    global $THEME;
+
+    if ($align) {
+        $tablealign = "ALIGN=\"$align\"";
+    }
+    if ($width) {
+        $tablewidth = "WIDTH=\"$width\"";
+    }
+    echo "<table $tablealign $tablewidth class=\"$class\" border=\"0\" cellpadding=\"$padding\" cellspacing=\"0\"><tr><td bgcolor=\"$color\" class=\"$class"."content\">";
+}
+
+function print_simple_box_end() {
+    echo "</td></tr></table>";
+}
+
+function print_single_button($link, $options, $label="OK") {
+    echo "<FORM ACTION=\"$link\" METHOD=GET>";
+    if ($options) {
+        foreach ($options as $name => $value) {
+            echo "<INPUT TYPE=hidden NAME=\"$name\" VALUE=\"$value\">";
+        }
+    }
+    echo "<INPUT TYPE=submit VALUE=\"$label\"></FORM>";
+}
+
+function print_spacer($height=1, $width=1, $br=true) {
+    global $CFG;
+    echo "<IMG HEIGHT=\"$height\" WIDTH=\"$width\" SRC=\"$CFG->wwwroot/pix/spacer.gif\" ALT=\"\">";
+    if ($br) {
+        echo "<BR \>\n";
+    }
+}
+
+function print_file_picture($path, $courseid=0, $height="", $width="", $link="") {
+// Given the path to a picture file in a course, or a URL,
+// this function includes the picture in the page.
+    global $CFG;
+
+    if ($height) {
+        $height = "HEIGHT=\"$height\"";
+    }
+    if ($width) {
+        $width = "WIDTH=\"$width\"";
+    }
+    if ($link) {
+        echo "<A HREF=\"$link\">";
+    }
+    if (substr(strtolower($path), 0, 7) == "http://") {
+        echo "<IMG BORDER=0 $height $width SRC=\"$path\">";
+
+    } else if ($courseid) {
+        echo "<IMG BORDER=0 $height $width SRC=\"";
+        if ($CFG->slasharguments) {        // Use this method if possible for better caching
+            echo "$CFG->wwwroot/file.php/$courseid/$path";
+        } else {
+            echo "$CFG->wwwroot/file.php?file=$courseid/$path";
+        }
+        echo "\">";
+    } else {
+        echo "Error: must pass URL or course";
+    }
+    if ($link) {
+        echo "</A>";
+    }
+}
+
+function print_user_picture($userid, $courseid, $picture, $large=false, $returnstring=false, $link=true) {
+    global $CFG;
+
+    if ($link) {
+        $output = "<A HREF=\"$CFG->wwwroot/user/view.php?id=$userid&course=$courseid\">";
+    } else {
+        $output = "";
+    }
+    if ($large) {
+        $file = "f1.jpg";
+        $size = 100;
+    } else {
+        $file = "f2.jpg";
+        $size = 35;
+    }
+    if ($picture) {
+        if ($CFG->slasharguments) {        // Use this method if possible for better caching
+            $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
+        } else {
+            $output .= "<IMG SRC=\"$CFG->wwwroot/user/pix.php?file=/$userid/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
+        }
+    } else {
+        $output .= "<IMG SRC=\"$CFG->wwwroot/user/default/$file\" BORDER=0 WIDTH=$size HEIGHT=$size ALT=\"\">";
+    }
+    if ($link) {
+        $output .= "</A>";
+    }
+
+    if ($returnstring) {
+        return $output;
+    } else {
+        echo $output;
+    }
+}
+
+function print_table($table) {
+// Prints a nicely formatted table.
+// $table is an object with several properties.
+//     $table->head      is an array of heading names.
+//     $table->align     is an array of column alignments
+//     $table->size      is an array of column sizes
+//     $table->data[]    is an array of arrays containing the data.
+//     $table->width     is an percentage of the page
+//     $table->cellpadding    padding on each cell
+//     $table->cellspacing    spacing between cells
+
+    if (isset($table->align)) {
+        foreach ($table->align as $key => $aa) {
+            if ($aa) {
+                $align[$key] = " ALIGN=\"$aa\"";
+            } else {
+                $align[$key] = "";
+            }
+        }
+    }
+    if (isset($table->size)) {
+        foreach ($table->size as $key => $ss) {
+            if ($ss) {
+                $size[$key] = " WIDTH=\"$ss\"";
+            } else {
+                $size[$key] = "";
+            }
+        }
+    }
+
+    if (!$table->width) {
+        $table->width = "80%";
+    }
+
+    if (!$table->cellpadding) {
+        $table->cellpadding = "5";
+    }
+
+    if (!$table->cellspacing) {
+        $table->cellspacing = "1";
+    }
+
+    print_simple_box_start("CENTER", "$table->width", "#FFFFFF", 0);
+    echo "<TABLE WIDTH=100% BORDER=0 valign=top align=center ";
+    echo " cellpadding=\"$table->cellpadding\" cellspacing=\"$table->cellspacing\" class=\"generaltable\">\n";
+
+    if ($table->head) {
+        echo "<TR>";
+        foreach ($table->head as $key => $heading) {
+            echo "<TH VALIGN=top ".$align[$key].$size[$key]." NOWRAP class=\"generaltableheader\">$heading</TH>";
+        }
+        echo "</TR>\n";
+    }
+
+    foreach ($table->data as $row) {
+        echo "<TR VALIGN=TOP>";
+        foreach ($row as $key => $item) {
+            echo "<TD ".$align[$key].$size[$key]." class=\"generaltablecell\">$item</TD>";
+        }
+        echo "</TR>\n";
+    }
+    echo "</TABLE>\n";
+    print_simple_box_end();
+
+    return true;
+}
+
+function print_editing_switch($courseid) {
+    global $CFG, $USER;
+
+    if (isteacher($courseid)) {
+        if ($USER->editing) {
+            echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=off\">Turn editing off</A>";
+        } else {
+            echo "<A HREF=\"$CFG->wwwroot/course/view.php?id=$courseid&edit=on\">Turn editing on</A>";
+        }
+    }
+}
+
+function print_textarea($richedit, $rows, $cols, $width, $height, $name, $value="") {
+    global $CFG, $THEME;
+
+    if ($richedit) {
+        echo "<object id=richedit style=\"BACKGROUND-COLOR: buttonface\"";
+        echo " data=\"$CFG->wwwroot/lib/rte/richedit.html\"";
+        echo " width=\"$width\" height=\"$height\" ";
+        echo " type=\"text/x-scriptlet\" VIEWASTEXT></object>\n";
+        echo "<TEXTAREA style=\"display:none\" NAME=\"$name\" ROWS=1 COLS=1>";
+        p($value);
+        echo "</TEXTAREA>\n";
+    } else {
+        echo "<TEXTAREA name=\"$name\" rows=\"$rows\" cols=\"$cols\" wrap=virtual>";
+        p($value);
+        echo "</TEXTAREA>\n";
+    }
+}
+
+function print_richedit_javascript($form, $name, $source="no") {
+    echo "<SCRIPT language=\"JavaScript\" event=\"onload\" for=\"window\">\n";
+    echo "   document.richedit.options = \"history=no;source=$source\";";
+    echo "   document.richedit.docHtml = $form.$name.innerText;";
+    echo "</SCRIPT>";
+}
+
+
+function update_course_icon($courseid) {
+// Used to be an icon, but it's now a simple form button
+    global $CFG, $USER;
+
+    if (isteacher($courseid)) {
+        if ($USER->editing) {
+            $string = get_string("turneditingoff");
+            $edit = "off";
+        } else {
+            $string = get_string("turneditingon");
+            $edit = "on";
+        }
+        return "<FORM TARGET=_parent METHOD=GET ACTION=\"$CFG->wwwroot/course/view.php\">".
+               "<INPUT TYPE=hidden NAME=id VALUE=\"$courseid\">".
+               "<INPUT TYPE=hidden NAME=edit VALUE=\"$edit\">".
+               "<INPUT TYPE=submit VALUE=\"$string\"></FORM>";
+    }
+}
+
+function update_module_button($moduleid, $courseid, $string) {
+// Prints the editing button on a module "view" page
+    global $CFG;
+
+    if (isteacher($courseid)) {
+        $string = get_string("updatethis", "", $string);
+        return "<FORM TARGET=_parent METHOD=GET ACTION=\"$CFG->wwwroot/course/mod.php\">".
+               "<INPUT TYPE=hidden NAME=update VALUE=\"$moduleid\">".
+               "<INPUT TYPE=hidden NAME=return VALUE=\"true\">".
+               "<INPUT TYPE=submit VALUE=\"$string\"></FORM>";
+    }
+}
+
+
+function navmenu($course, $cm=NULL) {
+// Given a course and a (current) coursemodule
+// This function returns a small popup menu with all the 
+// course activity modules in it, as a navigation menu
+// The data is taken from the serialised array stored in 
+// the course record
+
+    global $CFG;
+
+    if ($cm) {
+       $cm = $cm->id;
+    }
+
+    if ($course->format == 'weeks') {
+        $strsection = get_string("week");
+    } else {
+        $strsection = get_string("topic");
+    }
+
+    if (!$modinfo = unserialize($course->modinfo)) {
+        return "";
+    }
+    $section = -1;
+    $selected = "";
+    foreach ($modinfo as $mod) {
+        if ($mod->section > 0 and $section <> $mod->section) {
+            $menu[] = "-------------- $strsection $mod->section --------------";
+        }
+        $section = $mod->section;
+        $url = "$mod->mod/view.php?id=$mod->cm";
+        if ($cm == $mod->cm) {
+            $selected = $url;
+        }
+        $mod->name = urldecode($mod->name);
+        if (strlen($mod->name) > 55) {
+            $mod->name = substr($mod->name, 0, 50)."...";
+        }
+        $menu[$url] = $mod->name; 
+    }
+
+    return popup_form("$CFG->wwwroot/mod/", $menu, "navmenu", $selected, get_string("jumpto"), "", "", true);
+}   
+
+
+
+function print_date_selector($day, $month, $year, $currenttime=0) {
+// Currenttime is a default timestamp in GMT
+// Prints form items with the names $day, $month and $year
+
+    if (!$currenttime) {
+        $currenttime = time();
+    }
+    $currentdate = usergetdate($currenttime);
+
+    for ($i=1; $i<=31; $i++) {
+        $days[$i] = "$i";
+    }
+    for ($i=1; $i<=12; $i++) {
+        $months[$i] = date("F", mktime(0,0,0,$i,1,2000));
+    }
+    for ($i=2000; $i<=2010; $i++) {
+        $years[$i] = $i;
+    }
+    choose_from_menu($days,   $day,   $currentdate[mday], "");
+    choose_from_menu($months, $month, $currentdate[mon],  "");
+    choose_from_menu($years,  $year,  $currentdate[year], "");
+}
+
+function print_time_selector($hour, $minute, $currenttime=0) {
+// Currenttime is a default timestamp in GMT
+// Prints form items with the names $hour and $minute
+
+    if (!$currenttime) {
+        $currenttime = time();
+    }
+    $currentdate = usergetdate($currenttime);
+    for ($i=0; $i<=23; $i++) {
+        $hours[$i] = sprintf("%02d",$i);
+    }
+    for ($i=0; $i<=59; $i++) {
+        $minutes[$i] = sprintf("%02d",$i);
+    }
+    choose_from_menu($hours,   $hour,   $currentdate[hours],   "");
+    choose_from_menu($minutes, $minute, $currentdate[minutes], "");
+}
+
+function error ($message, $link="") {
+    global $CFG, $SESSION;
+
+    print_header(get_string("error"));
+    echo "<BR>";
+    print_simple_box($message, "center", "", "#FFBBBB");
+   
+    if (!$link) {
+        if ( !empty($SESSION->fromurl) ) {
+            $link = "$SESSION->fromurl";
+            unset($SESSION->fromurl);
+            save_session("SESSION");
+        } else {
+            $link = "$CFG->wwwroot";
+        }
+    }
+    print_continue($link);
+    print_footer();
+    die;
+}
+
+function helpbutton ($page, $title="", $module="moodle", $image=true, $linktext=false, $text="") {
+    // $page = the keyword that defines a help page
+    // $title = the title of links, rollover tips, alt tags etc
+    // $module = which module is the page defined in
+    // $image = use a help image for the link?  (true/false/"both")
+    // $text = if defined then this text is used in the page, and 
+    //         the $page variable is ignored.
+    global $CFG;
+
+    if ($module == "") {
+        $module = "moodle";
+    }
+
+    if ($image) {
+        if ($linktext) {
+            $linkobject = "$title<IMG align=\"absmiddle\" BORDER=0 HEIGHT=17 WIDTH=22 ALT=\"\" SRC=\"$CFG->wwwroot/pix/help.gif\">";
+        } else {
+            $linkobject = "<IMG align=\"absmiddle\" BORDER=0 HEIGHT=17 WIDTH=22 ALT=\"$title\" SRC=\"$CFG->wwwroot/pix/help.gif\">";
+        }
+    } else {
+        $linkobject = $title;
+    }
+    if ($text) {
+        $url = "/help.php?module=$module&text=".htmlentities(urlencode($text));
+    } else {
+        $url = "/help.php?module=$module&file=$page.html";
+    }
+    link_to_popup_window ($url, "popup", $linkobject, 400, 500, $title);
+}
+
+function notice ($message, $link="") {
+    global $THEME, $HTTP_REFERER;
+
+    if (!$link) {
+        $link = $HTTP_REFERER;
+    }
+
+    echo "<BR>";
+    print_simple_box($message, "center", "", "$THEME->cellheading");
+    print_heading("<A HREF=\"$link\">".get_string("continue")."</A>");
+    print_footer(get_site());
+    die;
+}
+
+function notice_yesno ($message, $linkyes, $linkno) {
+    global $THEME;
+
+    print_simple_box_start("center", "", "$THEME->cellheading");
+    echo "<P ALIGN=CENTER><FONT SIZE=3>$message</FONT></P>";
+    echo "<P ALIGN=CENTER><FONT SIZE=3><B>";
+    echo "<A HREF=\"$linkyes\">".get_string("yes")."</A>";
+    echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
+    echo "<A HREF=\"$linkno\">".get_string("no")."</A>";
+    echo "</B></FONT></P>";
+    print_simple_box_end();
+}
+
+function redirect($url, $message="", $delay=0) {
+// Uses META tags to redirect the user, after printing a notice
+
+    echo "<META HTTP-EQUIV='Refresh' CONTENT='$delay; URL=$url'>";
+
+    if (!empty($message)) {
+        print_header();
+        echo "<CENTER>";
+        echo "<P>$message</P>";
+        echo "<P>( <A HREF=\"$url\">".get_string("continue")."</A> )</P>";
+        echo "</CENTER>";
+    }
+    die; 
+}
+
+function notify ($message) {
+    echo "<P align=center><B><FONT COLOR=#FF0000>$message</FONT></B></P>\n";
+}
+
+
 ?>
index 2ce6431cf4cd8915eb0fa8e5b821e7f07a7b9e74..3c6f06f2fb46d60bea8fd2eb318d51710037bbd1 100644 (file)
@@ -2,7 +2,7 @@
 # Table structure for table `assignment`
 #
 
-CREATE TABLE `assignment` (
+CREATE TABLE `prefix_assignment` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `course` int(10) unsigned NOT NULL default '0',
   `name` varchar(255) NOT NULL default '',
@@ -22,7 +22,7 @@ CREATE TABLE `assignment` (
 # Table structure for table `assignment_submissions`
 #
 
-CREATE TABLE `assignment_submissions` (
+CREATE TABLE `prefix_assignment_submissions` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `assignment` int(10) unsigned NOT NULL default '0',
   `user` int(10) unsigned NOT NULL default '0',
@@ -39,9 +39,9 @@ CREATE TABLE `assignment_submissions` (
 # --------------------------------------------------------
 
 
-INSERT INTO log_display VALUES ('assignment', 'view', 'assignment', 'name');
-INSERT INTO log_display VALUES ('assignment', 'add', 'assignment', 'name');
-INSERT INTO log_display VALUES ('assignment', 'update', 'assignment', 'name');
-INSERT INTO log_display VALUES ('assignment', 'view submissions', 'assignment', 'name');
-INSERT INTO log_display VALUES ('assignment', 'upload', 'assignment', 'name');
+INSERT INTO prefix_log_display VALUES ('assignment', 'view', 'assignment', 'name');
+INSERT INTO prefix_log_display VALUES ('assignment', 'add', 'assignment', 'name');
+INSERT INTO prefix_log_display VALUES ('assignment', 'update', 'assignment', 'name');
+INSERT INTO prefix_log_display VALUES ('assignment', 'view submissions', 'assignment', 'name');
+INSERT INTO prefix_log_display VALUES ('assignment', 'upload', 'assignment', 'name');
 
index 2fabfc38f7961d86f87381c25dd8d1f03f52290c..4aac51e0949ae82dacf334c7cd77c48ddc5103da 100644 (file)
@@ -112,11 +112,7 @@ function assignment_cron () {
 
     $cutofftime = time() - $CFG->maxeditingtime;
 
-    if ($submissions = get_records_sql("SELECT s.*, a.course, a.name
-                                        FROM   assignment_submissions s, assignment a
-                                        WHERE  s.mailed = '0' 
-                                        AND s.timemarked < '$cutofftime' AND s.timemarked > 0
-                                        AND s.assignment = a.id")) {
+    if ($submissions = assignment_get_unmailed_submissions($cutofftime)) {
         $timenow = time();
 
         foreach ($submissions as $submission) {
@@ -194,9 +190,7 @@ function assignment_print_recent_activity(&$logs, $isteacher=false) {
 
     foreach ($logs as $log) {
         if ($log->module == "assignment" and $log->action == "upload") {
-            $assignments[$log->info] = get_record_sql("SELECT a.name, u.firstname, u.lastname
-                                                       FROM assignment a, user u
-                                                      WHERE a.id = '$log->info' AND u.id = '$log->user'");
+            $assignments[$log->info] = assignment_log_info($log);
             $assignments[$log->info]->time = $log->time;
             $assignments[$log->info]->url  = $log->url;
         }
@@ -220,11 +214,62 @@ function assignment_print_recent_activity(&$logs, $isteacher=false) {
 function assignment_grades($assignmentid) {
 /// Must return an array of grades, indexed by user, and a max grade.
 
-    $return->grades = get_records_sql_menu("SELECT user,grade FROM assignment_submissions WHERE assignment = '$assignmentid'");
+    $return->grades = get_records_menu("assignment_submissions", "assignment", 
+                                       $assignmentid, "", "user,grade");
     $return->maxgrade = get_field("assignment", "grade", "id", "$assignmentid");
     return $return;
 }
 
+/// SQL STATEMENTS //////////////////////////////////////////////////////////////////
+
+function assignment_log_info($log) {
+    global $CFG;
+    return get_record_sql("SELECT a.name, u.firstname, u.lastname
+                             FROM {$CFG->prefix}assignment a, 
+                                  {$CFG->prefix}user u
+                            WHERE a.id = '$log->info' 
+                              AND u.id = '$log->user'");
+}
+
+function assignment_get_all_submissions($assignment) {
+/// Return all assignment submissions by ENROLLED students
+    global $CFG;
+    return get_records_sql("SELECT a.* 
+                              FROM {$CFG->prefix}assignment_submissions a, 
+                                   {$CFG->prefix}user_students s
+                             WHERE a.user = s.user
+                               AND s.course = '$assignment->course'
+                               AND a.assignment = '$assignment->id' 
+                          ORDER BY a.timemodified DESC");
+}
+
+function assignment_get_users_done($assignment) {
+/// Return list of users who have done an assignment
+    global $CFG;
+    return get_records_sql("SELECT u.* 
+                              FROM {$CFG->prefix}user u, 
+                                   {$CFG->prefix}user_students s, 
+                                   {$CFG->prefix}assignment_submissions a
+                             WHERE s.course = '$assignment->course' 
+                               AND s.user = u.id
+                               AND u.id = a.user 
+                               AND a.assignment = '$assignment->id'
+                          ORDER BY a.timemodified DESC");
+}
+
+function assignment_get_unmailed_submissions($cutofftime) {
+/// Return list of marked submissions that have not been mailed out
+    global $CFG;
+    return get_records_sql("SELECT s.*, a.course, a.name
+                              FROM {$CFG->prefix}assignment_submissions s, 
+                                   {$CFG->prefix}assignment a
+                             WHERE s.mailed = 0 
+                               AND s.timemarked < $cutofftime 
+                               AND s.timemarked > 0
+                               AND s.assignment = a.id");
+}
+
+
 //////////////////////////////////////////////////////////////////////////////////////
 
 function assignment_file_area_name($assignment, $user) {
@@ -239,24 +284,7 @@ function assignment_file_area($assignment, $user) {
 }
 
 function assignment_get_submission($assignment, $user) {
-    return get_record_sql("SELECT * from assignment_submissions 
-                           WHERE assignment = '$assignment->id' AND user = '$user->id'");
-}
-
-function assignment_get_all_submissions($assignment) {
-// Return all assignment submissions by ENROLLED students
-    return get_records_sql("SELECT a.* FROM assignment_submissions a, user_students s
-                            WHERE a.user = s.user
-                              AND s.course = '$assignment->course'
-                              AND a.assignment = '$assignment->id' 
-                              ORDER BY a.timemodified DESC");
-}
-
-function assignment_get_users_done($assignment) {
-    return get_records_sql("SELECT u.* FROM user u, user_students s, assignment_submissions a
-                            WHERE s.course = '$assignment->course' AND s.user = u.id
-                              AND u.id = a.user AND a.assignment = '$assignment->id'
-                            ORDER BY a.timemodified DESC");
+    return get_record("assignment_submissions", "assignment", $assignment->id, "user", $user->id);
 }
 
 function assignment_print_difference($time) {
index 9eb6aad93c09523ac5a062317d3d29e19589995e..d34985fc93be23249d2c97661c511edfc617f58b 100644 (file)
@@ -51,9 +51,8 @@
             echo "<P align=right><A HREF=\"submissions.php?id=$assignment->id\">".
                   get_string("viewfeedback", "assignment")."</A></P>";
         } else {
-            $count = count_records_sql("SELECT COUNT(*) FROM assignment_submissions 
-                                        WHERE assignment = '$assignment->id' 
-                                          AND timemodified > 0");
+            $count = count_records_select("assignment_submissions", 
+                                          "assignment = '$assignment->id' AND timemodified > 0");
             echo "<P align=right><A HREF=\"submissions.php?id=$assignment->id\">".
                   get_string("viewsubmissions", "assignment", $count)."</A></P>";
         }
index 739996fcdbe70fa7f9fa223afcb6da98dc472b21..aad4042c015b13f077ae19cdfd65eee872877452 100755 (executable)
@@ -14,7 +14,7 @@
 # Table structure for table `choice`\r
 #\r
 \r
-CREATE TABLE choice (\r
+CREATE TABLE prefix_choice (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   course int(10) unsigned NOT NULL default '0',\r
   name varchar(255) NOT NULL default '',\r
@@ -37,7 +37,7 @@ CREATE TABLE choice (
 # Table structure for table `choice_answers`\r
 #\r
 \r
-CREATE TABLE choice_answers (\r
+CREATE TABLE prefix_choice_answers (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   choice int(10) unsigned NOT NULL default '0',\r
   user int(10) unsigned NOT NULL default '0',\r
@@ -51,10 +51,10 @@ CREATE TABLE choice_answers (
 # Dumping data for table `log_display`\r
 #\r
 \r
-INSERT INTO log_display VALUES ('choice', 'view', 'choice', 'name');\r
-INSERT INTO log_display VALUES ('choice', 'update', 'choice', 'name');\r
-INSERT INTO log_display VALUES ('choice', 'add', 'choice', 'name');\r
-INSERT INTO log_display VALUES ('choice', 'report', 'choice', 'name');\r
+INSERT INTO prefix_log_display VALUES ('choice', 'view', 'choice', 'name');\r
+INSERT INTO prefix_log_display VALUES ('choice', 'update', 'choice', 'name');\r
+INSERT INTO prefix_log_display VALUES ('choice', 'add', 'choice', 'name');\r
+INSERT INTO prefix_log_display VALUES ('choice', 'report', 'choice', 'name');\r
 \r
     \r
 \r
index 20cc0aa3a1cc3395fb6e0c305508c15f96631df9..cd80379622f4fc4871292816ab72971d5d7100b9 100644 (file)
@@ -28,7 +28,7 @@
         notice("There are no choices", "../../course/view.php?id=$course->id");
     }
 
-    if ( $allanswers = get_records_sql("SELECT * FROM choice_answers WHERE user='$USER->id'")) {
+    if ( $allanswers = get_records("choice_answers", "user", $USER->id)) {
         foreach ($allanswers as $aa) {
             $answers[$aa->choice] = $aa;
         }
index 8b19b993b1ba6ac6dd15a967a286acd13e2eb424..f0c35817acc7e330757675ca98fb4bef0f003789 100644 (file)
@@ -3,8 +3,7 @@
 $CHOICE_MAX_NUMBER = 6;
 
 function choice_user_outline($course, $user, $mod, $choice) {
-    if ($current = get_record_sql("SELECT * FROM choice_answers
-                                   WHERE choice='$choice->id' AND user='$user->id'")) {
+    if ($current = get_record("choice_answers", "choice", $choice->id, "user", $user->id)) {
         $result->info = "'".choice_get_answer($choice, $current->answer)."'";
         $result->time = $current->timemodified;
         return $result;
@@ -14,8 +13,7 @@ function choice_user_outline($course, $user, $mod, $choice) {
 
 
 function choice_user_complete($course, $user, $mod, $choice) {
-    if ($current = get_record_sql("SELECT * FROM choice_answers
-                                   WHERE choice='$choice->id' AND user='$user->id'")) {
+    if ($current = get_record("choice_answers", "choice", $choice->id, "user", $user->id)) {
         $result->info = "'".choice_get_answer($choice, $current->answer)."'";
         $result->time = $current->timemodified;
         echo get_string("answered", "choice").": $result->info , last updated ".userdate($result->time);
index e41f248d23ce43f9c6b7521ac5ccc4eb6dfe63d9..cb4fdb67000ae09b4d6e0d39c5c5635ca97c481b 100644 (file)
@@ -19,8 +19,7 @@
         error("Course module is incorrect");
     }
 
-    if ($current = get_record_sql("SELECT * FROM choice_answers
-                                     WHERE choice='$choice->id' AND user='$USER->id'")) {
+    if ($current = get_record("choice_answers", "choice", $choice->id, "user", $USER->id)) {
         $answerchecked[$current->answer] = "CHECKED";
     }
 
index eb831cf90eb69bcfc65b409d651763339c14b338..04e4121a982c75d4853be24a9f0a9b5770f85a3f 100644 (file)
@@ -2,7 +2,7 @@
 # Table structure for table `forum`
 #
 
-CREATE TABLE forum (
+CREATE TABLE prefix_forum (
   id int(10) unsigned NOT NULL auto_increment,
   course int(10) unsigned NOT NULL default '0',
   type enum('single','news','general','social','eachuser','teacher') NOT NULL default 'general',
@@ -21,7 +21,7 @@ CREATE TABLE forum (
 # Table structure for table `forum_discussions`
 #
 
-CREATE TABLE forum_discussions (
+CREATE TABLE prefix_forum_discussions (
   id int(10) unsigned NOT NULL auto_increment,
   course int(10) unsigned NOT NULL default '0',
   forum int(10) unsigned NOT NULL default '0',
@@ -37,7 +37,7 @@ CREATE TABLE forum_discussions (
 # Table structure for table `forum_posts`
 #
 
-CREATE TABLE forum_posts (
+CREATE TABLE prefix_forum_posts (
   id int(10) unsigned NOT NULL auto_increment,
   discussion int(10) unsigned NOT NULL default '0',
   parent int(10) unsigned NOT NULL default '0',
@@ -58,7 +58,7 @@ CREATE TABLE forum_posts (
 # Table structure for table `forum_ratings`
 #
 
-CREATE TABLE forum_ratings (
+CREATE TABLE prefix_forum_ratings (
   id int(10) unsigned NOT NULL auto_increment,
   user int(10) unsigned NOT NULL default '0',
   post int(10) unsigned NOT NULL default '0',
@@ -72,7 +72,7 @@ CREATE TABLE forum_ratings (
 # Table structure for table `forum_subscriptions`
 #
 
-CREATE TABLE forum_subscriptions (
+CREATE TABLE prefix_forum_subscriptions (
   id int(10) unsigned NOT NULL auto_increment,
   user int(10) unsigned NOT NULL default '0',
   forum int(10) unsigned NOT NULL default '0',
@@ -85,14 +85,14 @@ CREATE TABLE forum_subscriptions (
 # Dumping data for table `log_display`
 #
 
-INSERT INTO log_display VALUES ('forum', 'add', 'forum', 'name');
-INSERT INTO log_display VALUES ('forum', 'update', 'forum', 'name');
-INSERT INTO log_display VALUES ('forum', 'add discussion', 'forum_discussions', 'name');
-INSERT INTO log_display VALUES ('forum', 'add post', 'forum_posts', 'subject');
-INSERT INTO log_display VALUES ('forum', 'update post', 'forum_posts', 'subject');
-INSERT INTO log_display VALUES ('forum', 'view subscribers', 'forum', 'name');
-INSERT INTO log_display VALUES ('forum', 'view discussion', 'forum_discussions', 'name');
-INSERT INTO log_display VALUES ('forum', 'view forum', 'forum', 'name');
-INSERT INTO log_display VALUES ('forum', 'subscribe', 'forum', 'name');
-INSERT INTO log_display VALUES ('forum', 'unsubscribe', 'forum', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'add', 'forum', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'update', 'forum', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'add discussion', 'forum_discussions', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'add post', 'forum_posts', 'subject');
+INSERT INTO prefix_log_display VALUES ('forum', 'update post', 'forum_posts', 'subject');
+INSERT INTO prefix_log_display VALUES ('forum', 'view subscribers', 'forum', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'view discussion', 'forum_discussions', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'view forum', 'forum', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'subscribe', 'forum', 'name');
+INSERT INTO prefix_log_display VALUES ('forum', 'unsubscribe', 'forum', 'name');
 
index 1b4507c74c21cfad5a87ca812741f812ef981137..79443117680e6ff82519708b68ab635d34fdf8e8 100644 (file)
@@ -402,6 +402,45 @@ function forum_grades($forumid) {
 }
 
 
+/// SQL FUNCTIONS ///////////////////////////////////////////////////////////
+
+function forum_search_posts($search, $courseid) {
+/// Returns a list of posts that were found
+    global $CFG;
+
+    if (!isteacher($courseid)) {
+        $notteacherforum = "AND f.type <> 'teacher'";
+    } else {
+        $notteacherforum = "";
+    }
+
+    return get_records_sql("SELECT p.*,u.firstname,u.lastname,u.email,u.picture,u.id as userid 
+                            FROM {$CFG->prefix}forum_posts p,  
+                                 {$CFG->prefix}forum_discussions d, 
+                                 {$CFG->prefix}user u, 
+                                 {$CFG->prefix}forum f
+                            WHERE (p.message LIKE '%$search%' OR p.subject LIKE '%$search%')
+                              AND p.user = u.id 
+                              AND p.discussion = d.id 
+                              AND d.course = '$courseid' 
+                              AND d.forum = f.id 
+                              $notteacherforum
+                         ORDER BY p.modified DESC LIMIT 0, 50");
+}
+
+function forum_get_ratings($postid, $sort="u.firstname ASC") {
+/// Returns a list of ratings for a particular post - sorted.
+    global $CFG;
+    return get_records_sql("SELECT u.*, r.rating, r.time 
+                              FROM {$CFG->prefix}forum_ratings r, 
+                                   {$CFG->prefix}user u
+                             WHERE r.post='$postid' 
+                               AND r.user=u.id 
+                             ORDER BY $sort");
+}
+
+
+
 /// OTHER FUNCTIONS ///////////////////////////////////////////////////////////
 
 
@@ -1185,15 +1224,17 @@ function forum_subscribed_users($course, $forum) {
 }
 
 function forum_subscribe($userid, $forumid) {
-    global $db;
+/// Adds user to the subscriber list
+
+    $sub->user  = $userid;
+    $sub->forum = $forumid;
 
-    return $db->Execute("INSERT INTO forum_subscriptions SET user = '$userid', forum = '$forumid'");
+    return insert_record("forum_subscriptions", $sub);
 }
 
 function forum_unsubscribe($userid, $forumid) {
-    global $db;
-
-    return $db->Execute("DELETE FROM forum_subscriptions WHERE user = '$userid' AND forum = '$forumid'");
+/// Removes user from the subscriber list
+    return delete_records("forum_subscriptions", "user", $userid, "forum", $forumid)
 }
 
 
index 225c46cbf668a1f3cef50d05e1f5a7dace2be343..5f6fcfee6bd8a465bc1aed7bdbca8b6e2416b1e8 100644 (file)
 
 
     if ($post->discussion) {
-        if (! $toppost = get_record_sql("SELECT * FROM forum_posts 
-                                         WHERE discussion='$post->discussion' 
-                                         AND parent = 0")) {
+        if (! $toppost = get_record("forum_posts", "discussion", $post->discussion, "parent", 0)) {
             error("Could not find top parent of post $post->id");
         }
     } else {
index e2540b2f4ebcc39a175ee26787293f309aad8c27..c24213e1d94816bc4eae8ee166a1002ce70b4332 100644 (file)
                 continue;
             }
             if ($rating) {
-                if ($check = get_record_sql("SELECT COUNT(*) as count FROM forum_ratings 
-                                        WHERE user='$USER->id' AND post='$post'")){
-                    if ($check->count == 0) {
-                        $timenow = time();
-                        if (!$rs = $db->Execute("INSERT DELAYED INTO forum_ratings 
-                                            SET user='$USER->id', post='$post', time='$timenow', rating='$rating'")){
-                            error("Could not insert a new rating ($post = $rating)");
-                        }
-                        
-                    } else {
-                        error("You've rated this question before ($post)");
+                if (record_exists("forum_ratings", "user", $USER->id, "post", $post)) {
+                    error("You've rated this question before ($post)");
+                } else {
+                    unset($newrating);
+                    $newrating->user = $USER->id;
+                    $newrating->time = time();
+                    $newrating->post = $post;
+                    $newrating->rating = $rating;
+
+                    if (! insert_record("forum_ratings", $newrating)) {
+                        error("Could not insert a new rating ($post = $rating)");
                     }
                 }
             }
index e4250830b6be8c68869285663e57b8b725a520e6..790a63df3baa9056ab7bea9ac96753e7327c2114 100644 (file)
@@ -33,8 +33,7 @@
 
     print_header("Ratings for: $post->subject");
 
-    if (!$ratings = get_records_sql("SELECT u.*, r.rating, r.time FROM forum_ratings r, user u
-                                     WHERE r.post='$post->id' AND r.user=u.id ORDER BY $sort")) {
+    if (!$ratings = forum_get_ratings($post->id, $sort)) {
         echo "No ratings for this post: \"$post->subject\"";
         die;
     } else {
index f29d465278aaad420ec14d09312b0b3277343da6..4122d7cef1de9e14d93803c6f6cf9347b002a187 100644 (file)
 
     if ($search) {
     
-        if (!isteacher($course->id)) {
-            $notteacherforum = "AND f.type <> 'teacher'";
-        } else {
-            $notteacherforum = "";
-        }
-
-        $posts = get_records_sql("SELECT p.*,u.firstname,u.lastname,u.email,u.picture,u.id as userid 
-                                  FROM forum_posts p, forum_discussions d, user u, forum f
-                                  WHERE (p.message LIKE '%$search%' OR p.subject LIKE '%$search%')
-                                        AND p.user = u.id 
-                                        AND p.discussion = d.id AND d.course = '$course->id' 
-                                        AND d.forum = f.id $notteacherforum
-                                  ORDER BY p.modified DESC LIMIT 0, 50 ");
-
-        if (!$posts) {
+        if (!$posts = forum_search_posts($search, $course->id)) {
             print_heading("<BR>".get_string("nopostscontaining", "forum", $search));
 
         } else {
index 36bfcf64f481f5d766d04cce04c621945c03dbb2..4bc1ed39f861021d18df008e80396799c3ab1380 100755 (executable)
@@ -14,7 +14,7 @@
 # Table structure for table `journal`\r
 #\r
 \r
-CREATE TABLE journal (\r
+CREATE TABLE prefix_journal (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   course int(10) unsigned NOT NULL default '0',\r
   name varchar(255) default NULL,\r
@@ -30,7 +30,7 @@ CREATE TABLE journal (
 # Table structure for table `journal_entries`\r
 #\r
 \r
-CREATE TABLE journal_entries (\r
+CREATE TABLE prefix_journal_entries (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   journal int(10) unsigned NOT NULL default '0',\r
   user int(10) unsigned NOT NULL default '0',\r
@@ -49,7 +49,7 @@ CREATE TABLE journal_entries (
 # Dumping data for table `log_display`\r
 #\r
 \r
-INSERT INTO log_display VALUES ('journal', 'view', 'journal', 'name');\r
-INSERT INTO log_display VALUES ('journal', 'add entry', 'journal', 'name');\r
-INSERT INTO log_display VALUES ('journal', 'update entry', 'journal', 'name');\r
-INSERT INTO log_display VALUES ('journal', 'view responses', 'journal', 'name');\r
+INSERT INTO prefix_log_display VALUES ('journal', 'view', 'journal', 'name');\r
+INSERT INTO prefix_log_display VALUES ('journal', 'add entry', 'journal', 'name');\r
+INSERT INTO prefix_log_display VALUES ('journal', 'update entry', 'journal', 'name');\r
+INSERT INTO prefix_log_display VALUES ('journal', 'view responses', 'journal', 'name');\r
index 23cf709bd5db0696b3f9e2f8359942721ebe92e5..3fff3842e926579860ee0af773991aaf58ae2014 100644 (file)
@@ -22,8 +22,7 @@
         error("Course module is incorrect");
     }
 
-    $entry = get_record_sql("SELECT * FROM journal_entries 
-                             WHERE user='$USER->id' AND journal='$journal->id'");
+    $entry = get_record("journal_entries", "user", $USER->id, "journal", $journal->id);
 
 
 /// If data submitted, then process and store.
index 1cad28876d473819474ecf9b09b6ac0537ddfae4..21938b3d7836a156817f24d05834ccbf67278087 100644 (file)
@@ -49,8 +49,7 @@
 
     foreach ($journals as $journal) {
 
-        $entry = get_record_sql("SELECT text FROM journal_entries 
-                                 WHERE user='$USER->id' AND journal='$journal->id'");
+        $entrytext = get_field("journal_entries", "text", "user", $USER->id, "journal", $journal->id");
 
         $journal->timestart  = $course->startdate + (($journal->section - 1) * 608400);
         if ($journal->daysopen) {
@@ -61,7 +60,7 @@
         $journalopen = ($journal->timestart < $timenow && $timenow < $journal->timefinish);
 
 
-        $text = text_to_html($entry->text)."<P ALIGN=right><A HREF=\"view.php?id=$journal->coursemodule\">";
+        $text = text_to_html($entrytext)."<P ALIGN=right><A HREF=\"view.php?id=$journal->coursemodule\">";
         if ($journalopen) {
             $text .= "$stredit</A></P>";
         } else {
index e06d6ea946bca0686d681684bba197229fffadb3..d9d95d348a46b0daca779301890925324df094a6 100644 (file)
@@ -9,8 +9,7 @@ $JOURNAL_RATING = array ("3" => get_string("journalrating3", "journal"),
 // STANDARD MODULE FUNCTIONS /////////////////////////////////////////////////////////
 
 function journal_user_outline($course, $user, $mod, $journal) {
-    if ($entry = get_record_sql("SELECT * FROM journal_entries 
-                                 WHERE user='$user->id' AND journal='$journal->id'")) {
+    if ($entry = get_record("journal_entries", "user", $user->id, "journal", $journal->id)) {
 
         $numwords = count(preg_split("/\w\b/", $entry->text)) - 1;
 
@@ -24,8 +23,7 @@ function journal_user_outline($course, $user, $mod, $journal) {
 
 function journal_user_complete($course, $user, $mod, $journal) {
 
-    if ($entry = get_record_sql("SELECT * FROM journal_entries 
-                             WHERE user='$user->id' AND journal='$journal->id'")) {
+    if ($entry = get_record("journal_entries", "user", $user->id, "journal", $journal->id)) {
 
         print_simple_box_start();
         if ($entry->modified) {
@@ -53,11 +51,7 @@ function journal_cron () {
 
     $cutofftime = time() - $CFG->maxeditingtime;
 
-    if ($entries = get_records_sql("SELECT e.*, j.course, j.name
-                                     FROM   journal_entries e, journal j
-                                     WHERE  e.mailed = '0' 
-                                     AND e.timemarked < '$cutofftime' AND e.timemarked > 0
-                                     AND e.journal = j.id")) {
+    if ($entries = journal_get_unmailed_graded($cutofftime)) {
         $timenow = time();
 
         foreach ($entries as $entry) {
@@ -135,10 +129,7 @@ function journal_print_recent_activity(&$logs, $isteacher=false) {
         if ($log->module == "journal") {
             if ($log->action == "add entry" or $log->action == "update entry") {
                 if (!isset($journals[$log->info])) {
-                    $journals[$log->info] = get_record_sql("SELECT j.*, u.firstname, u.lastname
-                                           FROM journal j, journal_entries e, user u
-                                           WHERE e.id = '$log->info' AND e.journal = j.id
-                                                 AND e.user = u.id");
+                    $journals[$log->info] = journal_log_info($log);
                     $journals[$log->info]->time = $log->time;
                     $journals[$log->info]->url = $log->url;
                 }
@@ -165,9 +156,7 @@ function journal_grades($journalid) {
 /// Must return an array of grades, indexed by user, and a max grade.
     global $JOURNAL_RATING;
 
-    if ($return->grades = get_records_sql_menu("SELECT user,rating 
-                                                  FROM journal_entries
-                                                 WHERE journal = '$journalid'")) {
+    if ($return->grades = get_records_menu("journal_entries", "journal", $journalid, "", "user,rating")) {
         foreach ($return->grades as $key => $value) {
             if ($value) {
                 $return->grades[$key] = $JOURNAL_RATING[$value];
@@ -181,17 +170,48 @@ function journal_grades($journalid) {
 }
 
 
-// OTHER JOURNAL FUNCTIONS ///////////////////////////////////////////////////////////////////
-
+// SQL FUNCTIONS ///////////////////////////////////////////////////////////////////
 
 function journal_get_users_done($journal) {
-    return get_records_sql("SELECT u.* FROM user u, user_students s, user_teachers t, journal_entries j
-                            WHERE ((s.course = '$journal->course' AND s.user = u.id) OR 
-                                   (t.course = '$journal->course' AND t.user = u.id))
-                              AND u.id = j.user AND j.journal = '$journal->id'
-                            ORDER BY j.modified DESC");
+    global $CFG;
+    return get_records_sql("SELECT u.* 
+                              FROM {$CFG->prefix}user u, 
+                                   {$CFG->prefix}user_students s, 
+                                   {$CFG->prefix}user_teachers t, 
+                                   {$CFG->prefix}journal_entries j
+                             WHERE ((s.course = '$journal->course' AND s.user = u.id) 
+                                OR  (t.course = '$journal->course' AND t.user = u.id))
+                               AND u.id = j.user 
+                               AND j.journal = '$journal->id'
+                          ORDER BY j.modified DESC");
+}
+
+function journal_get_unmailed_graded($cutofftime) {
+    global $CFG;
+    return get_records_sql("SELECT e.*, j.course, j.name
+                              FROM {$CFG->prefix}journal_entries e, 
+                                   {$CFG->prefix}journal j
+                             WHERE e.mailed = '0' 
+                               AND e.timemarked < '$cutofftime' 
+                               AND e.timemarked > 0
+                               AND e.journal = j.id");
+}
+
+function journal_log_info($log) {
+    global $CFG;
+    return get_record_sql("SELECT j.*, u.firstname, u.lastname
+                             FROM {$CFG->prefix}journal j, 
+                                  {$CFG->prefix}journal_entries e, 
+                                  {$CFG->prefix}user u
+                            WHERE e.id = '$log->info' 
+                              AND e.journal = j.id
+                              AND e.user = u.id");
 }
 
+// OTHER JOURNAL FUNCTIONS ///////////////////////////////////////////////////////////////////
+
+
+
 function journal_print_user_entry($course, $user, $entry, $teachers, $ratings) {
     global $THEME;
 
index 8ddf4a0e07cc59692ff5e22e8b227478dedf8d9b..fa66bf925f89b9dcb50c3f5c2a9e230fafc4eb62 100644 (file)
@@ -24,7 +24,7 @@
     }
 
     // make some easy ways to access the entries.
-    if ( $eee = get_records_sql("SELECT * FROM journal_entries WHERE journal='$journal->id'")) {
+    if ( $eee = get_records("journal_entries", "journal", $journal->id)) {
         foreach ($eee as $ee) {
             $entrybyuser[$ee->user] = $ee;
             $entrybyentry[$ee->id]  = $ee;
index ad49c945d99d2cfb124e9c497d4fdfd23d7bbcd8..cce12686be2a9c71a21b7193df058fbf861abd06 100644 (file)
@@ -80,8 +80,8 @@
             echo "</CENTER>";
         }
 
-        if ($entry = get_record_sql("SELECT * FROM journal_entries 
-                                     WHERE user='$USER->id' AND journal='$journal->id'")) {
+
+        if ($entry = get_record("journal_entries", "user", $USER->id, "journal", $journal->id)) {
 
             if (empty($entry->text)) {
                 echo "<P ALIGN=center><B>".get_string("blankentry","journal")."</B></P>";
index 1ac102649b7d5f2d31440159857505c8c4669e31..029cf3fbbdff4bf2dc91e7d88594c31b01928839 100644 (file)
@@ -13,7 +13,7 @@
 # Table structure for table `quiz`
 #
 
-CREATE TABLE `quiz` (
+CREATE TABLE `prefix_quiz` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `course` int(10) unsigned NOT NULL default '0',
   `name` varchar(255) NOT NULL default '',
@@ -37,7 +37,7 @@ CREATE TABLE `quiz` (
 # Table structure for table `quiz_answers`
 #
 
-CREATE TABLE `quiz_answers` (
+CREATE TABLE `prefix_quiz_answers` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `question` int(10) unsigned NOT NULL default '0',
   `answer` varchar(255) NOT NULL default '',
@@ -52,7 +52,7 @@ CREATE TABLE `quiz_answers` (
 # Table structure for table `quiz_attempts`
 #
 
-CREATE TABLE `quiz_attempts` (
+CREATE TABLE `prefix_quiz_attempts` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `quiz` int(10) unsigned NOT NULL default '0',
   `user` int(10) unsigned NOT NULL default '0',
@@ -69,7 +69,7 @@ CREATE TABLE `quiz_attempts` (
 # Table structure for table `quiz_categories`
 #
 
-CREATE TABLE `quiz_categories` (
+CREATE TABLE `prefix_quiz_categories` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `course` int(10) unsigned NOT NULL default '0',
   `name` varchar(255) NOT NULL default '',
@@ -83,7 +83,7 @@ CREATE TABLE `quiz_categories` (
 # Table structure for table `quiz_grades`
 #
 
-CREATE TABLE `quiz_grades` (
+CREATE TABLE `prefix_quiz_grades` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `quiz` int(10) unsigned NOT NULL default '0',
   `user` int(10) unsigned NOT NULL default '0',
@@ -97,7 +97,7 @@ CREATE TABLE `quiz_grades` (
 # Table structure for table `quiz_multichoice`
 #
 
-CREATE TABLE `quiz_multichoice` (
+CREATE TABLE `prefix_quiz_multichoice` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `question` int(10) unsigned NOT NULL default '0',
   `layout` tinyint(4) NOT NULL default '0',
@@ -112,7 +112,7 @@ CREATE TABLE `quiz_multichoice` (
 # Table structure for table `quiz_question_grades`
 #
 
-CREATE TABLE `quiz_question_grades` (
+CREATE TABLE `prefix_quiz_question_grades` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `quiz` int(10) unsigned NOT NULL default '0',
   `question` int(10) unsigned NOT NULL default '0',
@@ -125,7 +125,7 @@ CREATE TABLE `quiz_question_grades` (
 # Table structure for table `quiz_questions`
 #
 
-CREATE TABLE `quiz_questions` (
+CREATE TABLE `prefix_quiz_questions` (
   `id` int(10) NOT NULL auto_increment,
   `category` int(10) NOT NULL default '0',
   `name` varchar(255) NOT NULL default '',
@@ -140,7 +140,7 @@ CREATE TABLE `quiz_questions` (
 # Table structure for table `quiz_responses`
 #
 
-CREATE TABLE `quiz_responses` (
+CREATE TABLE `prefix_quiz_responses` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `attempt` int(10) unsigned NOT NULL default '0',
   `question` int(10) unsigned NOT NULL default '0',
@@ -154,7 +154,7 @@ CREATE TABLE `quiz_responses` (
 # Table structure for table `quiz_shortanswer`
 #
 
-CREATE TABLE `quiz_shortanswer` (
+CREATE TABLE `prefix_quiz_shortanswer` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `question` int(10) unsigned NOT NULL default '0',
   `answers` varchar(255) NOT NULL default '',
@@ -168,7 +168,7 @@ CREATE TABLE `quiz_shortanswer` (
 # Table structure for table `quiz_truefalse`
 #
 
-CREATE TABLE `quiz_truefalse` (
+CREATE TABLE `prefix_quiz_truefalse` (
   `id` int(10) unsigned NOT NULL auto_increment,
   `question` int(10) unsigned NOT NULL default '0',
   `true` int(10) unsigned NOT NULL default '0',
@@ -178,8 +178,8 @@ CREATE TABLE `quiz_truefalse` (
 ) TYPE=MyISAM COMMENT='Options for True-False questions';
 
 
-INSERT INTO log_display VALUES ('quiz', 'view', 'quiz', 'name');
-INSERT INTO log_display VALUES ('quiz', 'report', 'quiz', 'name');
-INSERT INTO log_display VALUES ('quiz', 'attempt', 'quiz', 'name');
-INSERT INTO log_display VALUES ('quiz', 'submit', 'quiz', 'name');
+INSERT INTO prefix_log_display VALUES ('quiz', 'view', 'quiz', 'name');
+INSERT INTO prefix_log_display VALUES ('quiz', 'report', 'quiz', 'name');
+INSERT INTO prefix_log_display VALUES ('quiz', 'attempt', 'quiz', 'name');
+INSERT INTO prefix_log_display VALUES ('quiz', 'submit', 'quiz', 'name');
 
index d9c9a5ee63fea266a4fa968d5adb72aa2abb56d4..ac50cfcabfc689e164a40186da6c319c4b6bac0c 100755 (executable)
@@ -14,7 +14,7 @@
 # Table structure for table `resource`\r
 #\r
 \r
-CREATE TABLE resource (\r
+CREATE TABLE prefix_resource (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   course tinyint(10) unsigned NOT NULL default '0',\r
   name varchar(255) NOT NULL default '',\r
@@ -32,4 +32,4 @@ CREATE TABLE resource (
 # Dumping data for table `log_display`\r
 #\r
 \r
-INSERT INTO log_display VALUES ('resource', 'view', 'resource', 'name');\r
+INSERT INTO prefix_log_display VALUES ('resource', 'view', 'resource', 'name');\r
index 7e96b28cad24fbb89a70b25d10f93cd097ab4d09..cbae8ad76c4d2f4e3141c399d7ff80e5b7158f23 100755 (executable)
@@ -14,7 +14,7 @@
 # Table structure for table `survey`\r
 #\r
 \r
-CREATE TABLE survey (\r
+CREATE TABLE prefix_survey (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   course int(10) unsigned NOT NULL default '0',\r
   template int(10) unsigned NOT NULL default '0',\r
@@ -31,10 +31,10 @@ CREATE TABLE survey (
 # Dumping data for table `survey`\r
 #\r
 \r
-INSERT INTO `survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (1, 0, 0, 0, 985017600, 985017600, 'collesaname', 'collesaintro', '25,26,27,28,29,30,43,44');\r
-INSERT INTO `survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (2, 0, 0, 0, 985017600, 985017600, 'collespname', 'collespintro', '31,32,33,34,35,36,43,44');\r
-INSERT INTO `survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (3, 0, 0, 0, 985017600, 985017600, 'collesapname', 'collesapintro', '37,38,39,40,41,42,43,44');\r
-INSERT INTO `survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (4, 0, 0, 0, 985017600, 985017600, 'attlsname', 'attlsintro', '65,67,68');\r
+INSERT INTO `prefix_survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (1, 0, 0, 0, 985017600, 985017600, 'collesaname', 'collesaintro', '25,26,27,28,29,30,43,44');\r
+INSERT INTO `prefix_survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (2, 0, 0, 0, 985017600, 985017600, 'collespname', 'collespintro', '31,32,33,34,35,36,43,44');\r
+INSERT INTO `prefix_survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (3, 0, 0, 0, 985017600, 985017600, 'collesapname', 'collesapintro', '37,38,39,40,41,42,43,44');\r
+INSERT INTO `prefix_survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemodified`, `name`, `intro`, `questions`) VALUES (4, 0, 0, 0, 985017600, 985017600, 'attlsname', 'attlsintro', '65,67,68');\r
 \r
 \r
 \r
@@ -42,7 +42,7 @@ INSERT INTO `survey` (`id`, `course`, `template`, `days`, `timecreated`, `timemo
 # Table structure for table `survey_analysis`\r
 #\r
 \r
-CREATE TABLE survey_analysis (\r
+CREATE TABLE prefix_survey_analysis (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   survey int(10) unsigned NOT NULL default '0',\r
   user int(10) unsigned NOT NULL default '0',\r
@@ -61,7 +61,7 @@ CREATE TABLE survey_analysis (
 # Table structure for table `survey_answers`\r
 #\r
 \r
-CREATE TABLE survey_answers (\r
+CREATE TABLE prefix_survey_answers (\r
   id int(10) unsigned NOT NULL auto_increment,\r
   user int(10) unsigned NOT NULL default '0',\r
   survey int(10) unsigned NOT NULL default '0',\r
@@ -83,7 +83,7 @@ CREATE TABLE survey_answers (
 # Table structure for table `survey_questions`\r
 #\r
 \r
-CREATE TABLE `survey_questions` (\r
+CREATE TABLE `prefix_survey_questions` (\r
   `id` int(10) unsigned NOT NULL auto_increment,\r
   `text` varchar(255) NOT NULL default '',\r
   `shorttext` varchar(30) NOT NULL default '',\r
@@ -98,73 +98,73 @@ CREATE TABLE `survey_questions` (
 # Dumping data for table `survey_questions`\r
 #\r
 \r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (1, 'colles1', 'colles1short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (2, 'colles2', 'colles2short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (3, 'colles3', 'colles3short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (4, 'colles4', 'colles4short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (5, 'colles5', 'colles5short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (6, 'colles6', 'colles6short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (7, 'colles7', 'colles7short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (8, 'colles8', 'colles8short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (9, 'colles9', 'colles9short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (10, 'colles10', 'colles10short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (11, 'colles11', 'colles11short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (12, 'colles12', 'colles12short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (13, 'colles13', 'colles13short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (14, 'colles14', 'colles14short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (15, 'colles15', 'colles15short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (16, 'colles16', 'colles16short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (17, 'colles17', 'colles17short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (18, 'colles18', 'colles18short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (19, 'colles19', 'colles19short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (20, 'colles20', 'colles20short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (21, 'colles21', 'colles21short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (22, 'colles22', 'colles22short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (23, 'colles23', 'colles23short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (24, 'colles24', 'colles24short', '', '', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (25, 'collesm1', 'collesm1short', '1,2,3,4', 'collesmintro', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (26, 'collesm2', 'collesm2short', '5,6,7,8', 'collesmintro', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (27, 'collesm3', 'collesm3short', '9,10,11,12', 'collesmintro', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (28, 'collesm4', 'collesm4short', '13,14,15,16', 'collesmintro', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (29, 'collesm5', 'collesm5short', '17,18,19,20', 'collesmintro', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (30, 'collesm6', 'collesm6short', '21,22,23,24', 'collesmintro', 1, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (31, 'collesm1', 'collesm1short', '1,2,3,4', 'collesmintro', 2, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (32, 'collesm2', 'collesm2short', '5,6,7,8', 'collesmintro', 2, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (33, 'collesm3', 'collesm3short', '9,10,11,12', 'collesmintro', 2, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (34, 'collesm4', 'collesm4short', '13,14,15,16', 'collesmintro', 2, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (35, 'collesm5', 'collesm5short', '17,18,19,20', 'collesmintro', 2, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (36, 'collesm6', 'collesm6short', '21,22,23,24', 'collesmintro', 2, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (37, 'collesm1', 'collesm1short', '1,2,3,4', 'collesmintro', 3, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (38, 'collesm2', 'collesm2short', '5,6,7,8', 'collesmintro', 3, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (39, 'collesm3', 'collesm3short', '9,10,11,12', 'collesmintro', 3, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (40, 'collesm4', 'collesm4short', '13,14,15,16', 'collesmintro', 3, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (41, 'collesm5', 'collesm5short', '17,18,19,20', 'collesmintro', 3, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (42, 'collesm6', 'collesm6short', '21,22,23,24', 'collesmintro', 3, 'scaletimes5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (43, 'howlong', '', '', '', 1, 'howlongoptions');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (44, 'othercomments', '', '', '', 0, '');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (64, 'attls20', 'attls20short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (58, 'attls14', 'attls14short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (59, 'attls15', 'attls15short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (60, 'attls16', 'attls16short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (61, 'attls17', 'attls17short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (62, 'attls18', 'attls18short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (63, 'attls19', 'attls19short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (56, 'attls12', 'attls12short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (57, 'attls13', 'attls13short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (55, 'attls11', 'attls11short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (54, 'attls10', 'attls10short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (53, 'attls9', 'attls9short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (52, 'attls8', 'attls8short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (51, 'attls7', 'attls7short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (50, 'attls6', 'attls6short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (49, 'attls5', 'attls5short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (48, 'attls4', 'attls4short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (47, 'attls3', 'attls3short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (45, 'attls1', 'attls1short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (46, 'attls2', 'attls2short', '', '', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (65, 'attlsm1', 'attlsm1', '45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64', 'attlsmintro', 1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (67, 'attlsm2', 'attlsm2', '63,62,59,57,55,49,52,50,48,47', 'attlsmintro', -1, 'scaleagree5');\r
-INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (68, 'attlsm3', 'attlsm3', '46,54,45,51,60,53,56,58,61,64', 'attlsmintro', -1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (1, 'colles1', 'colles1short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (2, 'colles2', 'colles2short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (3, 'colles3', 'colles3short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (4, 'colles4', 'colles4short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (5, 'colles5', 'colles5short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (6, 'colles6', 'colles6short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (7, 'colles7', 'colles7short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (8, 'colles8', 'colles8short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (9, 'colles9', 'colles9short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (10, 'colles10', 'colles10short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (11, 'colles11', 'colles11short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (12, 'colles12', 'colles12short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (13, 'colles13', 'colles13short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (14, 'colles14', 'colles14short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (15, 'colles15', 'colles15short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (16, 'colles16', 'colles16short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (17, 'colles17', 'colles17short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (18, 'colles18', 'colles18short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (19, 'colles19', 'colles19short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (20, 'colles20', 'colles20short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (21, 'colles21', 'colles21short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (22, 'colles22', 'colles22short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (23, 'colles23', 'colles23short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (24, 'colles24', 'colles24short', '', '', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (25, 'collesm1', 'collesm1short', '1,2,3,4', 'collesmintro', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (26, 'collesm2', 'collesm2short', '5,6,7,8', 'collesmintro', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (27, 'collesm3', 'collesm3short', '9,10,11,12', 'collesmintro', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (28, 'collesm4', 'collesm4short', '13,14,15,16', 'collesmintro', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (29, 'collesm5', 'collesm5short', '17,18,19,20', 'collesmintro', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (30, 'collesm6', 'collesm6short', '21,22,23,24', 'collesmintro', 1, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (31, 'collesm1', 'collesm1short', '1,2,3,4', 'collesmintro', 2, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (32, 'collesm2', 'collesm2short', '5,6,7,8', 'collesmintro', 2, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (33, 'collesm3', 'collesm3short', '9,10,11,12', 'collesmintro', 2, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (34, 'collesm4', 'collesm4short', '13,14,15,16', 'collesmintro', 2, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (35, 'collesm5', 'collesm5short', '17,18,19,20', 'collesmintro', 2, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (36, 'collesm6', 'collesm6short', '21,22,23,24', 'collesmintro', 2, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (37, 'collesm1', 'collesm1short', '1,2,3,4', 'collesmintro', 3, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (38, 'collesm2', 'collesm2short', '5,6,7,8', 'collesmintro', 3, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (39, 'collesm3', 'collesm3short', '9,10,11,12', 'collesmintro', 3, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (40, 'collesm4', 'collesm4short', '13,14,15,16', 'collesmintro', 3, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (41, 'collesm5', 'collesm5short', '17,18,19,20', 'collesmintro', 3, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (42, 'collesm6', 'collesm6short', '21,22,23,24', 'collesmintro', 3, 'scaletimes5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (43, 'howlong', '', '', '', 1, 'howlongoptions');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (44, 'othercomments', '', '', '', 0, '');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (64, 'attls20', 'attls20short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (58, 'attls14', 'attls14short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (59, 'attls15', 'attls15short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (60, 'attls16', 'attls16short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (61, 'attls17', 'attls17short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (62, 'attls18', 'attls18short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (63, 'attls19', 'attls19short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (56, 'attls12', 'attls12short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (57, 'attls13', 'attls13short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (55, 'attls11', 'attls11short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (54, 'attls10', 'attls10short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (53, 'attls9', 'attls9short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (52, 'attls8', 'attls8short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (51, 'attls7', 'attls7short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (50, 'attls6', 'attls6short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (49, 'attls5', 'attls5short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (48, 'attls4', 'attls4short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (47, 'attls3', 'attls3short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (45, 'attls1', 'attls1short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (46, 'attls2', 'attls2short', '', '', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (65, 'attlsm1', 'attlsm1', '45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64', 'attlsmintro', 1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (67, 'attlsm2', 'attlsm2', '63,62,59,57,55,49,52,50,48,47', 'attlsmintro', -1, 'scaleagree5');\r
+INSERT INTO `prefix_survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `type`, `options`) VALUES (68, 'attlsm3', 'attlsm3', '46,54,45,51,60,53,56,58,61,64', 'attlsmintro', -1, 'scaleagree5');\r
 \r
 \r
 \r
@@ -172,8 +172,8 @@ INSERT INTO `survey_questions` (`id`, `text`, `shorttext`, `multi`, `intro`, `ty
 # Dumping data for table `log_display`\r
 #\r
 \r
-INSERT INTO log_display VALUES ('survey', 'download', 'survey', 'name');\r
-INSERT INTO log_display VALUES ('survey', 'view form', 'survey', 'name');\r
-INSERT INTO log_display VALUES ('survey', 'view graph', 'survey', 'name');\r
-INSERT INTO log_display VALUES ('survey', 'view report', 'survey', 'name');\r
-INSERT INTO log_display VALUES ('survey', 'submit', 'survey', 'name');\r
+INSERT INTO prefix_log_display VALUES ('survey', 'download', 'survey', 'name');\r
+INSERT INTO prefix_log_display VALUES ('survey', 'view form', 'survey', 'name');\r
+INSERT INTO prefix_log_display VALUES ('survey', 'view graph', 'survey', 'name');\r
+INSERT INTO prefix_log_display VALUES ('survey', 'view report', 'survey', 'name');\r
+INSERT INTO prefix_log_display VALUES ('survey', 'submit', 'survey', 'name');\r