From f8897ab43dc5aaabe3cfb709853b27192dbcb0d1 Mon Sep 17 00:00:00 2001 From: Vasilis Daloukas Date: Thu, 24 Dec 2015 11:22:47 +0200 Subject: [PATCH] Fix:Coding style --- lib.php | 752 ++++++++--------- locallib.php | 2270 +++++++++++++++++++++++++------------------------- 2 files changed, 1450 insertions(+), 1572 deletions(-) diff --git a/lib.php b/lib.php index ce8db7d..85650f8 100755 --- a/lib.php +++ b/lib.php @@ -1,4 +1,19 @@ -. + /** * Library of functions and constants for module game * @@ -8,9 +23,9 @@ **/ -/// CONSTANTS /////////////////////////////////////////////////////////////////// +// Define CONSTANTS. -/**#@+ +/* * Options determining how the grades from individual attempts are combined to give * the overall grade for a user */ @@ -18,36 +33,24 @@ define('GAME_GRADEHIGHEST', 1); define('GAME_GRADEAVERAGE', 2); define('GAME_ATTEMPTFIRST', 3); define('GAME_ATTEMPTLAST', 4); -/**#@-*/ -/**#@+ - * The different review options are stored in the bits of $game->review - * These constants help to extract the options - */ -/** - * The first 6 bits refer to the time immediately after the attempt - */ -define('GAME_REVIEW_IMMEDIATELY', 0x3f); -/** - * the next 6 bits refer to the time after the attempt but while the game is open - */ -define('GAME_REVIEW_OPEN', 0xfc0); -/** - * the final 6 bits refer to the time after the game closes - */ -define('GAME_REVIEW_CLOSED', 0x3f000); - -// within each group of 6 bits we determine what should be shown -define('GAME_REVIEW_RESPONSES', 1*0x1041); // Show responses -define('GAME_REVIEW_SCORES', 2*0x1041); // Show scores -define('GAME_REVIEW_FEEDBACK', 4*0x1041); // Show feedback -define('GAME_REVIEW_ANSWERS', 8*0x1041); // Show correct answers -// Some handling of worked solutions is already in the code but not yet fully supported -// and not switched on in the user interface. -define('GAME_REVIEW_SOLUTIONS', 16*0x1041); // Show solutions -define('GAME_REVIEW_GENERALFEEDBACK', 32*0x1041); // Show general feedback -/**#@-*/ +// The different review options are stored in the bits of $game->review. +// These constants help to extract the options. +define('GAME_REVIEW_IMMEDIATELY', 0x3f); // The first 6 bits refer to the time immediately after the attempt. +define('GAME_REVIEW_OPEN', 0xfc0); // The next 6 bits refer to the time after the attempt but while the game is open. +define('GAME_REVIEW_CLOSED', 0x3f000); // The final 6 bits refer to the time after the game closes. + +// Within each group of 6 bits we determine what should be shown. +define('GAME_REVIEW_RESPONSES', 1 * 0x1041); // Show responses. +define('GAME_REVIEW_SCORES', 2 * 0x1041); // Show scores. +define('GAME_REVIEW_FEEDBACK', 4 * 0x1041); // Show feedback. +define('GAME_REVIEW_ANSWERS', 8 * 0x1041); // Show correct answers. + +// Some handling of worked solutions is already in the code but not yet fully supported. +// and not switched on in the user interface. +define('GAME_REVIEW_SOLUTIONS', 16 * 0x1041); // Show solutions. +define('GAME_REVIEW_GENERALFEEDBACK', 32 * 0x1041); // Show general feedback. /** * Given an object containing all the necessary data, @@ -64,16 +67,16 @@ function game_add_instance($game) { $game->timemodified = time(); game_before_add_or_update( $game); - - # May have to add extra stuff in here # - + + // May have to add extra stuff in here. + $id = $DB->insert_record("game", $game); - + $game = $DB->get_record_select( 'game', "id=$id"); - + // Do the processing required after an add or an update. game_grade_item_update( $game); - + return $id; } @@ -91,86 +94,83 @@ function game_update_instance($game) { $game->timemodified = time(); $game->id = $game->instance; - if( !isset( $game->glossarycategoryid)){ + if (!isset( $game->glossarycategoryid)) { $game->glossarycategoryid = 0; } - - if( !isset( $game->glossarycategoryid2)){ + + if (!isset( $game->glossarycategoryid2)) { $game->glossarycategoryid2 = 0; } - - if( $game->grade == ''){ + + if ($game->grade == '') { $game->grade = 0; } - if( !isset( $game->param1)){ + if (!isset( $game->param1)) { $game->param1 = 0; } - if( $game->param1 == ''){ + if ($game->param1 == '') { $game->param1 = 0; } - if( !isset( $game->param2)){ + if (!isset( $game->param2)) { $game->param2 = 0; } - if( $game->param2 == ''){ + if ($game->param2 == '') { $game->param2 = 0; } - - if( !isset( $game->questioncategoryid)){ + + if (!isset( $game->questioncategoryid)) { $game->questioncategoryid = 0; - } - + } + game_before_add_or_update( $game); - - if( !$DB->update_record("game", $game)){ + + if (!$DB->update_record("game", $game)) { return false; } - + // Do the processing required after an add or an update. game_grade_item_update( $game); - - return true; + + return true; } function game_before_add_or_update(&$game) { - if( isset( $game->questioncategoryid)) - { + if (isset( $game->questioncategoryid)) { $pos = strpos( $game->questioncategoryid, ','); - if( $pos != false) + if ($pos != false) { $game->questioncategoryid = substr( $game->questioncategoryid, 0, $pos); + } } - - if( $game->gamekind == 'millionaire') - { + + if ($game->gamekind == 'millionaire') { $pos = strpos( '-'.$game->param8, '#'); - if( $pos > 0) - { + if ($pos > 0) { $game->param8 = hexdec(substr( $game->param8, $pos)); } - }else if( $game->gamekind == 'snakes') - { + } else if ($game->gamekind == 'snakes') { $s = ''; - if( $game->param3 == 0) - { - //means user defined + if ($game->param3 == 0) { + // Means user defined. $draftitemid = $game->param4; - if( isset( $game->id)) - { + if (isset( $game->id)) { $cmg = get_coursemodule_from_instance('game', $game->id, $game->course); $modcontext = get_context_instance(CONTEXT_MODULE, $cmg->id); - $attachmentoptions=array('subdirs' => 0, 'maxbytes' => 9999999, 'maxfiles' => 1); - file_save_draft_area_files($draftitemid, $modcontext->id, 'mod_game', 'snakes_file', $game->id, array('subdirs' => 0, 'maxbytes' => 9999999, 'maxfiles' => 1)); - $game->param5 = 1; + $attachmentoptions = array('subdirs' => 0, 'maxbytes' => 9999999, 'maxfiles' => 1); + file_save_draft_area_files($draftitemid, $modcontext->id, 'mod_game', 'snakes_file', $game->id, + array('subdirs' => 0, 'maxbytes' => 9999999, 'maxfiles' => 1)); + $game->param5 = 1; } - - if( isset( $_POST[ 'snakes_cols'])) - { - $fields = array( 'snakes_data', 'snakes_cols', 'snakes_rows', 'snakes_headerx', 'snakes_headery', 'snakes_footerx', 'snakes_footery', 'snakes_width', 'snakes_height'); - foreach( $fields as $f) + + if (isset( $_POST[ 'snakes_cols'])) { + $fields = array( 'snakes_data', 'snakes_cols', 'snakes_rows', 'snakes_headerx', 'snakes_headery', + 'snakes_footerx', 'snakes_footery', 'snakes_width', 'snakes_height'); + foreach ($fields as $f) { $s .= '#'.$f.':'.$_POST[ $f]; + } $s = substr( $s, 1); } } @@ -189,52 +189,51 @@ function game_before_add_or_update(&$game) { function game_delete_instance($gameid) { global $DB; - # Delete any dependent records here # - + // Delete any dependent records here. $aids = array(); - if( ($recs = $DB->get_records( 'game_attempts', array( 'gameid' => $gameid))) != false) - { + if (($recs = $DB->get_records( 'game_attempts', array( 'gameid' => $gameid))) != false) { $ids = ''; - $count = 0; - foreach( $recs as $rec) - { - $ids .= ( $ids == '' ? $rec->id : ','.$rec->id); - if( ++$count > 10) - { - $aids[] = $ids; - $count = 0; - $ids = ''; - } - } - if( $ids != '') - $aids[] = $ids; - } - - foreach( $aids as $ids) - { - $tables = array( 'game_hangman', 'game_cross', 'game_cryptex', 'game_millionaire', 'game_bookquiz', 'game_sudoku', 'game_snakes'); - foreach( $tables as $t) - { - $sql = "DELETE FROM {".$t."} WHERE id IN (".$ids.')'; - if (! $DB->execute( $sql)) - return false; - } - } - + + $count = 0; + foreach ($recs as $rec) { + $ids .= ( $ids == '' ? $rec->id : ','.$rec->id); + if (++$count > 10) { + $aids[] = $ids; + $count = 0; + $ids = ''; + } + } + if ($ids != '') { + $aids[] = $ids; + } + } + + foreach ($aids as $ids) { + $tables = array( 'game_hangman', 'game_cross', 'game_cryptex', 'game_millionaire', + 'game_bookquiz', 'game_sudoku', 'game_snakes'); + + foreach ($tables as $t) { + $sql = "DELETE FROM {".$t."} WHERE id IN (".$ids.')'; + if (!$DB->execute( $sql)) { + return false; + } + } + } + $tables = array( 'game_attempts', 'game_grades', 'game_bookquiz_questions', 'game_queries', 'game_repetitions'); - foreach( $tables as $t) - { - if (! $DB->delete_records( $t, array( 'gameid' => $gameid))) + foreach ($tables as $t) { + if (!$DB->delete_records( $t, array( 'gameid' => $gameid))) { return false; - } + } + } $tables = array( 'game_export_javame', 'game_export_html', 'game'); - foreach( $tables as $table) - { - if (!$DB->delete_records( $table, array( 'id' => $gameid))) + foreach ($tables as $table) { + if (!$DB->delete_records( $table, array( 'id' => $gameid))) { return false; + } } - + return true; } @@ -258,7 +257,8 @@ function game_user_outline($course, $user, $mod, $game) { $result->time = $grade->timemodified; return $result; } - return NULL; + + return null; } /** @@ -282,7 +282,7 @@ function game_user_complete($course, $user, $mod, $game) { echo ' - '.userdate($attempt->timelastattempt).'
'; } } else { - print_string('noattempts', 'game'); + print_string('noattempts', 'game'); } return true; @@ -300,7 +300,7 @@ function game_user_complete($course, $user, $mod, $game) { function game_print_recent_activity($course, $isteacher, $timestart) { global $CFG; - return false; // True if anything was printed, otherwise false + return false; // True if anything was printed, otherwise false. } /** @@ -312,7 +312,7 @@ function game_print_recent_activity($course, $isteacher, $timestart) { * @return boolean * @todo Finish documenting this function **/ -function game_cron () { +function game_cron() { global $CFG; return true; @@ -332,13 +332,13 @@ function game_cron () { * @return mixed Null or object with an array of grades and with the maximum grade **/ function game_grades($gameid) { -/// Must return an array of grades, indexed by user, and a max grade. + // Must return an array of grades, indexed by user, and a max grade. global $DB; $game = $DB->get_record( 'game', array( 'id' => intval($gameid))); if (empty($game) || empty($game->grade)) { - return NULL; + return null; } $return = new stdClass; @@ -360,11 +360,13 @@ function game_get_user_grades($game, $userid=0) { $user = $userid ? "AND u.id = $userid" : ""; - $sql = 'SELECT u.id, u.id AS userid, '.$game->grade.' * g.score AS rawgrade, g.timemodified AS dategraded, MAX(a.timefinish) AS datesubmitted + $sql = 'SELECT u.id, u.id AS userid, '.$game->grade. + ' * g.score AS rawgrade, g.timemodified AS dategraded, MAX(a.timefinish) AS datesubmitted FROM {user} u, {game_grades} g, {game_attempts} a WHERE u.id = g.userid AND g.gameid = '.$game->id.' AND a.gameid = g.gameid AND u.id = a.userid'; - if( $userid != 0) + if ($userid != 0) { $sql .= ' AND u.id='.$userid; + } $sql .= ' GROUP BY u.id, g.score, g.timemodified'; return $DB->get_records_sql( $sql); @@ -380,7 +382,7 @@ function game_get_user_grades($game, $userid=0) { * @return mixed boolean/array of students **/ function game_get_participants($gameid) { - return false; //todo + return false; } /** @@ -393,15 +395,9 @@ function game_get_participants($gameid) { * @return mixed * @todo Finish documenting this function **/ -function game_scale_used ($gameid,$scaleid) { +function game_scale_used ($gameid, $scaleid) { $return = false; - //$rec = get_record("game","id","$gameid","scale","-$scaleid"); - // - //if (!empty($rec) && !empty($scaleid)) { - // $return = true; - //} - return $return; } @@ -413,10 +409,11 @@ function game_scale_used ($gameid,$scaleid) { */ function game_update_grades($game=null, $userid=0, $nullifnone=true) { global $CFG; - if (!function_exists('grade_update')) { //workaround for buggy PHP versions - if( file_exists( $CFG->libdir.'/gradelib.php')){ + + if (!function_exists('grade_update')) { // Workaround for buggy PHP versions. + if (file_exists( $CFG->libdir.'/gradelib.php')) { require_once($CFG->libdir.'/gradelib.php'); - }else{ + } else { return; } } @@ -428,7 +425,7 @@ function game_update_grades($game=null, $userid=0, $nullifnone=true) { } else if ($userid and $nullifnone) { $grade = new object(); $grade->userid = $userid; - $grade->rawgrade = NULL; + $grade->rawgrade = null; game_grade_item_update( $game, $grade); } else { @@ -459,20 +456,21 @@ function game_update_grades($game=null, $userid=0, $nullifnone=true) { * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook * @return int 0 if ok, error code otherwise */ -function game_grade_item_update($game, $grades=NULL) { +function game_grade_item_update($game, $grades=null) { global $CFG; - if (!function_exists('grade_update')) { //workaround for buggy PHP versions - if( file_exists( $CFG->libdir.'/gradelib.php')){ + + if (!function_exists('grade_update')) { // Workaround for buggy PHP versions. + if (file_exists( $CFG->libdir.'/gradelib.php')) { require_once($CFG->libdir.'/gradelib.php'); - }else{ + } else { return; } } - if (array_key_exists('cmidnumber', $game)) { //it may not be always present - $params = array('itemname'=>$game->name, 'idnumber'=>$game->cmidnumber); + if (array_key_exists('cmidnumber', $game)) { // Tt may not be always present. + $params = array('itemname' => $game->name, 'idnumber' => $game->cmidnumber); } else { - $params = array('itemname'=>$game->name); + $params = array('itemname' => $game->name); } if ($game->grade > 0) { @@ -484,10 +482,9 @@ function game_grade_item_update($game, $grades=NULL) { $params['gradetype'] = GRADE_TYPE_NONE; } - - if ($grades === 'reset') { + if ($grades === 'reset') { $params['reset'] = true; - $grades = NULL; + $grades = null; } return grade_update('mod/game', $game->course, 'mod', 'game', $game->id, 0, $grades, $params); @@ -502,20 +499,20 @@ function game_grade_item_update($game, $grades=NULL) { */ function game_grade_item_delete( $game) { global $CFG; - - if( file_exists( $CFG->libdir.'/gradelib.php')){ + + if (file_exists( $CFG->libdir.'/gradelib.php')) { require_once($CFG->libdir.'/gradelib.php'); - }else{ + } else { return; - } + } - return grade_update('mod/game', $game->course, 'mod', 'game', $game->id, 0, NULL, array('deleted'=>1)); + return grade_update('mod/game', $game->course, 'mod', 'game', $game->id, 0, null, array('deleted' => 1)); } /** * Returns all game graded users since a given time for specified game */ -function game_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) { +function game_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) { global $DB, $COURSE, $USER; if ($COURSE->id == $courseid) { @@ -541,9 +538,9 @@ function game_get_recent_mod_activity(&$activities, &$index, $timestart, $course $groupselect = ""; $groupjoin = ""; } - + if (!$attempts = $DB->get_records_sql("SELECT qa.*, q.grade, - u.firstname, u.lastname, u.email, u.picture + u.firstname, u.lastname, u.email, u.picture FROM {game_attempts} qa JOIN {game} q ON q.id = qa.gameid JOIN {user} u ON u.id = qa.userid @@ -554,28 +551,26 @@ function game_get_recent_mod_activity(&$activities, &$index, $timestart, $course return; } - - $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id); - $grader = has_capability('moodle/grade:viewall', $cm_context); - $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context); - $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context); - $grader = has_capability('mod/game:grade', $cm_context); - //$grader = isteacher( $courseid, $userid); + $cmcontext = get_context_instance(CONTEXT_MODULE, $cm->id); + $grader = has_capability('moodle/grade:viewall', $cmcontext); + $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext); + $viewfullnames = has_capability('moodle/site:viewfullnames', $cmcontext); + $grader = has_capability('mod/game:grade', $cmcontext); $groupmode = groups_get_activity_groupmode($cm, $course); if (is_null($modinfo->groups)) { - $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo + $modinfo->groups = groups_get_user_groups($course->id); // Load all my groups and cache it in modinfo. } - $aname = format_string($cm->name,true); + $aname = format_string($cm->name, true); foreach ($attempts as $attempt) { if ($attempt->userid != $USER->id) { if (!$grader) { - // grade permission required + // Grade permission required. continue; } - if ($groupmode == SEPARATEGROUPS and !$accessallgroups) { + if ($groupmode == SEPARATEGROUPS and !$accessallgroups) { $usersgroups = groups_get_all_groups($course->id, $attempt->userid, $cm->groupingid); if (!is_array($usersgroups)) { continue; @@ -586,29 +581,27 @@ function game_get_recent_mod_activity(&$activities, &$index, $timestart, $course continue; } } - } + } $tmpactivity = new object(); $tmpactivity->type = 'game'; $tmpactivity->cmid = $cm->id; $tmpactivity->name = $aname; - $tmpactivity->sectionnum= $cm->sectionnum; + $tmpactivity->sectionnum = $cm->sectionnum; $tmpactivity->timestamp = $attempt->timefinish; - + $tmpactivity->content->attemptid = $attempt->id; $tmpactivity->content->sumgrades = $attempt->score * $attempt->grade; $tmpactivity->content->maxgrade = $attempt->grade; $tmpactivity->content->attempt = $attempt->attempt; - + $tmpactivity->user->userid = $attempt->userid; $tmpactivity->user->fullname = fullname($attempt, $viewfullnames); $tmpactivity->user->picture = $attempt->picture; - + $activities[$index++] = $tmpactivity; } - - return; } function game_print_recent_mod_activity($activity, $courseid, $detail, $modnames) { @@ -641,8 +634,6 @@ function game_print_recent_mod_activity($activity, $courseid, $detail, $modnames echo ''; echo ""; - - return; } @@ -671,21 +662,31 @@ function game_reset_gradebook($courseid, $type='') { */ function game_supports($feature) { switch($feature) { + case FEATURE_GRADE_HAS_GRADE: + return true; + case FEATURE_GROUPS: + return true; + case FEATURE_GROUPINGS: + return true; + case FEATURE_GROUPMEMBERSONLY: + return true; + case FEATURE_MOD_INTRO: + return false; + case FEATURE_COMPLETION_TRACKS_VIEWS: + return true; + case FEATURE_COMPLETION_HAS_RULES: + return true; + case FEATURE_GRADE_HAS_GRADE: + return true; + case FEATURE_GRADE_OUTCOMES: + return true; + case FEATURE_RATE: + return false; + case FEATURE_BACKUP_MOODLE2: + return true; - case FEATURE_GRADE_HAS_GRADE: return true; - - case FEATURE_GROUPS: return true; - case FEATURE_GROUPINGS: return true; - case FEATURE_GROUPMEMBERSONLY: return true; - case FEATURE_MOD_INTRO: return false; - case FEATURE_COMPLETION_TRACKS_VIEWS: return true; - case FEATURE_COMPLETION_HAS_RULES: return true; - case FEATURE_GRADE_HAS_GRADE: return true; - case FEATURE_GRADE_OUTCOMES: return true; - case FEATURE_RATE: return false; - case FEATURE_BACKUP_MOODLE2: return true; - - default: return null; + default: + return null; } } @@ -702,6 +703,7 @@ function game_get_extra_capabilities() { $reportcaps = $DB->get_records_select_menu('capabilities', 'name LIKE ?', array('quizreport/%'), 'id,name'); $caps = array_merge($caps, $reportcaps); $caps[] = 'moodle/site:accessallgroups'; + return $caps; } @@ -723,7 +725,8 @@ function game_get_extra_capabilities() { function game_num_attempt_summary($game, $cm, $returnzero = false, $currentgroup = 0) { global $CFG, $USER, $DB; - $numattempts = $DB->count_records('game_attempts', array('gameid'=> $game->id, 'preview'=>0));echo "num=$numattempts gameid=$game->id
"; + $numattempts = $DB->count_records('game_attempts', array('gameid' => $game->id, 'preview' => 0)); + if ($numattempts || $returnzero) { if (groups_get_activity_groupmode($cm)) { $a = new stdClass(); @@ -768,77 +771,6 @@ function game_get_grading_options() { GAME_ATTEMPTLAST => get_string('attemptlast', 'quiz')); } -/** - * This fucntion extends the global navigaiton for the site. - * It is important to note that you should not rely on PAGE objects within this - * body of code as there is no guarantee that during an AJAX request they are - * available - * - * @param navigation_node $gamenode The game node within the global navigation - * @param stdClass $course The course object returned from the DB - * @param stdClass $module The module object returned from the DB - * @param stdClass $cm The course module isntance returned from the DB - */ - /* -function game_extend_navigation($gamenode, $course, $module, $cm) { - $context = get_context_instance(CONTEXT_MODULE, $cm->id); - - if (!has_capability('mod/game:viewreports', $context)) - return; - - if (has_capability('mod/game:view', $context)) { - $url = new moodle_url('/mod/game/view.php', array('id'=>$cm->id)); - $gamenode->add(get_string('info', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/info', '')); - } - - if (has_capability('mod/game:manage', $context)) { - $url = new moodle_url('/course/modedit.php', array('update' => $cm->id, 'return' => true, 'sesskey' => sesskey())); - $gamenode->add(get_string('edit', 'moodle', ''), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('t/edit', '')); - } - - // if (has_capability('mod/game:viewreports', $context)) { - // $url = new moodle_url('/mod/game/report.php', array('q'=>$cm->instance)); - // $reportnode = $gamenode->add(get_string('results', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - //} - - if (has_capability('mod/game:viewreports', $context)) { - $url = new moodle_url('/mod/game/showanswers.php', array('q'=>$cm->instance)); - $reportnode = $gamenode->add(get_string('showanswers', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - } - - if (has_capability('mod/game:viewreports', $context)) { - $url = new moodle_url('/mod/game/showattempts.php', array('q'=>$cm->instance)); - $reportnode = $gamenode->add(get_string('showattempts', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('f/explore', '')); - } - - - if (has_capability('mod/game:viewreports', $context)) - { - switch( $module->gamekind){ - case 'bookquiz': - $url = new moodle_url('/mod/game/bookquiz/questions.php', array('q'=>$cm->instance)); - $exportnode = $gamenode->add( get_string('bookquiz_questions', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - break; - case 'hangman': - $url = new moodle_url('', null); - $exportnode = $gamenode->add( get_string('export', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/report', '')); - - $url = new moodle_url('/mod/game/export.php', array( 'id' => $cm->id,'courseid'=>$course->id, 'target' => 'html')); - $exportnode->add( get_string('export_to_html', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - - $url = new moodle_url('/mod/game/export.php', array( 'id' => $cm->id,'courseid'=>$course->id, 'target' => 'javame')); - $exportnode->add( get_string('export_to_javame', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - break; - case 'snakes': - case 'cross': - case 'millionaire': - $url = new moodle_url('/mod/game/export.php', array( 'id' => $cm->id,'courseid'=>$course->id, 'target' => 'html')); - $gamenode->add(get_string('export_to_html', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - break; - } - } -} -*/ /** * This function extends the settings navigation block for the site. * @@ -853,64 +785,69 @@ function game_extend_settings_navigation($settings, $gamenode) { global $PAGE, $CFG, $DB; $context = $PAGE->cm->context; - - if (!has_capability('mod/game:viewreports', $context)) + + if (!has_capability('mod/game:viewreports', $context)) { return; + } if (has_capability('mod/game:view', $context)) { - $url = new moodle_url('/mod/game/view.php', array('id'=>$PAGE->cm->id)); + $url = new moodle_url('/mod/game/view.php', array('id' => $PAGE->cm->id)); $gamenode->add(get_string('info', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/info', '')); } if (has_capability('mod/game:manage', $context)) { $url = new moodle_url('/course/modedit.php', array('update' => $PAGE->cm->id, 'return' => true, 'sesskey' => sesskey())); - $gamenode->add(get_string('edit', 'moodle', ''), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('t/edit', '')); + $gamenode->add(get_string('edit', 'moodle', ''), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('t/edit', '')); } - /* if (has_capability('mod/game:viewreports', $context)) { - $url = new moodle_url('/mod/game/report.php', array('q'=>$cm->instance)); - $reportnode = $gamenode->add(get_string('results', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - } */ - if (has_capability('mod/game:viewreports', $context)) { - $url = new moodle_url('/mod/game/showanswers.php', array('q'=>$PAGE->cm->instance)); - $reportnode = $gamenode->add(get_string('showanswers', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); + $url = new moodle_url('/mod/game/showanswers.php', array('q' => $PAGE->cm->instance)); + $reportnode = $gamenode->add(get_string('showanswers', 'game'), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('i/item', '')); } if (has_capability('mod/game:viewreports', $context)) { - $url = new moodle_url('/mod/game/showattempts.php', array('q'=>$PAGE->cm->instance)); - $reportnode = $gamenode->add(get_string('showattempts', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('f/explore', '')); + $url = new moodle_url('/mod/game/showattempts.php', array('q' => $PAGE->cm->instance)); + $reportnode = $gamenode->add(get_string('showattempts', 'game'), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('f/explore', '')); } - - if (has_capability('mod/game:viewreports', $context)) - { + if (has_capability('mod/game:viewreports', $context)) { $game = $DB->get_record('game', array("id" => $PAGE->cm->instance)); $courseid = $game->course; - - switch( $game->gamekind){ - case 'bookquiz': - $url = new moodle_url('/mod/game/bookquiz/questions.php', array('q'=>$PAGE->cm->instance)); - $exportnode = $gamenode->add( get_string('bookquiz_questions', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - break; - case 'hangman': - $url = new moodle_url('', null); - $exportnode = $gamenode->add( get_string('export', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/report', '')); - - $url = new moodle_url('/mod/game/export.php', array( 'id' => $PAGE->cm->id,'courseid'=>$courseid, 'target' => 'html')); - $exportnode->add( get_string('export_to_html', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - - $url = new moodle_url('/mod/game/export.php', array( 'id' => $PAGE->cm->id,'courseid'=>$courseid, 'target' => 'javame')); - $exportnode->add( get_string('export_to_javame', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - break; - case 'snakes': - case 'cross': - case 'millionaire': - $url = new moodle_url('/mod/game/export.php', array( 'q' => $game->id,'courseid'=>$courseid, 'target' => 'html')); - $gamenode->add(get_string('export_to_html', 'game'), $url, navigation_node::TYPE_SETTING, null, null, new pix_icon('i/item', '')); - break; + + switch( $game->gamekind) { + case 'bookquiz': + $url = new moodle_url('/mod/game/bookquiz/questions.php', array('q' => $PAGE->cm->instance)); + $exportnode = $gamenode->add( get_string('bookquiz_questions', 'game'), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('i/item', '')); + break; + case 'hangman': + $url = new moodle_url('', null); + $exportnode = $gamenode->add( get_string('export', 'game'), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('i/report', '')); + + $url = new moodle_url('/mod/game/export.php', array( 'id' => $PAGE->cm->id, + 'courseid' => $courseid, 'target' => 'html')); + $exportnode->add( get_string('export_to_html', 'game'), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('i/item', '')); + + $url = new moodle_url('/mod/game/export.php', array( 'id' => $PAGE->cm->id, + 'courseid' => $courseid, 'target' => 'javame')); + $exportnode->add( get_string('export_to_javame', 'game'), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('i/item', '')); + break; + case 'snakes': + case 'cross': + case 'millionaire': + $url = new moodle_url('/mod/game/export.php', array( 'q' => $game->id, + 'courseid' => $courseid, 'target' => 'html')); + $gamenode->add(get_string('export_to_html', 'game'), $url, navigation_node::TYPE_SETTING, + null, null, new pix_icon('i/item', '')); + break; } - } + } } /** @@ -918,7 +855,7 @@ function game_extend_settings_navigation($settings, $gamenode) { * menu list when adding new game * */ -function game_get_types(){ +function game_get_types() { global $DB; $config = get_config('game'); @@ -931,12 +868,9 @@ function game_get_types(){ $type->typestr = '--'.get_string( 'modulenameplural', 'game'); $types[] = $type; - if( isset( $config->hidehangman)) - $hide = ($config->hidehangman != 0); - else - $hide = false; - if( $hide == false) - { + $hide = ( isset( $config->hidehangman)) ? ($config->hidehangman != 0) : false); + + if ($hide == false) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=hangman"; @@ -944,51 +878,45 @@ function game_get_types(){ $types[] = $type; } - if( isset( $config->hidecross)) + if (isset( $config->hidecross)) { $hide = ($config->hidecross != 0); - else + } else { $hide = false; - if( $hide == false) - { + } + + if ($hide == false) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=cross"; $type->typestr = get_string('game_cross', 'game'); $types[] = $type; } - - if( isset( $config->hidecryptex)) + + if (isset( $config->hidecryptex)) { $hide = ($config->hidecryptex != 0); - else + } else { $hide = false; - if( $hide == false) - { + } + + if ($hide == false) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=cryptex"; $type->typestr = get_string('game_cryptex', 'game'); $types[] = $type; } - - if( isset( $config->hidemillionaire)) - $hide = ($config->hidemillionaire != 0); - else - $hide = false; - if( $hide == false) - { + + $hide = (isset( $config->hidemillionaire)) ? ($config->hidemillionaire != 0) : false); + if ($hide == false) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=millionaire"; $type->typestr = get_string('game_millionaire', 'game'); $types[] = $type; } - - if( isset( $config->hidesudoku)) - $hide = ($config->hidesudoku != 0); - else - $hide = false; - if( $hide == false) - { + + $hide = (isset( $config->hidesudoku)) ? ($config->hidesudoku != 0) : false); + if ($hide == false) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=sudoku"; @@ -996,12 +924,8 @@ function game_get_types(){ $types[] = $type; } - if( isset( $config->hidesnakes)) - $hide = ($config->hidesnakes != 0); - else - $hide = false; - if( $hide == false) - { + $hide = (isset( $config->hidesnakes)) ? ($config->hidesnakes != 0) : false); + if ($hide == false) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=snakes"; @@ -1009,12 +933,8 @@ function game_get_types(){ $types[] = $type; } - if( isset( $config->hidehiddenpicture)) - $hide = ($config->hidehiddenpicture != 0); - else - $hide = false; - if( $hide == false) - { + $hide = (isset( $config->hidehiddenpicture)) ? ($config->hidehiddenpicture != 0) : false); + if ($hide == false) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=hiddenpicture"; @@ -1022,13 +942,9 @@ function game_get_types(){ $types[] = $type; } - if( isset( $config->hidebookquiz)) - $hide = ($config->hidebookquiz != 0); - else - $hide = false; - if( $hide == false) - { - if($DB->get_record( 'modules', array( 'name' => 'book'), 'id,id')){ + $hide = (isset( $config->hidebookquiz)) ? ($config->hidebookquiz != 0) : false); + if ($hide == false) { + if ($DB->get_record( 'modules', array( 'name' => 'book'), 'id,id')) { $type = new object(); $type->modclass = MOD_CLASS_ACTIVITY; $type->type = "game&type=bookquiz"; @@ -1046,8 +962,7 @@ function game_get_types(){ return $types; } -function mod_game_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) -{ +function mod_game_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload) { global $CFG, $DB; if ($context->contextlevel != CONTEXT_MODULE) { @@ -1056,15 +971,14 @@ function mod_game_pluginfile($course, $cm, $context, $filearea, $args, $forcedow require_course_login($course, true, $cm); - if( $filearea == 'questiontext') - { + if ($filearea == 'questiontext') { $questionid = $args[ 0]; $file = $args[ 1]; $a = explode( '/', $context->path); if (!$contextcourse = get_context_instance(CONTEXT_COURSE, $course->id)) { print_error('nocontext'); } - $a = array( 'component' => 'question', 'filearea' => 'questiontext', + $a = array( 'component' => 'question', 'filearea' => 'questiontext', 'itemid' => $questionid, 'filename' => $file, 'contextid' => $contextcourse->id); $rec = $DB->get_record( 'files', $a); @@ -1073,17 +987,16 @@ function mod_game_pluginfile($course, $cm, $context, $filearea, $args, $forcedow return false; } - // finally send the file - send_stored_file($file, 0, 0, true); // download MUST be forced - security! - }else if( $filearea == 'answer') - { + // Finally send the file. + send_stored_file($file, 0, 0, true); // download MUST be forced - security! + } else if ($filearea == 'answer') { $answerid = $args[ 0]; $file = $args[ 1]; - + if (!$contextcourse = get_context_instance(CONTEXT_COURSE, $course->id)) { print_error('nocontext'); } - $rec = $DB->get_record( 'files', array( 'component' => 'question', 'filearea' => 'answer', + $rec = $DB->get_record( 'files', array( 'component' => 'question', 'filearea' => 'answer', 'itemid' => $answerid, 'filename' => $file, 'contextid' => $contextcourse->id)); $fs = get_file_storage(); @@ -1091,9 +1004,9 @@ function mod_game_pluginfile($course, $cm, $context, $filearea, $args, $forcedow return false; } - // finally send the file - send_stored_file($file, 0, 0, true); // download MUST be forced - security! - } + // Finally send the file. + send_stored_file($file, 0, 0, true); // Download MUST be forced - security! + } $filearea = $args[ 0]; $filename = $args[ 1]; @@ -1105,7 +1018,7 @@ function mod_game_pluginfile($course, $cm, $context, $filearea, $args, $forcedow return false; } - // finally send the file + // Finally send the file. send_stored_file($file, 0, 0, true); // download MUST be forced - security! } @@ -1116,8 +1029,7 @@ function mod_game_pluginfile($course, $cm, $context, $filearea, $args, $forcedow */ function game_reset_course_form_definition(&$mform) { $mform->addElement('header', 'gameheader', get_string('modulenameplural', 'game')); - $mform->addElement('checkbox', 'reset_game_all', get_string('reset_game_all','game')); - + $mform->addElement('checkbox', 'reset_game_all', get_string('reset_game_all', 'game')); $mform->addElement('checkbox', 'reset_game_deleted_course', get_string('reset_game_deleted_course', 'game')); } @@ -1126,7 +1038,7 @@ function game_reset_course_form_definition(&$mform) { * @return array */ function game_reset_course_form_defaults($course) { - return array('reset_game_all'=>0, 'reset_game_deleted_course' => 0); + return array('reset_game_all' => 0, 'reset_game_deleted_course' => 0); } /** @@ -1144,22 +1056,27 @@ function game_reset_userdata($data) { $status = array(); $fs = get_file_storage(); - for($i=1; $i <= 2; $i++){ - if( $i == 1){ - if (empty($data->reset_game_all)) - continue; + for ($i = 1; $i <= 2; $i++) { + if ($i == 1) { + if (empty($data->reset_game_all)) { + continue; + } $allgamessql = 'SELECT g.id FROM {game} g WHERE g.course = '.$data->courseid; - $allattemptssql = 'SELECT ga.id FROM {game} g LEFT JOIN {game_attempts} ga ON g.id = ga.gameid WHERE g.course = '.$data->courseid; - $newstatus = array('component'=>$componentstr, 'item'=>get_string('reset_game_all', 'game'), 'error'=>false); - }else if( $i == 2) - { - if (empty($data->reset_game_deleted_course)) - continue; + $allattemptssql = 'SELECT ga.id FROM {game} g LEFT JOIN {game_attempts} ga ON g.id = ga.gameid WHERE g.course = '. + $data->courseid; + $newstatus = array('component' => $componentstr, 'item' => get_string('reset_game_all', 'game'), 'error' => false); + } else if ($i == 2) { + if (empty($data->reset_game_deleted_course)) { + continue; + } + $allgamessql = 'SELECT g.id FROM {game} g WHERE NOT EXISTS( SELECT * FROM {course} c WHERE c.id = g.course)'; - $allattemptssql = 'SELECT ga.id FROM {game_attempts} ga WHERE NOT EXISTS( SELECT * FROM {game} g WHERE ga.gameid = g.id)'; - $newstatus = array('component'=>$componentstr, 'item'=>get_string('reset_game_deleted_course', 'game'), 'error'=>false); + $allattemptssql = 'SELECT ga.id FROM {game_attempts} ga '. + 'WHERE NOT EXISTS( SELECT * FROM {game} g WHERE ga.gameid = g.id)'; + $newstatus = array('component' => $componentstr, 'item' => get_string('reset_game_deleted_course', 'game'), + 'error' => false); } - + $recs = $DB->get_recordset_sql($allgamessql); if ($recs->valid()) { foreach ($recs as $rec) { @@ -1169,16 +1086,16 @@ function game_reset_userdata($data) { $context = game_get_context_module_instance( $cm->id); $fs->delete_area_files($context->id, 'mod_game', 'gnakes_file'); $fs->delete_area_files($context->id, 'mod_game', 'gnakes_board'); - - //reset grades - $game = $DB->get_record_select( 'game', 'id='.$rec->id, null,'id,name,course '); - $grades = NULL; - $params = array('itemname'=>$game->name, 'idnumber'=>0); + + // Reset grades. + $game = $DB->get_record_select( 'game', 'id='.$rec->id, null, 'id,name,course '); + $grades = null; + $params = array('itemname' => $game->name, 'idnumber' => 0); $params['reset'] = true; grade_update('mod/game', $game->course, 'mod', 'game', $game->id, 0, $grades, $params); } - } - + } + $DB->delete_records_select('game_bookquiz', "id IN ($allgamessql)"); $DB->delete_records_select('game_bookquiz_chapters', "attemptid IN ($allattemptssql)"); $DB->delete_records_select('game_bookquiz_questions', "gameid IN ($allgamessql)"); @@ -1195,32 +1112,36 @@ function game_reset_userdata($data) { $DB->delete_records_select('game_snakes', "id IN ($allgamessql)"); $DB->delete_records_select('game_sudoku', "id IN ($allgamessql)"); - if( $i == 2) + if ($i == 2) { $DB->delete_records_select('game_attempts', "NOT EXISTS (SELECT * FROM {game} g WHERE {game_attempts}.gameid=g.id)"); - else - $DB->delete_records_select('game_attempts', "gameid IN ($allgamessql)"); - + } else { + $DB->delete_records_select('game_attempts', "gameid IN ($allgamessql)"); + } + $status[] = $newstatus; } - - if (empty($data->reset_game_deleted_course)) + + if (empty($data->reset_game_deleted_course)) { return $status; - - //Delete data from deleted games - $a = array( 'bookquiz', 'cross', 'cryptex', 'grades', 'bookquiz_questions', 'export_html', 'export_javame', 'hangman', + } + + // Delete data from deleted games. + $a = array( 'bookquiz', 'cross', 'cryptex', 'grades', 'bookquiz_questions', 'export_html', 'export_javame', 'hangman', 'hiddenpicture', 'millionaire', 'snakes', 'sudoku'); - foreach( $a as $table) + foreach ($a as $table) { $DB->delete_records_select( 'game_'.$table, "NOT EXISTS( SELECT * FROM {game} g WHERE {game_$table}.id=g.id)"); - - //gameid + } + $a = array( 'grades', 'queries', 'repetitions'); - foreach( $a as $table) + foreach ($a as $table) { $DB->delete_records_select( 'game_'.$table, "NOT EXISTS( SELECT * FROM {game} g WHERE {game_$table}.gameid=g.id)"); - - //attempts + } + $a = array( 'bookquiz_chapters'); - foreach( $a as $table) - $DB->delete_records_select( 'game_'.$table, "NOT EXISTS( SELECT * FROM {game_attempts} ga WHERE {game_$table}.attemptid=ga.id)"); + foreach ($a as $table) { + $DB->delete_records_select( 'game_'.$table, + "NOT EXISTS( SELECT * FROM {game_attempts} ga WHERE {game_$table}.attemptid=ga.id)"); + } return $status; } @@ -1236,25 +1157,24 @@ function game_reset_userdata($data) { * @return bool True if completed, false if not, $type if conditions not set. */ function game_get_completion_state($course, $cm, $userid, $type) { - global $CFG,$DB; - + global $CFG, $DB; + require_once($CFG->dirroot . '/mod/game/locallib.php'); - if( ($cm->completion == 0) or ($cm->completion == 1)){ + if (($cm->completion == 0) or ($cm->completion == 1)) { // Completion option is not enabled so just return $type. return $type; } - - if( $cm->completionview) - { - //Just want to view it. Not needed it + + if ($cm->completionview) { + // Just want to view it. Not needed it. return true; } if (! $game = $DB->get_record('game', array('id' => $cm->instance))) { print_error('invalidcoursemodule'); } - + $grade = $DB->get_record_select('game_grades', "userid=$userid AND gameid = $cm->instance", null, 'id,score'); return $grade && $grade->score > 0; @@ -1272,17 +1192,17 @@ function game_get_completion_state($course, $cm, $userid, $type) { function game_scale_used_anywhere($scaleid) { global $DB; - if ($scaleid and $DB->record_exists('game', array('grade'=>-$scaleid))) { + if ($scaleid and $DB->record_exists('game', array('grade' => -$scaleid))) { return true; } else { return false; } } -function game_get_context_module_instance( $moduleid) -{ - if( class_exists( 'context_module')) +function game_get_context_module_instance( $moduleid) { + if (class_exists( 'context_module')) { return context_module::instance( $moduleid); - + } + return get_context_instance( CONTEXT_MODULE, $moduleid); } diff --git a/locallib.php b/locallib.php index 53826d8..74ca377 100755 --- a/locallib.php +++ b/locallib.php @@ -1,17 +1,30 @@ -. if (!defined('MOODLE_INTERNAL')) { - die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page. + die('Direct access to this script is forbidden.'); // It must be included from a Moodle page. } -/** - * Include those library functions that are also used by core Moodle or other modules - */ + +// Include those library functions that are also used by core Moodle or other modules. require_once($CFG->dirroot . '/mod/game/lib.php'); require_once($CFG->dirroot . '/mod/quiz/locallib.php'); -/// CONSTANTS /////////////////////////////////////////////////////////////////// -/**#@+ +// CONSTANTS. +/* * Options determining how the grades from individual attempts are combined to give * the overall grade for a user */ @@ -21,860 +34,807 @@ define( "GAME_GRADEMETHOD_AVERAGE", "2"); define( "GAME_GRADEMETHOD_FIRST", "3"); define( "GAME_GRADEMETHOD_LAST", "4"); -$GAME_GRADE_METHOD = array ( GAME_GRADEMETHOD_HIGHEST => get_string("gradehighest", "game"), +$gamegrademethod = array ( GAME_GRADEMETHOD_HIGHEST => get_string("gradehighest", "game"), GAME_GRADEMETHOD_AVERAGE => get_string("gradeaverage", "game"), GAME_GRADEMETHOD_FIRST => get_string("attemptfirst", "game"), - GAME_GRADEMETHOD_LAST => get_string("attemptlast", "game")); + GAME_GRADEMETHOD_LAST => get_string("attemptlast", "game")); define( "CONST_GAME_TRIES_REPETITION", "3"); -/**#@-*/ - -function game_get_moodle_version() -{ +function game_get_moodle_version() { global $DB; - static $s_moodle_version = null; - - if( $s_moodle_version != null) - return $s_moodle_version; - + static $smoodleversion = null; + + if ($smoodleversion != null) { + return $smoodleversion; + } + $rec = $DB->get_record_select( 'config', "name='release'"); - if( $rec == false) - return $s_moodle_version=''; - else - { - $a = explode( '.', $rec->value); - return $s_moodle_version = sprintf( '%02u.%02u', $a[ 0], $a[ 1]); + if ($rec == false) { + return $smoodleversion = ''; + } else { + $a = explode( '.', $rec->value); + return $smoodleversion = sprintf( '%02u.%02u', $a[ 0], $a[ 1]); } } -function game_upper( $str, $lang='') -{ - if( $lang == 'user') +function game_upper( $str, $lang='') { + if ($lang == 'user') { return $str; + } $str = game_strtoupper( $str); -/* - $strings = get_string_manager()->load_component_strings( 'game', ($lang == '' ? 'en' : $lang)); - if( !isset( $strings[ 'convertfrom'])) - return $str; - if( !isset( $strings[ 'convertto'])) - return $str; -*/ - switch( $lang) - { - case 'el': - $from = 'ΆΈΉΊΌΎΏ'; - $to = 'ΑΕΗΙΟΥΩ'; - break; - default: - return $str; + + switch ($lang) { + case 'el': + $from = 'ΆΈΉΊΌΎΏ'; + $to = 'ΑΕΗΙΟΥΩ'; + break; + default: + return $str; } - + $len = game_strlen( $from); - for($i=0; $i < $len; $i++){ + for ($i = 0; $i < $len; $i++) { $str = str_replace( game_substr( $from, $i, 1), game_substr( $to, $i, 1), $str); } return $str; } +function game_showselectcontrol( $name, $a, $input, $events='') { + $ret = "\r\n"; + + return $ret; +} + +function game_showcheckbox( $name, $value) { + $a = array(); + $a[ 0] = get_string( 'no'); + $a[ 1] = get_string( 'yes'); -function game_showselectcontrol( $name, $a, $input, $events=''){ - $ret = "\r\n"; - - return $ret; -} - -function game_showcheckbox( $name, $value) -{ - $a = array(); - $a[ 0] = get_string( 'no'); - $a[ 1] = get_string( 'yes'); - - return game_showselectcontrol( $name, $a, $value); - - $ret = 'sourcemodule) - { - case 'glossary': - return game_question_shortanswer_glossary( $game, $allowspaces, $use_repetitions); - case 'quiz': - return game_question_shortanswer_quiz( $game, $allowspaces, $use_repetitions); - case 'question': - return game_question_shortanswer_question( $game, $allowspaces, $use_repetitions); - } - - return false; -} - -//used by hangman -function game_question_shortanswer_glossary( $game, $allowspaces, $use_repetitions) -{ + return game_showselectcontrol( $name, $a, $value); +} + +// Used by hangman. +function game_question_shortanswer( $game, $allowspaces=false, $userepetitions=true) { + switch( $game->sourcemodule) + { + case 'glossary': + return game_question_shortanswer_glossary( $game, $allowspaces, $userepetitions); + case 'quiz': + return game_question_shortanswer_quiz( $game, $allowspaces, $userepetitions); + case 'question': + return game_question_shortanswer_question( $game, $allowspaces, $userepetitions); + } + + return false; +} + +// Used by hangman. +function game_question_shortanswer_glossary( $game, $allowspaces, $userepetitions) { global $DB; - if( $game->glossaryid == 0){ - print_error( get_string( 'must_select_glossary', 'game')); - } + if ($game->glossaryid == 0) { + print_error( get_string( 'must_select_glossary', 'game')); + } $select = "glossaryid={$game->glossaryid}"; - $table = '{glossary_entries} ge'; - if( $game->glossarycategoryid){ - $table .= ',{glossary_entries_categories} gec'; - $select .= ' AND gec.entryid = ge.id '. - " AND gec.categoryid = {$game->glossarycategoryid}"; - } - if( $allowspaces == false){ - $select .= " AND concept NOT LIKE '% %' "; + $table = '{glossary_entries} ge'; + if ($game->glossarycategoryid) { + $table .= ',{glossary_entries_categories} gec'; + $select .= ' AND gec.entryid = ge.id '. + " AND gec.categoryid = {$game->glossarycategoryid}"; + } + if ($allowspaces == false) { + $select .= " AND concept NOT LIKE '% %' "; } - if( ($id = game_question_selectrandom( $game, $table, $select, 'ge.id', $use_repetitions)) == false) + if (($id = game_question_selectrandom( $game, $table, $select, 'ge.id', $userepetitions)) == false) { return false; - - $sql = 'SELECT id, concept as answertext, definition as questiontext, id as glossaryentryid, 0 as questionid, glossaryid, attachment, 0 as answerid'. + } + + $sql = 'SELECT id, concept as answertext, definition as questiontext, id as glossaryentryid, '. + ' 0 as questionid, glossaryid, attachment, 0 as answerid'. " FROM {glossary_entries} ge WHERE id = $id"; - if( ($rec = $DB->get_record_sql( $sql)) == false) + if (($rec = $DB->get_record_sql( $sql)) == false) { return false; - - if( $rec->attachment != ''){ + } + + if ( $rec->attachment != '') { $rec->attachment = "glossary/{$game->glossaryid}/$rec->id/$rec->attachment"; } - + return $rec; } -//used by hangman -function game_question_shortanswer_quiz( $game, $allowspaces, $use_repetitions) -{ +// Used by hangman. +function game_question_shortanswer_quiz( $game, $allowspaces, $userepetitions) { global $DB; - if( $game->quizid == 0){ - print_error( get_string( 'must_select_quiz', 'game')); - } + if ($game->quizid == 0) { + print_error( get_string( 'must_select_quiz', 'game')); + } - if( game_get_moodle_version() < '02.07') - { - $select = "qtype='shortanswer' AND quiz='$game->quizid' ". - " AND qqi.question=q.id"; - $table = "{question} q,{quiz_question_instances} qqi"; - }else - { - $select = "qtype='shortanswer' AND qs.quizid='$game->quizid' ". - " AND qs.questionid=q.id"; - $table = "{question} q,{quiz_slots} qs"; - } - $fields = "q.id"; - - if( ($id = game_question_selectrandom( $game, $table, $select, $fields, $use_repetitions)) == false) - return false; - - $select = "q.id=$id AND qa.question=$id". - " AND q.hidden=0 AND qtype='shortanswer'"; - $table = "{question} q,{question_answers} qa"; - $fields = "qa.id as answerid, q.id, q.questiontext as questiontext, ". - "qa.answer as answertext, q.id as questionid, ". - "0 as glossaryentryid, '' as attachment"; - - //Maybe there are more answers to one question. I use as correct the one with bigger fraction + if (game_get_moodle_version() < '02.07') { + $select = "qtype='shortanswer' AND quiz='$game->quizid' ". + " AND qqi.question=q.id"; + $table = "{question} q,{quiz_question_instances} qqi"; + } else { + $select = "qtype='shortanswer' AND qs.quizid='$game->quizid' ". + " AND qs.questionid=q.id"; + $table = "{question} q,{quiz_slots} qs"; + } + $fields = "q.id"; + + if (($id = game_question_selectrandom( $game, $table, $select, $fields, $userepetitions)) == false) { + return false; + } + + $select = "q.id=$id AND qa.question=$id". + " AND q.hidden=0 AND qtype='shortanswer'"; + $table = "{question} q,{question_answers} qa"; + $fields = "qa.id as answerid, q.id, q.questiontext as questiontext, ". + "qa.answer as answertext, q.id as questionid, ". + "0 as glossaryentryid, '' as attachment"; + + // Maybe there are more answers to one question. I use as correct the one with bigger fraction. $sql = "SELECT $fields FROM $table WHERE $select ORDER BY fraction DESC"; - if( ($recs=$DB->get_records_sql( $sql, null, 0, 1)) == false){ - return false; - } - foreach( $recs as $rec){ - return $rec; - } + if (($recs = $DB->get_records_sql( $sql, null, 0, 1)) == false) { + return false; + } + foreach ($recs as $rec) { + return $rec; + } } -//used by hangman -function game_question_shortanswer_question( $game, $allowspaces, $use_repetitions) -{ +// Used by hangman. +function game_question_shortanswer_question( $game, $allowspaces, $userepetitions) { global $DB; - - if( $game->questioncategoryid == 0){ - print_error( get_string( 'must_select_questioncategory', 'game')); - } - - $select = 'category='.$game->questioncategoryid; - if( $game->subcategories){ + + if ($game->questioncategoryid == 0) { + print_error( get_string( 'must_select_questioncategory', 'game')); + } + + $select = 'category='.$game->questioncategoryid; + if ($game->subcategories) { $cats = question_categorylist( $game->questioncategoryid); - if( count( $cats) > 0){ + if (count( $cats) > 0) { $s = implode( ',', $cats); $select = 'category in ('.$s.')'; } } - $select .= " AND qtype='shortanswer'"; - - $table = '{question} q'; - $fields = 'q.id'; - - if( ($id = game_question_selectrandom( $game, $table, $select, $fields, $use_repetitions)) == false) - return false; - - $select = "q.id=$id AND qa.question=$id". - " AND q.hidden=0 AND qtype='shortanswer'"; - $table = "{question} q,{question_answers} qa"; - $fields = "qa.id as answerid, q.id, q.questiontext as questiontext, ". - "qa.answer as answertext, q.id as questionid, ". - "0 as glossaryentryid, '' as attachment"; - - //Maybe there are more answers to one question. I use as correct the one with bigger fraction - $sql = "SELECT $fields FROM $table WHERE $select ORDER BY fraction DESC"; - if( ($recs = $DB->get_records_sql( $sql, null, 0, 1)) == false){ - return false; - } - foreach( $recs as $rec){ - return $rec; - } -} - -//used by millionaire, game_question_shortanswer_quiz, hidden picture -function game_question_selectrandom( $game, $table, $select, $id_fields='id', $use_repetitions=true) -{ - global $DB, $USER; + $select .= " AND qtype='shortanswer'"; + + $table = '{question} q'; + $fields = 'q.id'; + + if (($id = game_question_selectrandom( $game, $table, $select, $fields, $userepetitions)) == false) { + return false; + } + + $select = "q.id=$id AND qa.question=$id". + " AND q.hidden=0 AND qtype='shortanswer'"; + $table = "{question} q,{question_answers} qa"; + $fields = "qa.id as answerid, q.id, q.questiontext as questiontext, ". + "qa.answer as answertext, q.id as questionid, ". + "0 as glossaryentryid, '' as attachment"; + + // Maybe there are more answers to one question. I use as correct the one with bigger fraction. + $sql = "SELECT $fields FROM $table WHERE $select ORDER BY fraction DESC"; + if (($recs = $DB->get_records_sql( $sql, null, 0, 1)) == false) { + return false; + } + foreach ($recs as $rec) { + return $rec; + } +} + +// Used by millionaire, game_question_shortanswer_quiz, hidden picture. +function game_question_selectrandom( $game, $table, $select, $idfields='id', $userepetitions=true) { + global $DB, $USER; $count = $DB->get_field_sql( "SELECT COUNT(*) FROM $table WHERE $select"); - - if( $count == 0) + + if ($count == 0) { return false; - - $min_num = 0; - $min_id = 0; - for($i=1; $i <= CONST_GAME_TRIES_REPETITION; $i++){ - $sel = mt_rand(0, $count-1); - - $sql = "SELECT $id_fields,$id_fields FROM ".$table." WHERE $select"; - if( ($recs = $DB->get_records_sql( $sql, null, $sel, 1)) == false){ + } + + $minnum = 0; + $minid = 0; + for ($i = 1; $i <= CONST_GAME_TRIES_REPETITION; $i++) { + $sel = mt_rand(0, $count - 1); + + $sql = "SELECT $idfields, $idfields FROM ".$table." WHERE $select"; + if (($recs = $DB->get_records_sql( $sql, null, $sel, 1)) == false) { return false; } $id = 0; - foreach( $recs as $rec){ + foreach ($recs as $rec) { $id = $rec->id; } - if( $min_id == 0){ - $min_id = $id; + if ($minid == 0) { + $minid = $id; } - - if( $use_repetitions == false){ + + if ($userepetitions == false) { return $id; } - - if( $count == 1){ + + if ($count == 1) { break; } - + $questionid = $glossaryentryid = 0; - if( $game->sourcemodule == 'glossary') + if ($game->sourcemodule == 'glossary') { $glossaryentryid = $id; - else + } else { $questionid = $id; - - $a = array( 'gameid' => $game->id, 'userid' => $USER->id, 'questionid' => $questionid, 'glossaryentryid' => $glossaryentryid); - if( ($rec = $DB->get_record( 'game_repetitions', $a, 'id,repetitions AS r')) != false){ - if( ($rec->r < $min_num) or ($min_num == 0)){ - $min_num = $rec->r; - $min_id = $id; + } + + $a = array( 'gameid' => $game->id, 'userid' => $USER->id, 'questionid' => $questionid, + 'glossaryentryid' => $glossaryentryid); + if (($rec = $DB->get_record( 'game_repetitions', $a, 'id,repetitions AS r')) != false) { + if (($rec->r < $minnum) or ($minnum == 0)) { + $minnum = $rec->r; + $minid = $id; } - }else - { - $min_id = $questionid; + } else { + $minid = $questionid; break; } - } - if( $game->sourcemodule == 'glossary') - game_update_repetitions( $game->id, $USER->id, 0, $min_id); - else - game_update_repetitions( $game->id, $USER->id, $min_id, 0); - - return $min_id; + if ($game->sourcemodule == 'glossary') { + game_update_repetitions( $game->id, $USER->id, 0, $minid); + } else { + game_update_repetitions( $game->id, $USER->id, $minid, 0); + } + + return $minid; } -function game_update_repetitions( $gameid, $userid, $questionid, $glossaryentryid){ +function game_update_repetitions( $gameid, $userid, $questionid, $glossaryentryid) { global $DB; $a = array( 'gameid' => $gameid, 'userid' => $userid, 'questionid' => $questionid, 'glossaryentryid' => $glossaryentryid); - if( ($rec = $DB->get_record( 'game_repetitions', $a, 'id,repetitions AS r')) != false){ + if (($rec = $DB->get_record( 'game_repetitions', $a, 'id,repetitions AS r')) != false) { $updrec = new stdClass(); $updrec->id = $rec->id; $updrec->repetitions = $rec->r + 1; - if( !$DB->update_record( 'game_repetitions', $updrec)){ - print_error("Update page: can't update game_repetitions id={$updrec->id}"); + if (!$DB->update_record( 'game_repetitions', $updrec)) { + print_error("Update page: can't update game_repetitions id={$updrec->id}"); } - }else - { + } else { $newrec = new stdClass(); $newrec->gameid = $gameid; $newrec->userid = $userid; $newrec->questionid = $questionid; $newrec->glossaryentryid = $glossaryentryid; $newrec->repetitions = 1; - - if( $newrec->questionid == ''){ + + if ($newrec->questionid == '') { $newrec->questionid = 0; } - if( $newrec->glossaryentryid == ''){ + if ($newrec->glossaryentryid == '') { $newrec->glossaryentryid = 0; } - - if (!$DB->insert_record( 'game_repetitions', $newrec)){ - print_r( $newrec); + if (!$DB->insert_record( 'game_repetitions', $newrec)) { print_error("Insert page: new page game_repetitions not inserted"); } } } -//used by sudoku -function game_questions_selectrandom( $game, $count=1) -{ - global $DB; - - switch( $game->sourcemodule) - { - case 'quiz': - - if( $game->quizid == 0){ - print_error( get_string( 'must_select_quiz', 'game')); - } - - if( game_get_moodle_version() < '02.07') - { - $table = '{question} q, {quiz_question_instances} qqi'; - $select = " qqi.quiz=$game->quizid". - " AND qqi.question=q.id ". - " AND q.qtype in ('shortanswer', 'truefalse', 'multichoice')". - " AND q.hidden=0"; - }else - { - - $table = '{question} q, {quiz_slots} qs'; - $select = " qs.quizid=$game->quizid". - " AND qs.questionid=q.id ". - " AND q.qtype in ('shortanswer', 'truefalse', 'multichoice')". - " AND q.hidden=0"; - } -//todo 'match' - $field = "q.id as id"; - - $table2 = 'question'; - $fields2 = 'id as questionid,0 as glossaryentryid,qtype'; - break; - case 'glossary': - if( $game->glossaryid == 0){ - print_error( get_string( 'must_select_glossary', 'game')); - } - $table = '{glossary_entries} ge'; - $select = "glossaryid='$game->glossaryid' "; - if( $game->glossarycategoryid){ - $table .= ',{glossary_entries_categories} gec'; - $select .= " AND gec.entryid = ge.id ". - " AND gec.categoryid = {$game->glossarycategoryid}"; - } - $field = 'ge.id'; - $table2 = 'glossary_entries'; - $fields2 = 'id as glossaryentryid, 0 as questionid'; - break; - case 'question': - if( $game->questioncategoryid == 0){ - print_error( get_string( 'must_select_questioncategory', 'game')); - } - $table = '{question} q'; - - //inlcude subcategories - $select = 'category='.$game->questioncategoryid; - if( $game->subcategories){ - $cats = question_categorylist( $game->questioncategoryid); - if( count( $cats)) - $select = 'category in ('.implode( ',', $cats).')'; - } - - $select .= " AND q.qtype in ('shortanswer', 'truefalse', 'multichoice') ". - "AND q.hidden=0"; -//todo 'match' - $field = "id"; - - $table2 = 'question'; - $fields2 = 'id as questionid,0 as glossaryentryid'; - break; - default: - print_error( 'No sourcemodule defined'); - break; - } - - $ids = game_questions_selectrandom_detail( $table, $select, $field, $count); - if( $ids === false){ - print_error( get_string( 'no_questions', 'game')); - } - - if( count( $ids) > 1){ - //randomize the array - shuffle( $ids); - } - - $ret = array(); - foreach( $ids as $id) - { - if( $recquestion = $DB->get_record( $table2, array( 'id' => $id), $fields2)){ - $new = new stdClass(); - $new->questionid = (int )$recquestion->questionid; - $new->glossaryentryid = (int )$recquestion->glossaryentryid; - $ret[] = $new; - } - } - - return $ret; -} - -//used by game_questions_selectrandom -function game_questions_selectrandom_detail( $table, $select, $id_field="id", $count=1) -{ +// Used by sudoku. +function game_questions_selectrandom( $game, $count=1) { global $DB; - - $sql = "SELECT $id_field FROM $table WHERE $select"; - if( ($recs=$DB->get_records_sql( $sql)) == false) + + switch( $game->sourcemodule) + { + case 'quiz': + if ($game->quizid == 0) { + print_error( get_string( 'must_select_quiz', 'game')); + } + if (game_get_moodle_version() < '02.07') { + $table = '{question} q, {quiz_question_instances} qqi'; + $select = " qqi.quiz=$game->quizid". + " AND qqi.question=q.id ". + " AND q.qtype in ('shortanswer', 'truefalse', 'multichoice')". + " AND q.hidden=0"; + } else { + $table = '{question} q, {quiz_slots} qs'; + $select = " qs.quizid=$game->quizid". + " AND qs.questionid=q.id ". + " AND q.qtype in ('shortanswer', 'truefalse', 'multichoice')". + " AND q.hidden=0"; + } + // Todo 'match'. + $field = "q.id as id"; + $table2 = 'question'; + $fields2 = 'id as questionid,0 as glossaryentryid,qtype'; + break; + case 'glossary': + if ($game->glossaryid == 0) { + print_error( get_string( 'must_select_glossary', 'game')); + } + $table = '{glossary_entries} ge'; + $select = "glossaryid='$game->glossaryid' "; + if ($game->glossarycategoryid) { + $table .= ',{glossary_entries_categories} gec'; + $select .= " AND gec.entryid = ge.id ". + " AND gec.categoryid = {$game->glossarycategoryid}"; + } + $field = 'ge.id'; + $table2 = 'glossary_entries'; + $fields2 = 'id as glossaryentryid, 0 as questionid'; + break; + case 'question': + if ($game->questioncategoryid == 0) { + print_error( get_string( 'must_select_questioncategory', 'game')); + } + $table = '{question} q'; + + // Inlcude subcategories. + $select = 'category='.$game->questioncategoryid; + if ($game->subcategories) { + $cats = question_categorylist( $game->questioncategoryid); + if (count( $cats)) { + $select = 'category in ('.implode( ',', $cats).')'; + } + } + + $select .= " AND q.qtype in ('shortanswer', 'truefalse', 'multichoice') AND q.hidden=0"; + // Todo 'match'. + $field = "id"; + + $table2 = 'question'; + $fields2 = 'id as questionid,0 as glossaryentryid'; + break; + default: + print_error( 'No sourcemodule defined'); + break; + } + + $ids = game_questions_selectrandom_detail( $table, $select, $field, $count); + if ($ids === false) { + print_error( get_string( 'no_questions', 'game')); + } + + if (count( $ids) > 1) { + // Randomize the array. + shuffle( $ids); + } + + $ret = array(); + foreach ($ids as $id) { + if ($recquestion = $DB->get_record( $table2, array( 'id' => $id), $fields2)) { + $new = new stdClass(); + $new->questionid = (int )$recquestion->questionid; + $new->glossaryentryid = (int )$recquestion->glossaryentryid; + $ret[] = $new; + } + } + + return $ret; +} + +// Used by game_questions_selectrandom. +function game_questions_selectrandom_detail( $table, $select, $idfield="id", $count=1) { + global $DB; + + $sql = "SELECT $idfield FROM $table WHERE $select"; + if (($recs = $DB->get_records_sql( $sql)) == false) { return false; + } - //the array contains the ids of all questions - $a = array(); - foreach( $recs as $rec){ + // The array contains the ids of all questions. + $a = array(); + foreach ($recs as $rec) { $a[ $rec->id] = $rec->id; } - if( $count >= count( $a)){ - return $a; - }else - { - $id = array_rand( $a, $count); - return ( $count == 1 ? array( $id) : $id); - } + if ($count >= count( $a)) { + return $a; + } else { + $id = array_rand( $a, $count); + return ($count == 1 ? array( $id) : $id); + } } -//Tries to detect the language of word -function game_detectlanguage( $word){ +// Tries to detect the language of word. +function game_detectlanguage( $word) { global $CFG; - + $langs = get_string_manager()->get_list_of_translations(); - - //English has more priority - if( array_key_exists( 'en', $langs)) - { + + // English has more priority. + if (array_key_exists( 'en', $langs)) { unset( $langs[ 'en']); $langs[ ''] = ''; } ksort( $langs); - $langs_installed = get_string_manager()->get_list_of_translations(); - - foreach( $langs as $lang => $name) - { - if( $lang == '') + $langsinstalled = get_string_manager()->get_list_of_translations(); + + foreach ($langs as $lang => $name) { + if ($lang == '') { $lang = 'en'; - - if( !array_key_exists( $lang, $langs_installed)) + } + + if (!array_key_exists( $lang, $langsinstalled)) { continue; - + } + $strings = get_string_manager()->load_component_strings( 'game', $lang); - if( isset( $strings[ 'lettersall'])) - { + if (isset( $strings[ 'lettersall'])) { $letters = $strings[ 'lettersall']; $word2 = game_upper( $word, $lang); - if( hangman_existall( $word2, $letters)) + if (hangman_existall( $word2, $letters)) { return $lang; - } + } + } } return false; } -//The words maybe are in two languages e.g. greek or english -//so I try to find the correct one. -function game_getallletters( $word, $lang='', $userlanguage='') -{ - for(;;) - { - if( $lang == 'user') - { +// The words maybe are in two languages e.g. greek or english so I try to find the correct one. +function game_getallletters( $word, $lang='', $userlanguage='') { + for (;;) { + if ($lang == 'user') { $letters = $userlanguage; - if( hangman_existall( $word, $letters)) + if (hangman_existall( $word, $letters)) { return $letters; - else + } else { return ''; - }else - { + } + } else { $strings = get_string_manager()->load_component_strings( 'game', ($lang == '' ? 'en' : $lang)); - if( isset( $strings[ 'lettersall'])) - { + if (isset( $strings[ 'lettersall'])) { $letters = $strings[ 'lettersall']; $word2 = game_upper( $word, $lang); - if( hangman_existall( $word2, $letters)) + if (hangman_existall( $word2, $letters)) { return $letters; + } } - if( $lang == '') + if ($lang == '') { break; - else - $lang = ''; + } else { + $lang = ''; + } } } - + return ''; } -function hangman_existall( $str, $strfind) -{ +function hangman_existall( $str, $strfind) { $n = game_strlen( $str); - for( $i=0; $i < $n; $i++) - { - $pos = game_strpos( $strfind, game_substr( $str, $i, 1)); - if( $pos === false) + for ($i = 0; $i < $n; $i++) { + $pos = game_strpos( $strfind, game_substr( $str, $i, 1)); + if ($pos === false) { return false; + } } - + return true; } -//used by cross -function game_questions_shortanswer( $game) -{ - switch( $game->sourcemodule) - { - case 'glossary': - $recs = game_questions_shortanswer_glossary( $game); - break; - case 'quiz'; - $recs = game_questions_shortanswer_quiz( $game); - break; - case 'question'; - $recs = game_questions_shortanswer_question( $game); - break; - } - - return $recs; -} - -//used by cross -function game_questions_shortanswer_glossary( $game) -{ +// Used by cross. +function game_questions_shortanswer( $game) { + switch( $game->sourcemodule) { + case 'glossary': + $recs = game_questions_shortanswer_glossary( $game); + break; + case 'quiz'; + $recs = game_questions_shortanswer_quiz( $game); + break; + case 'question'; + $recs = game_questions_shortanswer_question( $game); + break; + } + + return $recs; +} + +// Used by cross. +function game_questions_shortanswer_glossary( $game) { global $DB; - + $select = "glossaryid={$game->glossaryid}"; $table = '{glossary_entries} ge'; - if( $game->glossarycategoryid){ - $table .= ',{glossary_entries_categories} gec'; - $select .= ' AND gec.entryid = ge.id '. - ' AND gec.categoryid = '.$game->glossarycategoryid; - } - - $sql = 'SELECT ge.id, concept as answertext, definition as questiontext, ge.id as glossaryentryid, 0 as questionid, attachment '. - " FROM $table WHERE $select"; + if ($game->glossarycategoryid) { + $table .= ',{glossary_entries_categories} gec'; + $select .= ' AND gec.entryid = ge.id '. + ' AND gec.categoryid = '.$game->glossarycategoryid; + } - return $DB->get_records_sql( $sql); + $sql = 'SELECT ge.id, concept as answertext, definition as questiontext, ge.id as glossaryentryid, '. + ' 0 as questionid, attachment '. + " FROM $table WHERE $select"; + return $DB->get_records_sql( $sql); } -//used by cross -function game_questions_shortanswer_quiz( $game) -{ + +// Used by cross. +function game_questions_shortanswer_quiz( $game) { global $DB; - - if( $game->quizid == 0){ + + if ($game->quizid == 0) { print_error( get_string( 'must_select_quiz', 'game')); - } - - if( game_get_moodle_version() < '02.07') - { - $select = "qtype='shortanswer' AND quiz='$game->quizid' ". - " AND qqi.question=q.id". - " AND qa.question=q.id". - " AND q.hidden=0"; - $table = "{question} q,{quiz_question_instances} qqi,{question_answers} qa"; - $fields = "qa.id as qaid, q.id, q.questiontext as questiontext, ". - "qa.answer as answertext, q.id as questionid,". - " 0 as glossaryentryid,'' as attachment"; - }else - { - $select = "qtype='shortanswer' AND qs.quizid='$game->quizid' ". - " AND qs.questionid=q.id". - " AND qa.question=q.id". - " AND q.hidden=0"; - $table = "{question} q,{quiz_slots} qs,{question_answers} qa"; - $fields = "qa.id as qaid, q.id, q.questiontext as questiontext, ". - "qa.answer as answertext, q.id as questionid,". - " 0 as glossaryentryid,'' as attachment"; } - return game_questions_shortanswer_question_fraction( $table, $fields, $select); + if (game_get_moodle_version() < '02.07') { + $select = "qtype='shortanswer' AND quiz='$game->quizid' ". + " AND qqi.question=q.id". + " AND qa.question=q.id". + " AND q.hidden=0"; + $table = "{question} q,{quiz_question_instances} qqi,{question_answers} qa"; + $fields = "qa.id as qaid, q.id, q.questiontext as questiontext, ". + "qa.answer as answertext, q.id as questionid,". + " 0 as glossaryentryid,'' as attachment"; + } else { + $select = "qtype='shortanswer' AND qs.quizid='$game->quizid' ". + " AND qs.questionid=q.id". + " AND qa.question=q.id". + " AND q.hidden=0"; + $table = "{question} q,{quiz_slots} qs,{question_answers} qa"; + $fields = "qa.id as qaid, q.id, q.questiontext as questiontext, ". + "qa.answer as answertext, q.id as questionid,". + " 0 as glossaryentryid,'' as attachment"; + } + + return game_questions_shortanswer_question_fraction( $table, $fields, $select); } -//used by cross -function game_questions_shortanswer_question( $game) -{ - if( $game->questioncategoryid == 0){ +// Used by cross. +function game_questions_shortanswer_question( $game) { + if ($game->questioncategoryid == 0) { print_error( get_string( 'must_select_questioncategory', 'game')); } - - //include subcategories - $select = 'q.category='.$game->questioncategoryid; - if( $game->subcategories){ + + // Include subcategories. + $select = 'q.category='.$game->questioncategoryid; + if ($game->subcategories) { $cats = question_categorylist( $game->questioncategoryid); - if( count( $cats)){ + if (count( $cats)) { $select = 'q.category in ('.implode(',', $cats).')'; } - } - - $select .= " AND qtype='shortanswer' ". - " AND qa.question=q.id". - " AND q.hidden=0"; - $table = "{question} q,{question_answers} qa"; - $fields = "qa.id as qaid, q.id, q.questiontext as questiontext, ". - "qa.answer as answertext, q.id as questionid"; - - return game_questions_shortanswer_question_fraction( $table, $fields, $select); -} - -function game_questions_shortanswer_question_fraction( $table, $fields, $select) -{ + } + + $select .= " AND qtype='shortanswer' ". + " AND qa.question=q.id". + " AND q.hidden=0"; + $table = "{question} q,{question_answers} qa"; + $fields = "qa.id as qaid, q.id, q.questiontext as questiontext, ". + "qa.answer as answertext, q.id as questionid"; + + return game_questions_shortanswer_question_fraction( $table, $fields, $select); +} + +function game_questions_shortanswer_question_fraction( $table, $fields, $select) { + global $DB; + + $sql = "SELECT $fields FROM $table WHERE $select ORDER BY fraction DESC"; + + $recs = $DB->get_records_sql( $sql); + if ($recs == false) { + print_error( get_string( 'no_questions', 'game')); + } + + $recs2 = array(); + $map = array(); + foreach ($recs as $rec) { + if (array_key_exists( $rec->questionid, $map)) { + continue; + } + $rec2 = new stdClass(); + $rec2->id = $rec->id; + $rec2->questiontext = $rec->questiontext; + $rec2->answertext = $rec->answertext; + $rec2->questionid = $rec->questionid; + $rec2->glossaryentryid = 0; + $rec2->attachment = ''; + $recs2[] = $rec2; + + $map[ $rec->questionid] = $rec->questionid; + } + + return $recs2; +} + +function game_setchar( &$s, $pos, $char) { + $ret = ""; + + if ($pos > 0) { + $ret .= game_substr( $s, 0, $pos); + } + + $s = $ret . $char . game_substr( $s, $pos + 1); +} + +function game_insert_record( $table, $rec) { global $DB; - - $sql = "SELECT $fields FROM ".$table." WHERE $select ORDER BY fraction DESC"; - - $recs = $DB->get_records_sql( $sql); - if( $recs == false){ - print_error( get_string( 'no_questions', 'game')); - } - - $recs2 = array(); - $map = array(); - foreach( $recs as $rec){ - if( array_key_exists( $rec->questionid, $map)){ - continue; - } - $rec2 = new stdClass(); - $rec2->id = $rec->id; - $rec2->questiontext = $rec->questiontext; - $rec2->answertext = $rec->answertext; - $rec2->questionid = $rec->questionid; - $rec2->glossaryentryid = 0; - $rec2->attachment = ''; - $recs2[] = $rec2; - - $map[ $rec->questionid] = $rec->questionid; - } - - return $recs2; -} - - - function game_setchar( &$s, $pos, $char) - { - $ret = ""; - - if( $pos > 0){ - $ret .= game_substr( $s, 0, $pos); - } - - $s = $ret . $char . game_substr( $s, $pos+1); - } - - - function game_insert_record( $table, $rec) - { - global $DB; - - if( $DB->get_record($table, array('id' => $rec->id), 'id,id') == false){ - $sql = 'INSERT INTO {'.$table.'}(id) VALUES('.$rec->id.')'; - if( !$DB->execute( $sql)){ - print_error( "Cannot insert an empty $table with id=$rec->id"); - return false; - } - } - if( isset( $rec->question)){ - $temp = $rec->question; - $rec->question = addslashes( $rec->question); - } - $ret = $DB->update_record( $table, $rec); - - if( isset( $rec->question)){ - $rec->question = $temp; - } - - return $ret; - } - - //if score is negative doesn't update the record - //score is between 0 and 1 - function game_updateattempts( $game, $attempt, $score, $finished) - { - global $DB, $USER; - - if( $attempt != false){ - $updrec = new stdClass(); - $updrec->id = $attempt->id; - $updrec->timelastattempt = time(); - $updrec->lastip = getremoteaddr(); - if( isset( $_SERVER[ 'REMOTE_HOST'])){ - $updrec->lastremotehost = $_SERVER[ 'REMOTE_HOST']; - } - else{ - $updrec->lastremotehost = gethostbyaddr( $updrec->lastip); - } - $updrec->lastip = substr( $updrec->lastip, 0, 30); - $updrec->lastremotehost = substr( $updrec->lastremotehost, 0, 50); - - if( $score >= 0){ - $updrec->score = $score; - } - - if( $finished){ - $updrec->timefinish = $updrec->timelastattempt; - } - - $updrec->attempts = $attempt->attempts + 1; - - if( !$DB->update_record( 'game_attempts', $updrec)){ - print_error( "game_updateattempts: Can't update game_attempts id=$updrec->id"); - } - - // update grade item and send all grades to gradebook - $grades = new stdClass(); - $grades->userid = $USER->id; - $grades->rawgrade = game_score_to_grade($score, $game); - $grades->datesubmitted = time(); - game_grade_item_update( $game, $grades); - game_update_grades( $game, $grades->userid); - } - - //Update table game_grades - if( $finished){ - game_save_best_score( $game); - } - } - - function game_updateattempts_maxgrade( $game, $attempt, $grade, $finished) - { - global $DB; - - $recgrade = $DB->get_field( 'game_attempts', 'score', array( 'id' => $attempt->id)); - - if( $recgrade > $grade){ - $grade = -1; //don't touch the grade - } - - game_updateattempts( $game, $attempt, $grade, $finished); - } - - function game_update_queries( $game, $attempt, $query, $score, $studentanswer, $updatetries=false) - { - global $DB, $USER; - - if( $query->id != 0){ - $select = "id=$query->id"; - }else - { - $select = "attemptid = $attempt->id AND sourcemodule = '{$query->sourcemodule}'"; - switch( $query->sourcemodule) - { - case 'quiz': - $select .= " AND questionid='$query->questionid' "; - break; - case 'glossary': - $select .= " AND glossaryentryid='$query->glossaryentryid'"; - break; - } - } - - if( ($recq = $DB->get_record_select( 'game_queries', $select)) === false) - { - $recq = new stdClass(); - $recq->gamekind = $game->gamekind; - $recq->gameid = $attempt->gameid; - $recq->userid = $attempt->userid; - $recq->attemptid = $attempt->id; - $recq->sourcemodule = $query->sourcemodule; - $recq->questionid = $query->questionid; - $recq->glossaryentryid = $query->glossaryentryid; - if ($updatetries) - $recq->tries = 1; - - if (!($recq->id = $DB->insert_record( 'game_queries', $recq))){ - print_error( 'Insert page: new page game_queries not inserted'); - } - } - - $updrec = new stdClass(); - $updrec->id = $recq->id; - $updrec->timelastattempt = time(); - - if( $score >= 0){ + + if ($DB->get_record($table, array('id' => $rec->id), 'id,id') == false) { + $sql = 'INSERT INTO {'.$table.'}(id) VALUES('.$rec->id.')'; + if (!$DB->execute( $sql)) { + print_error( "Cannot insert an empty $table with id=$rec->id"); + return false; + } + } + + if (isset( $rec->question)) { + $temp = $rec->question; + $rec->question = addslashes( $rec->question); + } + $ret = $DB->update_record( $table, $rec); + + if (isset( $rec->question)) { + $rec->question = $temp; + } + + return $ret; +} + +// If score is negative doesn't update the record score is between 0 and 1. +function game_updateattempts( $game, $attempt, $score, $finished) { + global $DB, $USER; + + if ($attempt != false) { + $updrec = new stdClass(); + $updrec->id = $attempt->id; + $updrec->timelastattempt = time(); + $updrec->lastip = getremoteaddr(); + if (isset( $_SERVER[ 'REMOTE_HOST'])) { + $updrec->lastremotehost = $_SERVER[ 'REMOTE_HOST']; + } else { + $updrec->lastremotehost = gethostbyaddr( $updrec->lastip); + } + $updrec->lastip = substr( $updrec->lastip, 0, 30); + $updrec->lastremotehost = substr( $updrec->lastremotehost, 0, 50); + + if ($score >= 0) { $updrec->score = $score; } - - if( $studentanswer != ''){ - $updrec->studentanswer = $studentanswer; - } - - if ($updatetries) - $updrec->tries = $recq->tries + 1; - - if (!($DB->update_record( 'game_queries', $updrec))){ - print_error( "game_update_queries: not updated id=$updrec->id"); - } - } - - - function game_getattempt( $game, &$detail, $autoadd=false) - { - global $DB, $USER; - - $select = "gameid=$game->id AND userid=$USER->id and timefinish=0 "; - if( $USER->id == 1){ - $key = 'mod/game:instanceid'.$game->id; - if( array_key_exists( $key, $_SESSION)){ - $select .= ' AND id="'.$_SESSION[ $key].'"'; - }else{ - $select .= ' AND id=-1'; - } - } - - if( ($recs=$DB->get_records_select( 'game_attempts', $select))){ - foreach( $recs as $attempt){ - if( $USER->id == 1){ - $_SESSION[ $key] = $attempt->id; - } - - $detail = $DB->get_record( 'game_'.$game->gamekind, array( 'id' => $attempt->id)); - - return $attempt; - } - }; - - if( $autoadd) - { - game_addattempt( $game); - return game_getattempt( $game, $detail, false); - } - - return false; - } + + if ($finished) { + $updrec->timefinish = $updrec->timelastattempt; + } + + $updrec->attempts = $attempt->attempts + 1; + + if (!$DB->update_record( 'game_attempts', $updrec)) { + print_error( "game_updateattempts: Can't update game_attempts id=$updrec->id"); + } + + // Update grade item and send all grades to gradebook. + $grades = new stdClass(); + $grades->userid = $USER->id; + $grades->rawgrade = game_score_to_grade($score, $game); + $grades->datesubmitted = time(); + game_grade_item_update( $game, $grades); + game_update_grades( $game, $grades->userid); + } + + // Update table game_grades. + if ($finished) { + game_save_best_score( $game); + } +} + +function game_updateattempts_maxgrade( $game, $attempt, $grade, $finished) { + global $DB; + + $recgrade = $DB->get_field( 'game_attempts', 'score', array( 'id' => $attempt->id)); + + if ($recgrade > $grade) { + $grade = -1; // Don't touch the grade. + } + + game_updateattempts( $game, $attempt, $grade, $finished); +} + +function game_update_queries( $game, $attempt, $query, $score, $studentanswer, $updatetries=false) { + global $DB, $USER; + + if ($query->id != 0) { + $select = "id=$query->id"; + } else { + $select = "attemptid = $attempt->id AND sourcemodule = '{$query->sourcemodule}'"; + switch ($query->sourcemodule) { + case 'quiz': + $select .= " AND questionid='$query->questionid' "; + break; + case 'glossary': + $select .= " AND glossaryentryid='$query->glossaryentryid'"; + break; + } + } + + if (($recq = $DB->get_record_select( 'game_queries', $select)) === false) { + $recq = new stdClass(); + $recq->gamekind = $game->gamekind; + $recq->gameid = $attempt->gameid; + $recq->userid = $attempt->userid; + $recq->attemptid = $attempt->id; + $recq->sourcemodule = $query->sourcemodule; + $recq->questionid = $query->questionid; + $recq->glossaryentryid = $query->glossaryentryid; + if ($updatetries) { + $recq->tries = 1; + } + + if (!($recq->id = $DB->insert_record( 'game_queries', $recq))) { + print_error( 'Insert page: new page game_queries not inserted'); + } + } + + $updrec = new stdClass(); + $updrec->id = $recq->id; + $updrec->timelastattempt = time(); + + if ($score >= 0) { + $updrec->score = $score; + } + + if ($studentanswer != '') { + $updrec->studentanswer = $studentanswer; + } + + if ($updatetries) { + $updrec->tries = $recq->tries + 1; + } + + if (!($DB->update_record( 'game_queries', $updrec))) { + print_error( "game_update_queries: not updated id=$updrec->id"); + } +} + +function game_getattempt( $game, &$detail, $autoadd=false) { + global $DB, $USER; + + $select = "gameid=$game->id AND userid=$USER->id and timefinish=0 "; + if ($USER->id == 1) { + $key = 'mod/game:instanceid'.$game->id; + if (array_key_exists( $key, $_SESSION)) { + $select .= ' AND id="'.$_SESSION[ $key].'"'; + } else { + $select .= ' AND id=-1'; + } + } + + if (($recs = $DB->get_records_select( 'game_attempts', $select))) { + foreach ($recs as $attempt) { + if ($USER->id == 1) { + $_SESSION[ $key] = $attempt->id; + } + + $detail = $DB->get_record( 'game_'.$game->gamekind, array( 'id' => $attempt->id)); + + return $attempt; + } + } + + if ($autoadd) { + game_addattempt( $game); + return game_getattempt( $game, $detail, false); + } + + return false; +} /** * @param integer $gameid the game id. @@ -885,13 +845,13 @@ function game_questions_shortanswer_question_fraction( $table, $fields, $select) function game_get_user_attempts( $gameid, $userid, $status = 'finished') { global $DB; - $status_condition = array( + $statuscondition = array( 'all' => '', 'finished' => ' AND timefinish > 0', 'unfinished' => ' AND timefinish = 0' ); if ($attempts = $DB->get_records_select( 'game_attempts', - "gameid = ? AND userid = ? AND preview = 0" . $status_condition[$status], + "gameid = ? AND userid = ? AND preview = 0" . $statuscondition[$status], array( $gameid, $userid), 'attempt ASC')) { return $attempts; } else { @@ -934,25 +894,23 @@ function game_get_best_score($game, $userid) { if (is_numeric($score)) { return $score; } else { - return NULL; + return null; } } function game_get_best_grade($game, $userid) { $score = game_get_best_score( $game, $userid); - - if( is_numeric( $score)){ - return round( $score * $game->grade, $game->decimalpoints); - }else - { - return NULL; + + if (is_numeric( $score)) { + return round( $score * $game->grade, $game->decimalpoints); + } else { + return null; } } - function game_score_to_grade($score, $game) { if ($score) { - return round($score*$game->grade, $game->decimalpoints); + return round($score * $game->grade, $game->decimalpoints); } else { return 0; } @@ -973,12 +931,12 @@ function game_get_reviewoptions($game, $attempt, $context=null) { $options = new stdClass; $options->readonly = true; - // Provide the links to the question review and comment script + + // Provide the links to the question review and comment script. $options->questionreviewlink = '/mod/game/reviewquestion.php'; - if ($context /* && has_capability('mod/game:viewreports', $context) */ and !$attempt->preview) { - // The teacher should be shown everything except during preview when the teachers - // wants to see just what the students see + if ($context and !$attempt->preview) { + // The teacher should be shown everything except during preview when the teachers wants to see just what the students see. $options->responses = true; $options->scores = true; $options->feedback = true; @@ -987,48 +945,47 @@ function game_get_reviewoptions($game, $attempt, $context=null) { $options->generalfeedback = true; $options->overallfeedback = true; - // Show a link to the comment box only for closed attempts + // Show a link to the comment box only for closed attempts. if ($attempt->timefinish) { $options->questioncommentlink = '/mod/game/comment.php'; } } else { - if (((time() - $attempt->timefinish) < 120) || $attempt->timefinish==0) { - $game_state_mask = GAME_REVIEW_IMMEDIATELY; + if (((time() - $attempt->timefinish) < 120) || $attempt->timefinish == 0) { + $gamestatemask = GAME_REVIEW_IMMEDIATELY; } else if (!$game->timeclose or time() < $game->timeclose) { - $game_state_mask = GAME_REVIEW_OPEN; + $gamestatemask = GAME_REVIEW_OPEN; } else { - $game_state_mask = GAME_REVIEW_CLOSED; + $gamestatemask = GAME_REVIEW_CLOSED; } - $options->responses = ($game->review & $game_state_mask & GAME_REVIEW_RESPONSES) ? 1 : 0; - $options->scores = ($game->review & $game_state_mask & GAME_REVIEW_SCORES) ? 1 : 0; - $options->feedback = ($game->review & $game_state_mask & GAME_REVIEW_FEEDBACK) ? 1 : 0; - $options->correct_responses = ($game->review & $game_state_mask & GAME_REVIEW_ANSWERS) ? 1 : 0; - $options->solutions = ($game->review & $game_state_mask & GAME_REVIEW_SOLUTIONS) ? 1 : 0; - $options->generalfeedback = ($game->review & $game_state_mask & GAME_REVIEW_GENERALFEEDBACK) ? 1 : 0; - $options->overallfeedback = $attempt->timefinish && ($game->review & $game_state_mask & GAME_REVIEW_FEEDBACK); + $options->responses = ($game->review & $gamestatemask & GAME_REVIEW_RESPONSES) ? 1 : 0; + $options->scores = ($game->review & $gamestatemask & GAME_REVIEW_SCORES) ? 1 : 0; + $options->feedback = ($game->review & $gamestatemask & GAME_REVIEW_FEEDBACK) ? 1 : 0; + $options->correct_responses = ($game->review & $gamestatemask & GAME_REVIEW_ANSWERS) ? 1 : 0; + $options->solutions = ($game->review & $gamestatemask & GAME_REVIEW_SOLUTIONS) ? 1 : 0; + $options->generalfeedback = ($game->review & $gamestatemask & GAME_REVIEW_GENERALFEEDBACK) ? 1 : 0; + $options->overallfeedback = $attempt->timefinish && ($game->review & $gamestatemask & GAME_REVIEW_FEEDBACK); } return $options; } - -function game_compute_attempt_layout( $game, &$attempt) -{ +function game_compute_attempt_layout( $game, &$attempt) { global $DB; - $ret = ''; - $recs = $DB->get_records_select( 'game_queries', "attemptid=$attempt->id", null, '', 'id,questionid,sourcemodule,glossaryentryid'); - if( $recs){ - foreach( $recs as $rec){ - if( $rec->sourcemodule == 'glossary'){ - $ret .= $rec->glossaryentryid.'G,'; - }else{ - $ret .= $rec->questionid.','; - } - } - } - - $attempt->layout = $ret.'0'; + $ret = ''; + $recs = $DB->get_records_select( 'game_queries', "attemptid=$attempt->id", null, '', + 'id,questionid,sourcemodule,glossaryentryid'); + if ($recs) { + foreach ($recs as $rec) { + if ($rec->sourcemodule == 'glossary') { + $ret .= $rec->glossaryentryid.'G,'; + } else { + $ret .= $rec->questionid.','; + } + } + } + + $attempt->layout = $ret.'0'; } /** @@ -1074,15 +1031,15 @@ function game_get_combined_reviewoptions($game, $attempts, $context=null) { function game_save_best_score($game) { global $DB, $USER; - // Get all the attempts made by the user + // Get all the attempts made by the user. if (!$attempts = game_get_user_attempts( $game->id, $USER->id, 'all')) { print_error( 'Could not find any user attempts gameid='.$game->id.' userid='.$USER->id); } - // Calculate the best grade + // Calculate the best grade. $bestscore = game_calculate_best_score( $game, $attempts); - // Save the best grade in the database + // Save the best grade in the database. if ($grade = $DB->get_record('game_grades', array( 'gameid' => $game->id, 'userid' => $USER->id))) { $grade->score = $bestscore; $grade->timemodified = time(); @@ -1099,8 +1056,8 @@ function game_save_best_score($game) { print_error( 'Could not insert new best grade'); } } - - // update gradebook + + // Updates gradebook. $grades = new stdClass(); $grades->userid = $USER->id; $grades->rawgrade = game_score_to_grade($bestscore, $game); @@ -1111,28 +1068,25 @@ function game_save_best_score($game) { } /** -* Calculate the overall score for a game given a number of attempts by a particular user. -* -* @return double The overall score -* @param object $game The game for which the best score is to be calculated -* @param array $attempts An array of all the attempts of the user at the game -*/ + * Calculate the overall score for a game given a number of attempts by a particular user. + * + * @return double The overall score + * @param object $game The game for which the best score is to be calculated + * @param array $attempts An array of all the attempts of the user at the game + */ function game_calculate_best_score($game, $attempts) { switch ($game->grademethod) { - case GAME_GRADEMETHOD_FIRST: foreach ($attempts as $attempt) { return $attempt->score; } break; - case GAME_GRADEMETHOD_LAST: foreach ($attempts as $attempt) { $final = $attempt->score; } return $final; - case GAME_GRADEMETHOD_AVERAGE: $sum = 0; $count = 0; @@ -1140,8 +1094,7 @@ function game_calculate_best_score($game, $attempts) { $sum += $attempt->score; $count++; } - return (float)$sum/$count; - + return (float)$sum / $count; default: case GAME_GRADEMETHOD_HIGHEST: $max = 0; @@ -1155,14 +1108,14 @@ function game_calculate_best_score($game, $attempts) { } /** -* Return the attempt with the best score for a game -* -* Which attempt is the best depends on $game->grademethod. If the grade -* method is GRADEAVERAGE then this function simply returns the last attempt. -* @return object The attempt with the best grade -* @param object $game The game for which the best grade is to be calculated -* @param array $attempts An array of all the attempts of the user at the game -*/ + * Return the attempt with the best score for a game + * + * Which attempt is the best depends on $game->grademethod. If the grade + * method is GRADEAVERAGE then this function simply returns the last attempt. + * @return object The attempt with the best grade + * @param object $game The game for which the best grade is to be calculated + * @param array $attempts An array of all the attempts of the user at the game + */ function game_calculate_best_attempt($game, $attempts) { switch ($game->grademethod) { @@ -1173,7 +1126,7 @@ function game_calculate_best_attempt($game, $attempts) { } break; - case GAME_GRADEAVERAGE: // need to do something with it :-) + case GAME_GRADEAVERAGE: // Need to do something with it. case GAME_ATTEMPTLAST: foreach ($attempts as $attempt) { $final = $attempt; @@ -1195,25 +1148,25 @@ function game_calculate_best_attempt($game, $attempts) { /** -* Loads the most recent state of each question session from the database -* -* For each question the most recent session state for the current attempt -* is loaded from the game_questions table and the question type specific data -* -* @return array An array of state objects representing the most recent -* states of the question sessions. -* @param array $questions The questions for which sessions are to be restored or -* created. -* @param object $cmoptions -* @param object $attempt The attempt for which the question sessions are -* to be restored or created. -* @param mixed either the id of a previous attempt, if this attmpt is -* building on a previous one, or false for a clean attempt. -*/ + * Loads the most recent state of each question session from the database + * + * For each question the most recent session state for the current attempt + * is loaded from the game_questions table and the question type specific data + * + * @return array An array of state objects representing the most recent + * states of the question sessions. + * @param array $questions The questions for which sessions are to be restored or + * created. + * @param object $cmoptions + * @param object $attempt The attempt for which the question sessions are + * to be restored or created. + * @param mixed either the id of a previous attempt, if this attmpt is + * building on a previous one, or false for a clean attempt. + */ function game_get_question_states(&$questions, $cmoptions, $attempt, $lastattemptid = false) { global $DB, $QTYPES; - // get the question ids + // Get the question ids. $ids = array_keys( $questions); $questionlist = implode(',', $ids); @@ -1224,204 +1177,210 @@ function game_get_question_states(&$questions, $cmoptions, $attempt, $lastattemp " WHERE attemptid = '$attempt->id'". " AND questionid IN ($questionlist)"; $states = $DB->get_records_sql($sql); - - // loop through all questions and set the last_graded states - foreach ($ids as $i) { - // Create the empty question type specific information + + // Loops through all questions and set the last_graded states. + foreach ($ids as $i) { + // Creates the empty question type specific information. if (!$QTYPES[$questions[$i]->qtype]->create_session_and_responses( - $questions[$i], $states[$i], $cmoptions, $attempt)) { - return false; - } + $questions[$i], $states[$i], $cmoptions, $attempt)) { + return false; + } - $states[$i]->last_graded = clone($states[$i]); + $states[$i]->last_graded = clone($states[$i]); } + return $states; } -function game_sudoku_getquestions( $questionlist) -{ +function game_sudoku_getquestions( $questionlist) { global $CFG, $DB; - // Load the questions - $sql = "SELECT q.*,qmo.single FROM {$CFG->prefix}question LEFT JOIN {$CFG->prefix}qtype_multichoice_options qmo ON q.id=qmo.questionid AND q.qtype='multichoice' WHERE q.id IN ($questionlist)"; + // Load the questions. + $sql = "SELECT q.*,qmo.single ". + " FROM {$CFG->prefix}question ". + " LEFT JOIN {$CFG->prefix}qtype_multichoice_options qmo ON q.id=qmo.questionid AND q.qtype='multichoice' ". + " WHERE q.id IN ($questionlist)"; if (!$questions = $DB->get_records_select( 'question', "id IN ($questionlist)")) { print_error( get_string( 'no_questions', 'game')); } - // Load the question type specific information + // Load the question type specific information. if (!get_question_options($questions)) { print_error('Could not load question options'); } - + return $questions; } -function game_filterglossary( $text, $entryid, $contextid, $courseid) -{ +function game_filterglossary( $text, $entryid, $contextid, $courseid) { global $CFG, $DB; - for(;;) - { - $find='@@PLUGINFILE@@'; + for (;;) { + $find = '@@PLUGINFILE@@'; $pos = strpos( $text, $find); - if( $pos === false) + if ($pos === false) { break; - - $pos2 = strpos( $text,'/', $pos); - if( $pos2 === false) + } + + $pos2 = strpos( $text, '/', $pos); + if ($pos2 === false) { break; - - $pos3 = strpos( $text,'"', $pos); - if( $pos3 === false) + } + + $pos3 = strpos( $text, '"', $pos); + if ($pos3 === false) { break; - - $file = substr( $text, $pos2+1, $pos3-$pos2-1); - + } + + $file = substr( $text, $pos2 + 1, $pos3 - $pos2 - 1); + $new = $CFG->wwwroot."/pluginfile.php/$contextid/mod_glossary/entry/$entryid/$file"; - $text = substr( $text, 0, $pos).$new.substr( $text,$pos3); + $text = substr( $text, 0, $pos).$new.substr( $text, $pos3); } + $questiontext = str_replace( '$$'.'\\'.'\\'.'frac', '$$\\'.'frac', $text); return game_filtertext( $text, $courseid); - } -function game_filterbook( $text, $chapterid, $contextid, $courseid) -{ +function game_filterbook( $text, $chapterid, $contextid, $courseid) { global $CFG, $DB; - for(;;) - { - $find='@@PLUGINFILE@@'; + for (;;) { + $find = '@@PLUGINFILE@@'; $pos = strpos( $text, $find); - if( $pos === false) + if ($pos === false) { break; - - $pos2 = strpos( $text,'/', $pos); - if( $pos2 === false) + } + + $pos2 = strpos( $text, '/', $pos); + if ($pos2 === false) { break; - - $pos3 = strpos( $text,'"', $pos); - if( $pos3 === false) + } + + $pos3 = strpos( $text, '"', $pos); + if ($pos3 === false) { break; - - $file = substr( $text, $pos2+1, $pos3-$pos2-1); - + } + + $file = substr( $text, $pos2 + 1, $pos3 - $pos2 - 1); + $new = $CFG->wwwroot."/pluginfile.php/$contextid/mod_book/chapter/$chapterid/$file"; - $text = substr( $text, 0, $pos).$new.substr( $text,$pos3); + $text = substr( $text, 0, $pos).$new.substr( $text, $pos3); } + $questiontext = str_replace( '$$'.'\\'.'\\'.'frac', '$$\\'.'frac', $text); return game_filtertext( $text, $courseid); - } -function game_filterquestion( $questiontext, $questionid, $contextid, $courseid) -{ +function game_filterquestion( $questiontext, $questionid, $contextid, $courseid) { global $CFG, $DB; - for(;;) - { - $find='@@PLUGINFILE@@'; + for (;;) { + $find = '@@PLUGINFILE@@'; $pos = strpos( $questiontext, $find); - if( $pos === false) + if ($pos === false) { break; - - $pos2 = strpos( $questiontext,'/', $pos); - if( $pos2 === false) + } + + $pos2 = strpos( $questiontext, '/', $pos); + if ($pos2 === false) { break; - - $pos3 = strpos( $questiontext,'"', $pos); - if( $pos3 === false) + } + + $pos3 = strpos( $questiontext, '"', $pos); + if ($pos3 === false) { break; - - $file = substr( $questiontext, $pos2+1, $pos3-$pos2-1); - + } + + $file = substr( $questiontext, $pos2 + 1, $pos3 - $pos2 - 1); + $new = $CFG->wwwroot."/pluginfile.php/$contextid/mod_game/questiontext/$questionid/$file"; - $questiontext = substr( $questiontext, 0, $pos).$new.substr( $questiontext,$pos3); + $questiontext = substr( $questiontext, 0, $pos).$new.substr( $questiontext, $pos3); } + $questiontext = str_replace( '$$'.'\\'.'\\'.'frac', '$$\\'.'frac', $questiontext); return game_filtertext( $questiontext, $courseid); - } -function game_filterquestion_answer( $questiontext, $questionid, $contextid, $courseid) -{ +function game_filterquestion_answer( $questiontext, $questionid, $contextid, $courseid) { global $CFG, $DB; - for(;;) - { - $find='@@PLUGINFILE@@'; + for (;;) { + $find = '@@PLUGINFILE@@'; $pos = strpos( $questiontext, $find); - if( $pos === false) + if ($pos === false) { break; - - $pos2 = strpos( $questiontext,'/', $pos); - if( $pos2 === false) + } + + $pos2 = strpos( $questiontext, '/', $pos); + if ($pos2 === false) { break; - - $pos3 = strpos( $questiontext,'"', $pos); - if( $pos3 === false) + } + + $pos3 = strpos( $questiontext, '"', $pos); + if ($pos3 === false) { break; - - $file = substr( $questiontext, $pos2+1, $pos3-$pos2-1); - + } + + $file = substr( $questiontext, $pos2 + 1, $pos3 - $pos2 - 1); + $new = $CFG->wwwroot."/pluginfile.php/$contextid/mod_game/answer/$questionid/$file"; - $questiontext = substr( $questiontext, 0, $pos).$new.substr( $questiontext,$pos3); + $questiontext = substr( $questiontext, 0, $pos).$new.substr( $questiontext, $pos3); } - + return game_filtertext( $questiontext, $courseid); } -function game_filtertext( $text, $courseid){ +function game_filtertext( $text, $courseid) { $formatoptions = new stdClass(); $formatoptions->noclean = true; - $formatoptions->filter = 1; + $formatoptions->filter = 1; $text = trim( format_text( $text, FORMAT_MOODLE, $formatoptions)); $start = '
'; - if( substr( $text, 0, strlen( $start)) == $start){ - if( substr( $text, -6) == '
'){ + if (substr( $text, 0, strlen( $start)) == $start) { + if (substr( $text, -6) == '') { $text = substr( $text, strlen( $start), -6); } } - if( substr( $text, 0, 3) == '

'){ - if( substr( $text, -4) == '

'){ + if (substr( $text, 0, 3) == '

') { + if (substr( $text, -4) == '

') { $text = substr( $text, 3, -4); } } - + return $text; } -function game_tojavascriptstring( $text) -{ - $from = array('"',"\r", "\n"); +function game_tojavascriptstring( $text) { + $from = array('"', "\r", "\n"); $to = array('\"', ' ', ' '); - + $from[] = '