[system] / trunk / wwmoodle / wwassignment / lib.php Repository:
ViewVC logotype

View of /trunk/wwmoodle/wwassignment/lib.php

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4381 - (download) (as text) (annotate)
Mon Aug 14 19:34:14 2006 UTC (6 years, 9 months ago) by sh002i
File size: 19645 byte(s)
move bridge creation to mod.html -- that way, the bridge is created the
first time someone asks to create a webwork set. this allows us to
provide the create/administer ww course links right away. cleanup,
formatting. the bridge creation is actually done in
_wwassignment_ensureBridgeExists in lib.php.

also, i hate php.

    1 <?php
    2 // $Id: lib.php,v 1.7 2006-08-14 19:34:14 sh002i Exp $
    3 //require_once("DB.php");
    4 function debug_log($obj) {
    5   $fh = fopen("/home/gage/moodle_debug", "w");
    6   //fwrite($fh,  "wwmoodle\n");
    7   $struct = print_r($obj, true);
    8   fwrite($fh, $struct);
    9   fwrite($fh, "\n");
   10   fclose($fh);
   11   //MEG
   12 }
   13 //MEG
   14 $path = ini_get('include_path');
   15 //debug_log($path);
   16 //ini_set('include_path', $path . ':/usr/local/lib/php/pear/DB');
   17 //ini_set('include_path', $path . 'lib/adodb');
   18 //require_once("PEAR.php");
   19 //require_once("DB.php");
   20 //require_once($CFG->libdir.'/adodb/adodb-pear.inc.php');
   21 //endMEG
   22 
   23 
   24 
   25 //MEG  from old wwmoodle/lib.php
   26 /**
   27  * These defines exist simply for easy of referencing them in functions.
   28  */
   29 /**
   30  * The location of the webwork courses directory.
   31  * The user that this script executes as must have write access to this directory.
   32  * This must end in a /!
   33  */
   34 define('WWASSIGNMENT_WEBWORK_COURSES', $CFG->wwassignment_webworkcourses);
   35 /**
   36  * The URL of the WeBWorK install.
   37  */
   38 define('WWASSIGNMENT_WEBWORK_URL', $CFG->wwassignment_webworkurl);
   39 
   40 
   41 
   42 
   43 
   44 
   45 /// Library of functions and constants for module wwassignment
   46 
   47 /**
   48  * The URL of your WeBWorK installation.
   49  */
   50 define('WW_TABLE_PREFIX', 'webwork');
   51 define('WWASSIGNMENT_WEBWORK_URL', $CFG->wwassignment_webwork_url);
   52 /**
   53  * The PEAR::DB connection string to connect to the WeBWorK database.
   54  * This is in the form:
   55  * type://username:password@host/dbname
   56  * Where type is usually either 'mysql', 'mysqli', or 'pgsql'
   57  */
   58 define('WWASSIGNMENT_WEBWORK_DB', $CFG->wwmoodle_webwork_db);
   59 
   60 
   61 function wwassignment_gradeMethods() {
   62 
   63   return array(
   64     0 => array('name' => get_string("gradeSimple", "wwassignment"), 'formula' => '$fGrade += ($p[\'num_correct\'] > 0) ? 1 : 0;'),
   65     1 => array('name' => get_string("gradeDeductRetry", "wwassignment"), 'formula' => '$fGrade += $p[\'num_correct\']/$p[\'attempted\'];'),
   66   );
   67 
   68 }
   69 
   70 /**
   71  * Prints out a select box allowing a teacher to select how WeBWorK grades will be calculated.
   72  * @param int $iGradeMethod The current grade method.
   73  * @return void
   74  */
   75 function wwassignment_printGradeMethodSelect($iGradeMethod='-1') {
   76     // debug_log("printGrademethodSelect called");
   77   $wwassignment_gradeMethods = wwassignment_gradeMethods();
   78   print("<select id='gradingmethod' name='gradingmethod'>\n");
   79   foreach( $wwassignment_gradeMethods as $k=>$g ) {
   80     print("\t<option value='$k'");
   81     if( $k == $iGradeMethod ) {
   82       print(" selected='selected'");
   83     }
   84     print(">$g[name]</option>\n");
   85   }
   86 }
   87 
   88 
   89 
   90 
   91 /**
   92  * Maps a course ID number to it's (sanatized) shortname.
   93  * @param int $iCourseID The ID of the course.
   94  * @return string The shortname of the course, with unsafe characters removed. If the courseID is not found, null is returned.
   95  */
   96 function wwassignment_courseIdToShortName($iCourseId) {
   97   $c = get_record('course', 'id', $iCourseId);
   98   if( ! $c ) {
   99     return null;
  100   }
  101   $shortname = preg_replace("/[^a-zA-Z0-9]/", "", $c->shortname);
  102   return $shortname;
  103 }
  104 
  105 
  106 
  107 function wwassignment_add_instance($wwassignment) {
  108 /// Given an object containing all the necessary data,
  109 /// (defined by the form in mod.html) this function
  110 /// will create a new instance and return the id number
  111 /// of the new instance.
  112   # create set
  113   $aSetInfo = _wwrpc_getSetInfo($wwassignment->set_id, wwassignment_courseIdToShortName($wwassignment->course));
  114 
  115   $wwassignment->timemodified = time();
  116   $wwassignment->id = $wwassignment->instance;
  117   $wwassignment->timedue = $aSetInfo['due_date'];
  118   $wwassignment->timeavailable = $aSetInfo['open_date'];
  119   error_log("add wwassignment record");
  120 //  error_log(print_r($wwassignment, true));
  121   if ($returnid = insert_record("wwassignment", $wwassignment)) {
  122     if ($wwassignment->timedue) {
  123       $event = NULL;
  124       $event->name        = $wwassignment->name;
  125       $event->description = $wwassignment->description;
  126       $event->courseid    = $wwassignment->course;
  127       $event->groupid     = 0;
  128       $event->userid      = 0;
  129       $event->modulename  = 'wwassignment';
  130       $event->instance    = $returnid;
  131       $event->eventtype   = 'due';
  132       $event->timestart   = $wwassignment->timedue;
  133       $event->timeduration = 0;
  134       if (! add_event($event) ){
  135         error_log("wwassignment event not created when adding instance!");
  136       }
  137     }
  138   }
  139 
  140   return $returnid;
  141 }
  142 
  143 
  144 function wwassignment_update_instance($wwassignment) {
  145 /// Given an object containing all the necessary data,
  146 /// (defined by the form in mod.html) this function
  147 /// will update an existing instance with new data.
  148     $aSetInfo = _wwrpc_getSetInfo($wwassignment->set_id, wwassignment_courseIdToShortName($wwassignment->course));
  149 
  150   $wwassignment->timemodified = time();
  151   $wwassignment->id = $wwassignment->instance;
  152   $wwassignment->timedue = $aSetInfo['due_date'];
  153   $wwassignment->timeavailable = $aSetInfo['open_date'];
  154 
  155     error_log("updating wwassignment record");
  156     error_log(print_r($wwassignment, true));
  157   if ($returnid = update_record("wwassignment", $wwassignment)) {
  158     if ($wwassignment->timedue) {
  159       $event = NULL;
  160 
  161       if ($event->id = get_field('event', 'id', 'modulename', 'wwassignment', 'instance', $wwassignment->id)) {
  162 
  163         $event->name        = $wwassignment->name;
  164         $event->description = $wwassignment->description;
  165         $event->timestart   = $wwassignment->timedue;
  166 
  167         $rs = update_event($event) ;
  168 
  169         error_log("updating the event".$rs);
  170         error_log(print_r($event,true));
  171 
  172       } else {
  173         $event = NULL;
  174         $event->name        = $wwassignment->name;
  175         $event->description = $wwassignment->description;
  176         $event->courseid    = $wwassignment->course;
  177         $event->groupid     = 0;
  178         $event->userid      = 0;
  179         $event->modulename  = 'wwassignment';
  180         $event->instance    = $wwassignment->id;
  181         $event->eventtype   = 'due';
  182         $event->timestart   = $wwassignment->timedue;
  183         $event->timeduration = 0;
  184         add_event($event);
  185       }
  186     } else {
  187       delete_records('event', 'modulename', 'wwassignment', 'instance', $wwassignment->id);
  188     }
  189     return $returnid;
  190   }
  191 
  192 }
  193 function wwassignment_delete_instance($id) {
  194 /// Given an ID of an instance of this module,
  195 /// this function will permanently delete the instance
  196 /// and any data that depends on it.
  197     $result = true;
  198   if (! $wwassignment = get_record("wwassignment", "id", "$id")) {
  199     return false;
  200   }
  201 
  202   # Delete any dependent records here #
  203 
  204   if (! delete_records("wwassignment", "id", $wwassignment->id)) {
  205     $result = false;
  206   }
  207 
  208   if (! delete_records('event', 'modulename', 'wwassignment', 'instance', $wwassignment->id)) {
  209     $result = false;
  210   }
  211 
  212   // Get the cm id to properly clean up the grade_items for this assignment
  213   // bug 4976
  214   if (! $cm = get_record('modules', 'name', 'wwassignment')) {
  215     $result = false;
  216   } else {
  217     if (! delete_records('grade_item', 'modid', $cm->id, 'cminstance', $wwassignment->id)) {
  218       $result = false;
  219     }
  220   }
  221 
  222   return $result;
  223 }
  224 
  225 function wwassignment_user_outline($course, $user, $mod, $wwassignment) {
  226 /// Return a small object with summary information about what a
  227 /// user has done with a given particular instance of this module
  228 /// Used for user activity reports.
  229 /// $return->time = the time they did it
  230 /// $return->info = a short text description
  231   $aLogs = get_logs("l.userid=$user AND l.course=$course AND l.cmid={$wwassignment->id}");
  232   if( count($aLogs) > 0 ) {
  233     $return->time = $aLogs[0]->time;
  234     $return->info = $aLogs[0]->info;
  235   }
  236   return $return;
  237 }
  238 
  239 function wwassignment_user_complete($course, $user, $mod, $wwassignment) {
  240 /// Print a detailed representation of what a  user has done with
  241 /// a given particular instance of this module, for user activity reports.
  242 
  243   return true;
  244 }
  245 
  246 function wwassignment_print_recent_activity($course, $isteacher, $timestart) {
  247 /// Given a course and a time, this module should find recent activity
  248 /// that has occurred in wwassignment activities and print it out.
  249 /// Return true if there was output, or false is there was none.
  250 
  251     global $CFG;
  252 
  253     return false;  //  True if anything was printed, otherwise false
  254 }
  255 
  256 function wwassignment_cron () {
  257 /// Function to be run periodically according to the moodle cron
  258 /// This function searches for things that need to be done, such
  259 /// as sending out mail, toggling flags etc ...
  260 
  261     global $CFG;
  262 
  263     return true;
  264 }
  265 
  266 function wwassignment_grades($wwassignmentid) {
  267 /// Must return an array of grades for a given instance of this module,
  268 /// indexed by user.  It also returns a maximum allowed grade.
  269 ///
  270 ///    $return->grades = array of grades;
  271 ///    $return->maxgrade = maximum allowed grade;
  272 ///
  273 ///    return $return;
  274   // here's how we compute the grade:
  275   // NOTE: each set has P problems in it.
  276   // NOTE: each problem may be attempted M times.
  277   // NOTE: each problem has been attempted A times (by a given user).
  278   // NOTE: each problem was gotten correct C times (by a given user).
  279   // NOTE: each problem was gotten incorrect I times (by a given user).
  280   // Thus, a users grade is: sigma(over P) C/A
  281   // And the max score is P
  282   // Alternately, code is provided for:
  283   // sigma(over P) { if( C > 0) 1 else 0 }
  284   // again with a max of P
  285 
  286   // redefine it here, 'cause for some reason we can't global it...
  287     //debug_log("start grades ".$wwassignmentid);
  288   $wwassignment_gradeMethods = wwassignment_gradeMethods();
  289 
  290   $oGrades->grades = array();
  291   $aGrades->maxgrade = 0;
  292 
  293   $oMod = get_record("wwassignment", "id", $wwassignmentid);
  294   if( ! $oMod ) {
  295     return NULL;
  296   }
  297   //debug_log("record ".print_r($oMod,true));
  298   $gradeFormula = $wwassignment_gradeMethods[$oMod->gradingmethod]['formula'];
  299   //debug_log("formula ".print_r($gradeFormula, true));
  300   if( empty($gradeFormula) ) {
  301     return NULL;
  302   }
  303 
  304   $sCourseName = wwassignment_courseIdToShortName($oMod->course);
  305 
  306   // enumerate over the students in the course:
  307   $aStudents = get_course_students($oMod->course);
  308   foreach( $aStudents as $s ) {
  309     $aProblems = _wwrpc_getProblemsForUser($s->username, $oMod->set_id, $sCourseName);
  310     $fGrade = 0.0;
  311     foreach( $aProblems as $p ) {
  312         //debug_log("student".$s->username." set ".$oMod->set_id." score ". $p['num_correct']);
  313       eval($gradeFormula);
  314     }
  315     $oGrades->grades[$s->id] = $fGrade;
  316   }
  317   $oGrades->maxgrade = _wwrpc_getMaxSetGrade($oMod->set_id, $sCourseName);
  318   debug_log("all grades".print_r($oGrades, true));
  319   return $oGrades;
  320 }
  321 
  322 function wwassignment_get_participants($wwassignmentid) {
  323 //Must return an array of user records (all data) who are participants
  324 //for a given instance of wwassignment. Must include every user involved
  325 //in the instance, independient of his role (student, teacher, admin...)
  326 //See other modules as example.
  327   $oMod = get_record("wwassignment", "id", $wwassignmentid);
  328   if( ! $oMod ) {
  329     return array();
  330   }
  331   return get_course_users($oMod->course);
  332 }
  333 
  334 function wwassignment_scale_used ($wwassignmentid,$scaleid) {
  335 //This function returns if a scale is being used by one wwassignment
  336 //it it has support for grading and scales. Commented code should be
  337 //modified if necessary. See forum, glossary or journal modules
  338 //as reference.
  339 
  340   $return = false;
  341 
  342   $rec = get_record("wwassignment","id","$wwassignmentid","scale","-$scaleid");
  343 
  344   if (!empty($rec)  && !empty($scaleid)) {
  345     $return = true;
  346   }
  347   return $return;
  348 }
  349 function wwassignment_refresh_events($courseid = 0) {
  350     error_log("wwassignment_refresh_events called");
  351     if ($courseid == 0) {
  352         if (! $wwassignment = get_records("wwassignment")) {
  353             return true;
  354         }
  355     } else {
  356         if (! $wwassignment = get_records("wwassignment", "course", $courseid)) {
  357             return true;
  358         }
  359     }
  360     $moduleid = get_field('modules', 'id', 'name', 'wwassignment');
  361 
  362     foreach ($wwassignment as $wwassignment) {
  363         $event = NULL;
  364         $event->name        = addslashes($wwassignment->name);
  365         $event->description = addslashes($wwassignment->description);
  366         $event->timestart   = $wwassignment->timedue;
  367 
  368         if ($event->id = get_field('event', 'id', 'modulename', 'wwassignment', 'instance', $wwassignment->id)) {
  369             update_event($event);
  370 
  371         } else {
  372             $event->courseid    = $wwassignment->course;
  373             $event->groupid     = 0;
  374             $event->userid      = 0;
  375             $event->modulename  = 'wwassignment';
  376             $event->instance    = $wwassignment->id;
  377             $event->eventtype   = 'due';
  378             $event->timeduration = 0;
  379             $event->visible     = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $wwassignment->id);
  380             add_event($event);
  381         }
  382 
  383     }
  384     return true;
  385 }
  386 
  387 
  388 ////////////////////////////////////////////////////////////////////////////////////
  389 // calls to WeBWorK database start with _wwrpc_
  390 ///////////////////////////////////////////////////////////////////////////////////
  391 
  392 /**
  393  * Gets information about the specified set.
  394  * @param int $iSetId The id of the set.
  395  * @param $sCourseName The name of this course
  396  * @return array Information about the set.
  397  */
  398 function _wwrpc_getSetInfo($iSetId, $sCourseName) {
  399   global $db, $CFG;
  400   $qry = "SELECT * FROM ". WW_TABLE_PREFIX.".{$sCourseName}_set WHERE set_id=?";
  401     //error_log("get info for set $iSetID and $sCourseName");
  402   if (!$res = $db->query($qry, array($iSetId))) {
  403         if (isset($CFG->debug) and $CFG->debug > 7) {
  404             notify($db->ErrorMsg() .'<br /><br />'. $sql);
  405         }
  406         if (!empty($CFG->dblogerror)) {
  407             $debug=array_shift(debug_backtrace());
  408             error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT:  $sql");
  409         }
  410         return false;
  411     }
  412   $row = $res->fetchRow();
  413   if( ! $row ) {
  414     return array('set_id' => $iSetId, 'set_header' => "Unable to get information for this set.", 'hardcopy_header' => "Unable to get information for this set.", 'open_date'=>time(), 'due_date'=>time(), 'answer_date'=>time(), 'published'=>time());
  415   }
  416   $res->free();
  417   //error_log("result from getSetInfo");
  418   return $row;
  419 }
  420 
  421 /**
  422  * Gets the max grade for a given problem set.
  423  * Essentially, this is just the number of problems in the set.
  424  * @param int $iSetId The id of the set.
  425  * @param string $sCourseName The name of this course.
  426  * @return int
  427  */
  428 function _wwrpc_getMaxSetGrade($iSetId, $sCourseName) {
  429   global $db, $CFG;
  430 
  431 
  432   $qry = "SELECT COUNT(*) FROM ". WW_TABLE_PREFIX.".{$sCourseName}_problem WHERE set_id=?";
  433   if (!$res = $db->query($qry, array($iSetId))) {
  434         if (isset($CFG->debug) and $CFG->debug > 7) {
  435             notify($db->ErrorMsg() .'<br /><br />'. $sql);
  436         }
  437         if (!empty($CFG->dblogerror)) {
  438             $debug=array_shift(debug_backtrace());
  439             error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT:  $sql");
  440         }
  441         return false;
  442     }
  443   $row = $res->fetchRow();
  444   $res->free();
  445   return $row ? $row['COUNT(*)'] : -1;
  446 }
  447 
  448 /**
  449  * Gets the results of all the problems in the given set for the given user.
  450  * @param string $sUserName The name of the user to check for.
  451  * @param int $iSetId The id of the set to check for.
  452  * @param string $sCourseName The name of this course.
  453  * @return array An array of the results of all the problems for this user.
  454  */
  455 function _wwrpc_getProblemsForUser($sUserName, $iSetId, $sCourseName) {
  456   // debug_log("start getProblemsForUser");
  457     global $db, $CFG;
  458   $qry = "SELECT * FROM ". WW_TABLE_PREFIX.".{$sCourseName}_problem_user WHERE user_id=? AND set_id=? ORDER BY problem_id";
  459   if (!$res = $db->query($qry, array($sUserName, $iSetId))) {
  460         if (isset($CFG->debug) and $CFG->debug > 7) {
  461             notify($db->ErrorMsg() .'<br /><br />'. $sql);
  462         }
  463         if (!empty($CFG->dblogerror)) {
  464             $debug=array_shift(debug_backtrace());
  465             error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT:  $sql");
  466         }
  467         return false;
  468     }
  469   $row = $res->getArray();
  470   !$row ? $row = array() : $row = $row;
  471 
  472   //debug_log("row for $sUserName $iSetID");
  473   //debug_log(print_r($row,true));
  474 
  475   $res->free();
  476   return $row;
  477 }
  478 
  479 ////////////////////////////////////////////////////////////////////////////////////
  480 // internal functions start with _wwassignment
  481 ///////////////////////////////////////////////////////////////////////////////////
  482 
  483 /**
  484  * Prints an HTML select widget allowing for selection of any of the sets defined
  485  * for this course in WeBWorK.
  486  * @pre There is a WeBWorK course for this course.
  487  * @param int $iCourseId The id of this course.
  488  * @param int $iSetId The set id to have selected.
  489  * @return void
  490  */
  491 function _wwassignment_printSetSelect($iCourseId, $iSetId=-1) {
  492   global $db, $CFG;
  493   // debug_log("starting printSetSelect");
  494   $sCourseName = wwassignment_courseIdToShortName($iCourseId);
  495   if( is_null($sCourseName) ) {
  496     print("<b>Unable to find the name of this course.</b>\n");
  497     return;
  498   }
  499 
  500   // now get a list of all sets for this course:
  501   $qry = "SELECT * FROM ". WW_TABLE_PREFIX.".{$sCourseName}_set ORDER BY open_date DESC";
  502   if (!$res = $db->query($qry)) {
  503         if (isset($CFG->debug) and $CFG->debug > 7) {
  504             notify($db->ErrorMsg() .'<br /><br />'. $sql);
  505         }
  506         if (!empty($CFG->dblogerror)) {
  507             $debug=array_shift(debug_backtrace());
  508             error_log("SQL ".$db->ErrorMsg()." in {$debug['file']} on line {$debug['line']}. STATEMENT:  $sql");
  509         }
  510         return false;
  511     }
  512   $aSets = array();
  513   // debug_log("got sets");
  514   while( $row = $res->fetchRow() ) {
  515     $aSets[] = $row['set_id'];
  516   }
  517   $res->free();
  518 
  519 
  520   // now print the option box, if we have any to print:
  521   if( count($aSets) < 1 ) {
  522     print("<b>No sets exist for this course. Please create one via <a href='" . WWASSIGNMENT_WEBWORK_URL . "/$sCourseName'>WeBWorK</a>.</b>\n");
  523     return;
  524   }
  525   print("<select id='set_id' name='set_id'>\n");
  526   foreach( $aSets as $s ) {
  527     print("<option value='");
  528     p($s);
  529     print("'");
  530     if( $s == $iSetId ) {
  531       print("selected='selected'");
  532     }
  533     print(">$s</option>\n");
  534   }
  535   print("</select>\n");
  536 }
  537 
  538 /**
  539  * Maps a course ID number to it's (sanatized) shortname.
  540  * @param int $iCourseID The ID of the course.
  541  * @return string The shortname of the course, with unsafe characters removed. If the courseID is not found, null is returned.
  542  */
  543 function _wwassignment_courseIdToShortName($iCourseId) {
  544   $c = get_record('course', 'id', $iCourseId);
  545   if( ! $c ) {
  546     return null;
  547   }
  548   $shortname = preg_replace("/[^a-zA-Z0-9]/", "", $c->shortname);
  549   return $shortname;
  550 }
  551 
  552 /**
  553  * Returns a URL to the specified set.
  554  * @param int $iSetId The set ID to link to.
  555  * @param string $sCourseName The name of this course.
  556  * @return string The URL to the specified set. This might be absolute, or relative. However, it is assured of working.
  557  */
  558 function _wwassignment_linkToSet($iSetId, $sCourseName) {
  559   // TODO: Verify me.
  560   return WWASSIGNMENT_WEBWORK_URL."/$sCourseName/$iSetId";
  561 }
  562 
  563 /**
  564  * Checks for a wwassignment_bridge record for the given course, creates one if it does not exist.
  565  * @param int $iCourseID The ID of the course.
  566  * @return void
  567  */
  568 function _wwassignment_ensureBridgeExists($iCourseID) {
  569   $wwassignment_bridge = get_record("wwassignment_bridge", "course", $iCourseID);
  570   if (!$wwassignment_bridge) {
  571     $wwassignment_bridge->timemodified = time();
  572     $wwassignment_bridge->course = $iCourseID;
  573     $wwassignment_bridge->coursename = _wwassignment_courseIdToShortName($iCourseID);
  574     $wwassignment_bridge->name = $wwassignment_bridge->coursename;
  575     if (!isset($wwassignment_bridge->coursename)) {
  576       $wwassignment_bridge->coursename = "foo";
  577     }
  578     $returnid = insert_record("wwassignment_bridge",$wwassignment_bridge);
  579     error_log("inserting new entry to wwassignment_bridge id=$returnid");
  580   }
  581 }
  582 
  583 ?>

aubreyja at gmail dot com
ViewVC Help
Powered by ViewVC 1.0.9