Browse Source

Fix:Coding style

MOODLE_20_STABLE
Vasilis Daloukas 9 years ago
parent
commit
7b957611bd
  1. 144
      headergame.php
  2. 405
      mod_form.php
  3. 72
      pagelib.php
  4. 120
      preview.php
  5. 135
      print.php
  6. 131
      report.php
  7. 610
      review.php
  8. 19
      settings.php
  9. 446
      showanswers.php
  10. 454
      showattempts.php
  11. 42
      tabs.php
  12. 379
      translate.php
  13. 39
      version.php
  14. 535
      view.php

144
headergame.php

@ -1,82 +1,92 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once(dirname(__FILE__) . '/../../config.php'); require_once(dirname(__FILE__) . '/../../config.php');
require_once($CFG->libdir.'/gradelib.php'); require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->dirroot.'/mod/game/locallib.php'); require_once($CFG->dirroot.'/mod/game/locallib.php');
require_once($CFG->libdir . '/completionlib.php'); require_once($CFG->libdir . '/completionlib.php');
$id = optional_param('id', 0, PARAM_INT); // Course Module ID, or $id = optional_param('id', 0, PARAM_INT); // Course Module ID.
$q = optional_param('q', 0, PARAM_INT); // game ID $q = optional_param('q', 0, PARAM_INT); // Game ID.
if ($id) { if ($id) {
if (! $cm = get_coursemodule_from_id('game', $id)) { if (!$cm = get_coursemodule_from_id('game', $id)) {
print_error('invalidcoursemodule'); print_error('invalidcoursemodule');
}
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
print_error('coursemisconf');
}
if (! $game = $DB->get_record('game', array('id' => $cm->instance))) {
print_error('invalidcoursemodule');
}
} else {
if (! $game = $DB->get_record('game', array('id' => $q))) {
print_error('invalidgameid q='.$q, 'game');
}
if (! $course = $DB->get_record('course', array('id' => $game->course))) {
print_error('invalidcourseid');
}
if (! $cm = get_coursemodule_from_instance('game', $game->id, $course->id)) {
print_error('invalidcoursemodule');
}
} }
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
print_error('coursemisconf');
}
if (! $game = $DB->get_record('game', array('id' => $cm->instance))) {
print_error('invalidcoursemodule');
}
} else {
if (! $game = $DB->get_record('game', array('id' => $q))) {
print_error('invalidgameid q='.$q, 'game');
}
if (!$course = $DB->get_record('course', array('id' => $game->course))) {
print_error('invalidcourseid');
}
if (!$cm = get_coursemodule_from_instance('game', $game->id, $course->id)) {
print_error('invalidcoursemodule');
}
}
/// Check login and get context. // Check login and get context.
require_login($course->id, false, $cm); require_login($course->id, false, $cm);
$context = game_get_context_module_instance( $cm->id); $context = game_get_context_module_instance( $cm->id);
require_capability('mod/game:view', $context); require_capability('mod/game:view', $context);
/// Cache some other capabilites we use several times.
$canattempt = has_capability('mod/game:attempt', $context);
$canreviewmine = has_capability('mod/game:reviewmyattempts', $context);
/// Create an object to manage all the other (non-roles) access rules. // Cache some other capabilites we use several times.
$timenow = time(); $canattempt = has_capability('mod/game:attempt', $context);
//$accessmanager = new game_access_manager(game::create($game->id, $USER->id), $timenow); $canreviewmine = has_capability('mod/game:reviewmyattempts', $context);
/// If no questions have been set up yet redirect to edit.php // Create an object to manage all the other (non-roles) access rules.
//if (!$game->questions && has_capability('mod/game:manage', $context)) { $timenow = time();
// redirect($CFG->wwwroot . '/mod/game/edit.php?cmid=' . $cm->id);
//}
/// Log this request. // Log this request.
if( game_use_events()) if (game_use_events()) {
{ require( 'classes/event/course_module_viewed.php');
require( 'classes/event/course_module_viewed.php'); \mod_game\event\course_module_viewed::viewed($game, $context)->trigger();
\mod_game\event\course_module_viewed::viewed($game, $context)->trigger(); } else {
}else add_to_log($course->id, 'game', 'view', "view.php?id=$cm->id", $game->id, $cm->id);
add_to_log($course->id, 'game', 'view', "view.php?id=$cm->id", $game->id, $cm->id); }
/// Initialize $PAGE, compute blocks // Initialize $PAGE, compute blocks.
$PAGE->set_url('/mod/game/view.php', array('id' => $cm->id)); $PAGE->set_url('/mod/game/view.php', array('id' => $cm->id));
$edit = optional_param('edit', -1, PARAM_BOOL); $edit = optional_param('edit', -1, PARAM_BOOL);
if ($edit != -1 && $PAGE->user_allowed_editing()) { if ($edit != -1 && $PAGE->user_allowed_editing()) {
$USER->editing = $edit; $USER->editing = $edit;
} }
// Note: MDL-19010 there will be further changes to printing header and blocks. // Note: MDL-19010 there will be further changes to printing header and blocks.
// The code will be much nicer than this eventually. // The code will be much nicer than this eventually.
$title = $course->shortname . ': ' . format_string($game->name); $title = $course->shortname . ': ' . format_string($game->name);
if ($PAGE->user_allowed_editing() && !empty($CFG->showblocksonmodpages)) { if ($PAGE->user_allowed_editing() && !empty($CFG->showblocksonmodpages)) {
$buttons = '<table><tr><td><form method="get" action="view.php"><div>'. $buttons = '<table><tr><td><form method="get" action="view.php"><div>'.
'<input type="hidden" name="id" value="'.$cm->id.'" />'. '<input type="hidden" name="id" value="'.$cm->id.'" />'.
'<input type="hidden" name="edit" value="'.($PAGE->user_is_editing()?'off':'on').'" />'. '<input type="hidden" name="edit" value="'.($PAGE->user_is_editing() ? 'off' : 'on').'" />'.
'<input type="submit" value="'.get_string($PAGE->user_is_editing()?'blockseditoff':'blocksediton').'" /></div></form></td></tr></table>'; '<input type="submit" value="'.
$PAGE->set_button($buttons); get_string($PAGE->user_is_editing() ? 'blockseditoff' : 'blocksediton').
} '" /></div></form></td></tr></table>';
$PAGE->set_button($buttons);
}
$PAGE->set_title($title); $PAGE->set_title($title);
$PAGE->set_heading($course->fullname); $PAGE->set_heading($course->fullname);
echo $OUTPUT->header(); echo $OUTPUT->header();

405
mod_form.php

@ -1,4 +1,19 @@
<?php // $Id: mod_form.php,v 1.28 2012/07/26 05:38:58 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* Form for creating and modifying a game * Form for creating and modifying a game
* *
@ -7,88 +22,84 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/ */
require_once ($CFG->dirroot.'/course/moodleform_mod.php'); require_once( $CFG->dirroot.'/course/moodleform_mod.php');
require( 'locallib.php'); require( 'locallib.php');
class mod_game_mod_form extends moodleform_mod { class mod_game_mod_form extends moodleform_mod {
function definition() {
global $CFG, $DB, $COURSE;
public function definition() {
global $CFG, $DB, $COURSE;
$config = get_config('game'); $config = get_config('game');
$mform =& $this->_form; $mform =& $this->_form;
$id = $this->_instance; $id = $this->_instance;
if(!empty($this->_instance)){ if (!empty($this->_instance)) {
if ($g = $DB->get_record('game', array('id' => $id))) {
if($g = $DB->get_record('game', array('id' => $id))){
$gamekind = $g->gamekind; $gamekind = $g->gamekind;
} else {
print_error('incorrect game');
} }
else{ } else {
print_error('incorrect game');
}
}
else {
$gamekind = required_param('type', PARAM_ALPHA); $gamekind = required_param('type', PARAM_ALPHA);
} }
//Hidden elements // Hidden elements.
$mform->addElement('hidden', 'gamekind', $gamekind); $mform->addElement('hidden', 'gamekind', $gamekind);
$mform->setDefault('gamekind', $gamekind); $mform->setDefault('gamekind', $gamekind);
$mform->setType('gamekind', PARAM_ALPHA); $mform->setType('gamekind', PARAM_ALPHA);
$mform->addElement('hidden', 'type', $gamekind); $mform->addElement('hidden', 'type', $gamekind);
$mform->setDefault('type', $gamekind); $mform->setDefault('type', $gamekind);
$mform->setType('type', PARAM_ALPHA); $mform->setType('type', PARAM_ALPHA);
$mform->addElement( 'hidden', 'gameversion', game_get_version()); $mform->addElement( 'hidden', 'gameversion', game_get_version());
$mform->setType('gameversion', PARAM_INT); $mform->setType('gameversion', PARAM_INT);
$mform->addElement('header', 'general', get_string('general', 'form')); $mform->addElement('header', 'general', get_string('general', 'form'));
$mform->addElement('text', 'name', 'Name', array('size'=>'64')); $mform->addElement('text', 'name', 'Name', array('size' => '64'));
if (!empty($CFG->formatstringstriptags)){ if (!empty($CFG->formatstringstriptags)) {
$mform->setType('name', PARAM_TEXT); $mform->setType('name', PARAM_TEXT);
} } else {
else{
$mform->setType('name', PARAM_CLEAN); $mform->setType('name', PARAM_CLEAN);
} }
if( !isset( $g)) if (!isset( $g)) {
$mform->setDefault('name', get_string( 'game_'.$gamekind, 'game')); $mform->setDefault('name', get_string( 'game_'.$gamekind, 'game'));
}
$mform->addRule('name', null, 'required', null, 'client'); $mform->addRule('name', null, 'required', null, 'client');
$hasglossary = ($gamekind == 'hangman' || $gamekind == 'cross' || $gamekind == 'cryptex' || $gamekind == 'sudoku' || $gamekind == 'hiddenpicture' || $gamekind == 'snakes'); $hasglossary = ($gamekind == 'hangman' || $gamekind == 'cross' ||
$gamekind == 'cryptex' || $gamekind == 'sudoku' ||
$gamekind == 'hiddenpicture' || $gamekind == 'snakes');
$questionsourceoptions = array(); $questionsourceoptions = array();
if($hasglossary) if ($hasglossary) {
$questionsourceoptions['glossary'] = get_string('modulename', 'glossary'); $questionsourceoptions['glossary'] = get_string('modulename', 'glossary');
//if( $gamekind != 'snakes' && $gamekind != 'sudoku' && }
// $gamekind != 'hiddenpicture') { $questionsourceoptions['question'] = get_string('sourcemodule_question', 'game');
$questionsourceoptions['question'] = get_string('sourcemodule_question', 'game'); if ($gamekind != 'bookquiz') {
//}
if( $gamekind != 'bookquiz')
$questionsourceoptions['quiz'] = get_string('modulename', 'quiz'); $questionsourceoptions['quiz'] = get_string('modulename', 'quiz');
$mform->addElement('select', 'sourcemodule', get_string('sourcemodule','game'), $questionsourceoptions); }
$mform->addElement('select', 'sourcemodule', get_string('sourcemodule', 'game'), $questionsourceoptions);
if($hasglossary){ if ($hasglossary) {
$a = array(); $a = array();
if($recs = $DB->get_records('glossary', array( 'course' => $COURSE->id), 'id,name')){ if ($recs = $DB->get_records('glossary', array( 'course' => $COURSE->id), 'id,name')) {
foreach($recs as $rec){ foreach ($recs as $rec) {
$a[$rec->id] = $rec->name; $a[$rec->id] = $rec->name;
} }
} }
$mform->addElement('select', 'glossaryid', get_string('sourcemodule_glossary', 'game'), $a); $mform->addElement('select', 'glossaryid', get_string('sourcemodule_glossary', 'game'), $a);
$mform->disabledIf('glossaryid', 'sourcemodule', 'neq', 'glossary'); $mform->disabledIf('glossaryid', 'sourcemodule', 'neq', 'glossary');
if( count( $a) == 0) if (count( $a) == 0) {
$select = 'glossaryid=-1'; $select = 'glossaryid=-1';
else if( count( $a) == 1) } else if (count( $a) == 1) {
$select = 'glossaryid='.$rec->id; $select = 'glossaryid='.$rec->id;
else } else {
{
$select = ''; $select = '';
foreach($recs as $rec){ foreach ($recs as $rec) {
$select .= ','.$rec->id; $select .= ','.$rec->id;
} }
$select = 'g.id IN ('.substr( $select, 1).')'; $select = 'g.id IN ('.substr( $select, 1).')';
@ -98,8 +109,8 @@ class mod_game_mod_form extends moodleform_mod {
$a = array(); $a = array();
$a[ ] = ''; $a[ ] = '';
$sql = "SELECT gc.id,gc.name,g.name as name2 FROM $table WHERE $select ORDER BY g.name,gc.name"; $sql = "SELECT gc.id,gc.name,g.name as name2 FROM $table WHERE $select ORDER BY g.name,gc.name";
if($recs = $DB->get_records_sql( $sql)){ if ($recs = $DB->get_records_sql( $sql)) {
foreach($recs as $rec){ foreach ($recs as $rec) {
$a[$rec->id] = $rec->name2.' -> '.$rec->name; $a[$rec->id] = $rec->name2.' -> '.$rec->name;
} }
} }
@ -107,41 +118,35 @@ class mod_game_mod_form extends moodleform_mod {
$mform->disabledIf('glossarycategoryid', 'sourcemodule', 'neq', 'glossary'); $mform->disabledIf('glossarycategoryid', 'sourcemodule', 'neq', 'glossary');
} }
// Question Category - Short Answer.
//********************* if ($gamekind != 'bookquiz') {
// Question Category - Short Answer
if( $gamekind != 'bookquiz'){
$context = game_get_context_course_instance( $COURSE->id); $context = game_get_context_course_instance( $COURSE->id);
$select = " contextid in ($context->id)"; $select = " contextid in ($context->id)";
$a = array(); $a = array();
if($recs = $DB->get_records_select('question_categories', $select, null, 'id,name')){ if ($recs = $DB->get_records_select('question_categories', $select, null, 'id,name')) {
foreach($recs as $rec){ foreach ($recs as $rec) {
$s = $rec->name; $s = $rec->name;
if(($count = $DB->count_records('question', array( 'category' => $rec->id))) != 0){ if (($count = $DB->count_records('question', array( 'category' => $rec->id))) != 0) {
$s .= " ($count)"; $s .= " ($count)";
} }
$a[$rec->id] = $s; $a[$rec->id] = $s;
} }
} }
$mform->addElement('select', 'questioncategoryid', get_string('sourcemodule_questioncategory', 'game'), $a); $mform->addElement('select', 'questioncategoryid', get_string('sourcemodule_questioncategory', 'game'), $a);
$mform->disabledIf('questioncategoryid', 'sourcemodule', 'neq', 'question'); $mform->disabledIf('questioncategoryid', 'sourcemodule', 'neq', 'question');
//subcategories // Subcategories.
$mform->addElement('selectyesno', 'subcategories', get_string('sourcemodule_include_subcategories', 'game')); $mform->addElement('selectyesno', 'subcategories', get_string('sourcemodule_include_subcategories', 'game'));
$mform->disabledIf('subcategories', 'sourcemodule', 'neq', 'question'); $mform->disabledIf('subcategories', 'sourcemodule', 'neq', 'question');
} }
// Quiz Category.
//*********************** if ($gamekind != 'bookquiz') {
// Quiz Category
if( $gamekind != 'bookquiz'){
$a = array(); $a = array();
if( $recs = $DB->get_records('quiz', array( 'course' => $COURSE->id), 'id,name')){ if ($recs = $DB->get_records('quiz', array( 'course' => $COURSE->id), 'id,name')) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$a[$rec->id] = $rec->name; $a[$rec->id] = $rec->name;
} }
} }
@ -149,80 +154,74 @@ class mod_game_mod_form extends moodleform_mod {
$mform->disabledIf('quizid', 'sourcemodule', 'neq', 'quiz'); $mform->disabledIf('quizid', 'sourcemodule', 'neq', 'quiz');
} }
// Book.
//*********************** if ( $gamekind == 'bookquiz') {
// Book
if($gamekind == 'bookquiz'){
$a = array(); $a = array();
if($recs = $DB->get_records('book', array( 'course' => $COURSE->id), 'id,name')){ if ($recs = $DB->get_records('book', array( 'course' => $COURSE->id), 'id,name')) {
foreach($recs as $rec){ foreach ($recs as $rec) {
$a[$rec->id] = $rec->name; $a[$rec->id] = $rec->name;
} }
} }
$mform->addElement('select', 'bookid', get_string('sourcemodule_book', 'game'), $a); $mform->addElement('select', 'bookid', get_string('sourcemodule_book', 'game'), $a);
} }
//Common settings to all games
$mform->addElement('text', 'maxattempts', get_string('cross_max_attempts','game'));
$mform->setType('maxattempts', PARAM_INT);
//--------------------------------------------------------------------------- // Common settings to all games.
// Grade options $mform->addElement('text', 'maxattempts', get_string('cross_max_attempts', 'game'));
$mform->setType('maxattempts', PARAM_INT);
// Grade options.
$mform->addElement('header', 'gradeoptions', get_string('grades', 'grades')); $mform->addElement('header', 'gradeoptions', get_string('grades', 'grades'));
$mform->addElement('text', 'grade', get_string( 'grademax', 'grades'), array('size' => 4)); $mform->addElement('text', 'grade', get_string( 'grademax', 'grades'), array('size' => 4));
$mform->setType('grade', PARAM_INT); $mform->setType('grade', PARAM_INT);
$gradingtypeoptions = array(); $gradingtypeoptions = array();
$gradingtypeoptions[ GAME_GRADEHIGHEST] = get_string('gradehighest','game'); $gradingtypeoptions[ GAME_GRADEHIGHEST] = get_string('gradehighest', 'game');
$gradingtypeoptions[ GAME_GRADEAVERAGE] = get_string('gradeaverage','game'); $gradingtypeoptions[ GAME_GRADEAVERAGE] = get_string('gradeaverage', 'game');
$gradingtypeoptions[ GAME_ATTEMPTFIRST] = get_string('attemptfirst','game'); $gradingtypeoptions[ GAME_ATTEMPTFIRST] = get_string('attemptfirst', 'game');
$gradingtypeoptions[ GAME_ATTEMPTLAST] = get_string('attemptlast','game'); $gradingtypeoptions[ GAME_ATTEMPTLAST] = get_string('attemptlast', 'game');
$mform->addElement('select', 'grademethod', get_string('grademethod','game'), $gradingtypeoptions); $mform->addElement('select', 'grademethod', get_string('grademethod', 'game'), $gradingtypeoptions);
// Open and close dates. // Open and close dates.
$mform->addElement('date_time_selector', 'timeopen', get_string('gameopen', 'game'), $mform->addElement('date_time_selector', 'timeopen', get_string('gameopen', 'game'),
array('optional' => true, 'step' => 1)); array('optional' => true, 'step' => 1));
$mform->addHelpButton('timeopen', 'gameopenclose', 'game'); $mform->addHelpButton('timeopen', 'gameopenclose', 'game');
$mform->addElement('date_time_selector', 'timeclose', get_string('gameclose', 'game'), $mform->addElement('date_time_selector', 'timeclose', get_string('gameclose', 'game'),
array('optional' => true, 'step' => 1)); array('optional' => true, 'step' => 1));
//---------------------------------------------------------------------------
// Bookquiz options
if($gamekind == 'bookquiz'){ // Bookquiz options.
if ($gamekind == 'bookquiz') {
$mform->addElement('header', 'bookquiz', get_string( 'bookquiz_options', 'game')); $mform->addElement('header', 'bookquiz', get_string( 'bookquiz_options', 'game'));
$bookquizlayoutoptions = array(); $bookquizlayoutoptions = array();
$bookquizlayoutoptions[0] = get_string('bookquiz_layout0', 'game'); $bookquizlayoutoptions[0] = get_string('bookquiz_layout0', 'game');
$bookquizlayoutoptions[1] = get_string('bookquiz_layout1', 'game'); $bookquizlayoutoptions[1] = get_string('bookquiz_layout1', 'game');
$mform->addElement('select','param3', get_string('bookquiz_layout', 'game'), $bookquizlayoutoptions); $mform->addElement('select', 'param3',
get_string('bookquiz_layout', 'game'), $bookquizlayoutoptions);
} }
//---------------------------------------------------------------------------
// Hangman options
if($gamekind == 'hangman'){ // Hangman options.
if ($gamekind == 'hangman') {
$mform->addElement('header', 'hangman', get_string( 'hangman_options', 'game')); $mform->addElement('header', 'hangman', get_string( 'hangman_options', 'game'));
$mform->addElement('text', 'param4', get_string('hangman_maxtries', 'game'), array('size' => 4)); $mform->addElement('text', 'param4', get_string('hangman_maxtries', 'game'), array('size' => 4));
$mform->setType('param4', PARAM_INT); $mform->setType('param4', PARAM_INT);
$mform->addElement('selectyesno', 'param1', get_string('hangman_showfirst', 'game')); $mform->addElement('selectyesno', 'param1', get_string('hangman_showfirst', 'game'));
$mform->addElement('selectyesno', 'param2', get_string('hangman_showlast', 'game')); $mform->addElement('selectyesno', 'param2', get_string('hangman_showlast', 'game'));
$mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces','game')); $mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces', 'game'));
$mform->addElement('selectyesno', 'param8', get_string('hangman_allowsub', 'game')); $mform->addElement('selectyesno', 'param8', get_string('hangman_allowsub', 'game'));
$mform->addElement('text', 'param10', get_string( 'hangman_maximum_number_of_errors', 'game'), array('size' => 4)); $mform->addElement('text', 'param10', get_string( 'hangman_maximum_number_of_errors', 'game'), array('size' => 4));
$mform->setType('param10', PARAM_INT); $mform->setType('param10', PARAM_INT);
if( !isset( $config->hangmanimagesets)) if (!isset( $config->hangmanimagesets)) {
$number = 1; $number = 1;
else } else {
$number = $config->hangmanimagesets; $number = $config->hangmanimagesets;
if( $number > 1) }
{ if ($number > 1) {
$a = array(); $a = array();
for( $i=1; $i <= $number; $i++) for ($i = 1; $i <= $number; $i++) {
$a[ $i] = $i; $a[ $i] = $i;
$mform->addElement('select', 'param3', get_string('hangman_imageset','game'), $a); }
$mform->addElement('select', 'param3', get_string('hangman_imageset', 'game'), $a);
} }
$mform->addElement('selectyesno', 'param5', get_string('hangman_showquestion', 'game')); $mform->addElement('selectyesno', 'param5', get_string('hangman_showquestion', 'game'));
@ -231,40 +230,36 @@ class mod_game_mod_form extends moodleform_mod {
$a = array(); $a = array();
$a = get_string_manager()->get_list_of_translations(); $a = get_string_manager()->get_list_of_translations();
$a[ ''] = '----------'; $a[ ''] = '----------';
$a[ 'user'] = get_string('language_user_defined', 'game'); $a[ 'user'] = get_string('language_user_defined', 'game');
ksort( $a); ksort( $a);
$mform->addElement('select', 'language', get_string('hangman_language','game'), $a); $mform->addElement('select', 'language', get_string('hangman_language', 'game'), $a);
$mform->addElement('text', 'userlanguage', get_string('language_user_defined','game')); $mform->addElement('text', 'userlanguage', get_string('language_user_defined', 'game'));
$mform->setType('userlanguage', PARAM_TEXT); $mform->setType('userlanguage', PARAM_TEXT);
$mform->disabledIf('userlanguage', 'language', 'neq', 'user'); $mform->disabledIf('userlanguage', 'language', 'neq', 'user');
} }
//--------------------------------------------------------------------------- // Crossword options.
// Crossword options if ($gamekind == 'cross') {
if($gamekind == 'cross'){
$mform->addElement('header', 'cross', get_string( 'cross_options', 'game')); $mform->addElement('header', 'cross', get_string( 'cross_options', 'game'));
$mform->addElement('text', 'param1', get_string('cross_maxcols', 'game')); $mform->addElement('text', 'param1', get_string('cross_maxcols', 'game'));
$mform->setType('param1', PARAM_INT); $mform->setType('param1', PARAM_INT);
$mform->addElement('text', 'param4', get_string('cross_minwords', 'game')); $mform->addElement('text', 'param4', get_string('cross_minwords', 'game'));
$mform->setType('param4', PARAM_INT); $mform->setType('param4', PARAM_INT);
$mform->addElement('text', 'param2', get_string('cross_maxwords', 'game')); $mform->addElement('text', 'param2', get_string('cross_maxwords', 'game'));
$mform->setType('param2', PARAM_INT); $mform->setType('param2', PARAM_INT);
$mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces','game')); $mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces', 'game'));
$crosslayoutoptions = array(); $crosslayoutoptions = array();
$crosslayoutoptions[0] = get_string('cross_layout0', 'game'); $crosslayoutoptions[0] = get_string('cross_layout0', 'game');
$crosslayoutoptions[1] = get_string('cross_layout1', 'game'); $crosslayoutoptions[1] = get_string('cross_layout1', 'game');
$mform->addElement('select','param3', get_string('cross_layout', 'game'), $crosslayoutoptions); $mform->addElement('select', 'param3', get_string('cross_layout', 'game'), $crosslayoutoptions);
$mform->setType('param5', PARAM_INT); $mform->setType('param5', PARAM_INT);
$mform->addElement('selectyesno', 'param6', get_string('cross_disabletransformuppercase','game')); $mform->addElement('selectyesno', 'param6', get_string('cross_disabletransformuppercase', 'game'));
} }
//--------------------------------------------------------------------------- // Cryptex options.
// Cryptex options if ($gamekind == 'cryptex') {
if($gamekind == 'cryptex'){
$mform->addElement('header', 'cryptex', get_string( 'cryptex_options', 'game')); $mform->addElement('header', 'cryptex', get_string( 'cryptex_options', 'game'));
$mform->addElement('text', 'param1', get_string('cross_maxcols', 'game')); $mform->addElement('text', 'param1', get_string('cross_maxcols', 'game'));
$mform->setType('param1', PARAM_INT); $mform->setType('param1', PARAM_INT);
@ -272,15 +267,13 @@ class mod_game_mod_form extends moodleform_mod {
$mform->setType('param4', PARAM_INT); $mform->setType('param4', PARAM_INT);
$mform->addElement('text', 'param2', get_string('cross_maxwords', 'game')); $mform->addElement('text', 'param2', get_string('cross_maxwords', 'game'));
$mform->setType('param2', PARAM_INT); $mform->setType('param2', PARAM_INT);
$mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces','game')); $mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces', 'game'));
$mform->addElement('text', 'param8', get_string('cryptex_maxtries','game')); $mform->addElement('text', 'param8', get_string('cryptex_maxtries', 'game'));
$mform->setType('param8', PARAM_INT); $mform->setType('param8', PARAM_INT);
} }
//---------------------------------------------------------------------------
// Millionaire options
if($gamekind == 'millionaire'){ // Millionaire options.
if ($gamekind == 'millionaire') {
global $OUTPUT, $PAGE; global $OUTPUT, $PAGE;
$mform->addElement('header', 'millionaire', get_string( 'millionaire_options', 'game')); $mform->addElement('header', 'millionaire', get_string( 'millionaire_options', 'game'));
@ -288,44 +281,36 @@ class mod_game_mod_form extends moodleform_mod {
$mform->setDefault('param8', '#408080'); $mform->setDefault('param8', '#408080');
$mform->setType('param8', PARAM_TEXT); $mform->setType('param8', PARAM_TEXT);
//$mform->addElement('colorpicker', 'param8', get_string('millionaire_background', 'game')); $mform->addElement('selectyesno', 'shuffle', get_string('millionaire_shuffle', 'game'));
//$mform->registerRule('color','regex','/^#([a-fA-F0-9]{6})$/');
//$mform->addRule('config_bgcolor','Enter a valid RGB color - # and then 6 characters','color');
$mform->addElement('selectyesno', 'shuffle', get_string('millionaire_shuffle','game'));
} }
//--------------------------------------------------------------------------- // Sudoku options.
// Sudoku options if ($gamekind == 'sudoku') {
if($gamekind == 'sudoku'){
$mform->addElement('header', 'sudoku', get_string( 'sudoku_options', 'game')); $mform->addElement('header', 'sudoku', get_string( 'sudoku_options', 'game'));
$mform->addElement('text', 'param2', get_string('sudoku_maxquestions', 'game')); $mform->addElement('text', 'param2', get_string('sudoku_maxquestions', 'game'));
$mform->setType('param2', PARAM_INT); $mform->setType('param2', PARAM_INT);
} }
//--------------------------------------------------------------------------- // Snakes and Ladders options.
// Snakes and Ladders options if ($gamekind == 'snakes') {
if($gamekind == 'snakes'){
$mform->addElement('header', 'snakes', get_string( 'snakes_options', 'game')); $mform->addElement('header', 'snakes', get_string( 'snakes_options', 'game'));
$snakesandladdersbackground = array(); $snakesandladdersbackground = array();
if($recs = $DB->get_records( 'game_snakes_database', null, 'id,name')){ if ($recs = $DB->get_records( 'game_snakes_database', null, 'id,name')) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$snakesandladdersbackground[$rec->id] = $rec->name; $snakesandladdersbackground[$rec->id] = $rec->name;
} }
} }
$snakeslayoutoptions = array(); $snakeslayoutoptions = array();
$snakeslayoutoptions[0] = get_string('snakes_layout0', 'game'); $snakeslayoutoptions[0] = get_string('snakes_layout0', 'game');
$snakeslayoutoptions[1] = get_string('snakes_layout1', 'game'); $snakeslayoutoptions[1] = get_string('snakes_layout1', 'game');
$mform->addElement('select','param8', get_string('bookquiz_layout', 'game'), $snakeslayoutoptions); $mform->addElement('select', 'param8', get_string('bookquiz_layout', 'game'), $snakeslayoutoptions);
if(count($snakesandladdersbackground) == 0){ if (count($snakesandladdersbackground) == 0) {
require("{$CFG->dirroot}/mod/game/db/importsnakes.php"); require("{$CFG->dirroot}/mod/game/db/importsnakes.php");
if($recs = $DB->get_records('game_snakes_database', null, 'id,name')){ if ($recs = $DB->get_records('game_snakes_database', null, 'id,name')) {
foreach($recs as $rec){ foreach ($recs as $rec) {
$snakesandladdersbackground[$rec->id] = $rec->name; $snakesandladdersbackground[$rec->id] = $rec->name;
} }
} }
@ -334,14 +319,14 @@ class mod_game_mod_form extends moodleform_mod {
ksort( $snakesandladdersbackground); ksort( $snakesandladdersbackground);
$mform->addElement('select', 'param3', get_string('snakes_background', 'game'), $snakesandladdersbackground); $mform->addElement('select', 'param3', get_string('snakes_background', 'game'), $snakesandladdersbackground);
//param3 = background // Param3 = background.
//param4 = itemid for file_storage // Param4 = itemid for file_storage.
//param5 (=1 means dirty file and and have to be computed again) // Param5 (=1 means dirty file and and have to be computed again).
//param6 = width of autogenerated picture // Param6 = width of autogenerated picture.
//param7 = height of autogenerated picture // Param7 = height of autogenerated picture.
//param8 = layout // Param8 = layout.
$attachmentoptions = array('subdirs'=>false, 'maxfiles'=>1); $attachmentoptions = array('subdirs' => false, 'maxfiles' => 1);
$mform->addElement('filepicker', 'param4', get_string('snakes_file', 'game'), $attachmentoptions); $mform->addElement('filepicker', 'param4', get_string('snakes_file', 'game'), $attachmentoptions);
$mform->disabledIf('param4', 'param3', 'neq', '0'); $mform->disabledIf('param4', 'param3', 'neq', '0');
@ -379,10 +364,8 @@ class mod_game_mod_form extends moodleform_mod {
$mform->setType('snakes_height', PARAM_INT); $mform->setType('snakes_height', PARAM_INT);
} }
//--------------------------------------------------------------------------- // Hidden Picture options.
// Hidden Picture options if ($gamekind == 'hiddenpicture') {
if($gamekind == 'hiddenpicture'){
$mform->addElement('header', 'hiddenpicture', get_string( 'hiddenpicture_options', 'game')); $mform->addElement('header', 'hiddenpicture', get_string( 'hiddenpicture_options', 'game'));
$mform->addElement('text', 'param1', get_string('hiddenpicture_across', 'game')); $mform->addElement('text', 'param1', get_string('hiddenpicture_across', 'game'));
$mform->setType('param1', PARAM_INT); $mform->setType('param1', PARAM_INT);
@ -392,14 +375,14 @@ class mod_game_mod_form extends moodleform_mod {
$mform->setDefault('param2', 3); $mform->setDefault('param2', 3);
$a = array(); $a = array();
if($recs = $DB->get_records('glossary', array( 'course' => $COURSE->id), 'id,name')){ if ($recs = $DB->get_records('glossary', array( 'course' => $COURSE->id), 'id,name')) {
foreach($recs as $rec){ foreach ($recs as $rec) {
$cmg = get_coursemodule_from_instance('glossary', $rec->id, $COURSE->id); $cmg = get_coursemodule_from_instance('glossary', $rec->id, $COURSE->id);
$context = game_get_context_module_instance( $cmg->id); $context = game_get_context_module_instance( $cmg->id);
if( $DB->record_exists( 'files', array( 'contextid' => $context->id))){ if ($DB->record_exists( 'files', array( 'contextid' => $context->id))) {
$a[$rec->id] = $rec->name; $a[$rec->id] = $rec->name;
} }
} }
} }
$mform->addElement('select', 'glossaryid2', get_string('hiddenpicture_pictureglossary', 'game'), $a); $mform->addElement('select', 'glossaryid2', get_string('hiddenpicture_pictureglossary', 'game'), $a);
@ -407,104 +390,98 @@ class mod_game_mod_form extends moodleform_mod {
$mform->setType('param4', PARAM_INT); $mform->setType('param4', PARAM_INT);
$mform->addELement('text', 'param5', get_string('hiddenpicture_height', 'game')); $mform->addELement('text', 'param5', get_string('hiddenpicture_height', 'game'));
$mform->setType('param5', PARAM_INT); $mform->setType('param5', PARAM_INT);
$mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces','game')); $mform->addElement('selectyesno', 'param7', get_string('hangman_allowspaces', 'game'));
} }
//--------------------------------------------------------------------------- // Header/Footer options.
// Header/Footer options
$mform->addElement('header', 'headerfooteroptions', 'Header/Footer Options'); $mform->addElement('header', 'headerfooteroptions', 'Header/Footer Options');
$mform->addElement('htmleditor', 'toptext', get_string('toptext','game')); $mform->addElement('htmleditor', 'toptext', get_string('toptext', 'game'));
$mform->addElement('htmleditor', 'bottomtext', get_string('bottomtext','game')); $mform->addElement('htmleditor', 'bottomtext', get_string('bottomtext', 'game'));
//---------------------------------------------------------------------------
$features = new stdClass; $features = new stdClass;
$this->standard_coursemodule_elements($features); $this->standard_coursemodule_elements($features);
//--------------------------------------------------------------------------- // Buttons.
// buttons
$this->add_action_buttons(); $this->add_action_buttons();
} }
public function validation($data, $files) {
function validation($data, $files){
$errors = parent::validation($data, $files); $errors = parent::validation($data, $files);
// Check open and close times are consistent. // Check open and close times are consistent.
if ($data['timeopen'] != 0 && $data['timeclose'] != 0 && if ($data['timeopen'] != 0 && $data['timeclose'] != 0 &&
$data['timeclose'] < $data['timeopen']) { $data['timeclose'] < $data['timeopen']) {
$errors['timeclose'] = get_string('closebeforeopen', 'quiz'); $errors['timeclose'] = get_string('closebeforeopen', 'quiz');
} }
return $errors; return $errors;
} }
function set_data($default_values) { public function set_data($defaultvalues) {
global $DB; global $DB;
if( isset( $default_values->type)) if (isset( $defaultvalues->type)) {
{ // Default values for every game.
//Default values for every game. if ($defaultvalues->type == 'hangman') {
if( $default_values->type == 'hangman') $defaultvalues->param10 = 6; // Maximum number of wrongs.
{ } else if ($defaultvalues->type == 'snakes') {
$default_values->param10 = 6; //maximum number of wrongs $defaultvalues->gamekind = $defaultvalues->type;
}else if( $default_values->type == 'snakes') $defaultvalues->param3 = 1;
{ $defaultvalues->questioncategoryid = 0;
$default_values->gamekind = $default_values->type; } else if ($defaultvalues->type == 'millionaire') {
$default_values->param3 = 1; $defaultvalues->shuffle = 1;
$default_values->questioncategoryid = 0;
}else if( $default_values->type == 'millionaire')
{
$default_values->shuffle = 1;
} }
} }
if( isset( $default_values->gamekind)){ if (isset( $defaultvalues->gamekind)) {
if( $default_values->gamekind == 'hangman'){ if ($defaultvalues->gamekind == 'hangman') {
if( $default_values->param10 == 0) if ($defaultvalues->param10 == 0) {
$default_values->param10 = 6; $defaultvalues->param10 = 6;
}else if( $default_values->gamekind == 'millionaire'){ }
if( isset( $default_values->param8)) } else if ($defaultvalues->gamekind == 'millionaire') {
$default_values->param8 = '#'.substr( '000000'.strtoupper( dechex( $default_values->param8)),-6); if (isset( $defaultvalues->param8)) {
}else if( $default_values->gamekind == 'cross') $defaultvalues->param8 = '#'.substr( '000000'.strtoupper( dechex( $defaultvalues->param8)), -6);
{ }
if( $default_values->param5 == NULL) } else if ($defaultvalues->gamekind == 'cross') {
$default_values->param5 = 1; if ($defaultvalues->param5 == null) {
$defaultvalues->param5 = 1;
}
} }
if( $default_values->gamekind == 'snakes'){ if ($defaultvalues->gamekind == 'snakes') {
if( isset( $default_values->param9)){ if (isset( $defaultvalues->param9)) {
$a = explode( '#',$default_values->param9); $a = explode( '#', $defaultvalues->param9);
foreach( $a as $s){ foreach ($a as $s) {
$pos = strpos( $s, ':'); $pos = strpos( $s, ':');
if( $pos){ if ($pos) {
$name = substr( $s, 0, $pos); $name = substr( $s, 0, $pos);
$default_values->$name = substr( $s, $pos+1); $defaultvalues->$name = substr( $s, $pos + 1);
} }
} }
} }
} }
} }
if( !isset( $default_values->gamekind)) if (!isset( $defaultvalues->gamekind)) {
$default_values->gamekind = $default_values->type; $defaultvalues->gamekind = $defaultvalues->type;
if( $default_values->gamekind == 'snakes'){ }
if( isset( $default_values->param3)){ if ($defaultvalues->gamekind == 'snakes') {
$board = $default_values->param3; if (isset( $defaultvalues->param3)) {
if( $board != 0){ $board = $defaultvalues->param3;
if ($board != 0) {
$rec = $DB->get_record( 'game_snakes_database', array( 'id' => $board)); $rec = $DB->get_record( 'game_snakes_database', array( 'id' => $board));
$default_values->snakes_data = $rec->data; $defaultvalues->snakes_data = $rec->data;
$default_values->snakes_cols = $rec->cols; $defaultvalues->snakes_cols = $rec->cols;
$default_values->snakes_rows = $rec->rows; $defaultvalues->snakes_rows = $rec->rows;
$default_values->snakes_headerx = $rec->headerx; $defaultvalues->snakes_headerx = $rec->headerx;
$default_values->snakes_headery = $rec->headery; $defaultvalues->snakes_headery = $rec->headery;
$default_values->snakes_footerx = $rec->footerx; $defaultvalues->snakes_footerx = $rec->footerx;
$default_values->snakes_footery = $rec->footery; $defaultvalues->snakes_footery = $rec->footery;
} }
} }
} }
parent::set_data($default_values); parent::set_data($defaultvalues);
} }
} }

72
pagelib.php

@ -1,7 +1,21 @@
<?php // $Id: pagelib.php,v 1.5 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
require_once($CFG->libdir.'/pagelib.php'); require_once( $CFG->libdir.'/pagelib.php');
require_once($CFG->dirroot.'/course/lib.php'); // needed for some blocks require_once( $CFG->dirroot.'/course/lib.php'); // Needed for some blocks.
define('PAGE_GAME_VIEW', 'mod-game-view'); define('PAGE_GAME_VIEW', 'mod-game-view');
@ -18,75 +32,59 @@ $DEFINEDPAGES = array( PAGE_GAME_VIEW);
class page_game extends page_generic_activity { class page_game extends page_generic_activity {
function init_quick($data) { public function init_quick($data) {
if(empty($data->pageid)) { if (empty($data->pageid)) {
print_error('Cannot quickly initialize page: empty course id'); print_error('Cannot quickly initialize page: empty course id');
} }
$this->activityname = 'game'; $this->activityname = 'game';
parent::init_quick($data); parent::init_quick($data);
} }
function print_header($title, $morebreadcrumbs = NULL, $navigation ='') { public function print_header($title, $morebreadcrumbs = null, $navigation ='') {
global $USER, $CFG; global $USER, $CFG;
$this->init_full(); $this->init_full();
$replacements = array( $replacements = array(
'%fullname%' => format_string($this->activityrecord->name) '%fullname%' => format_string($this->activityrecord->name)
); )
foreach($replacements as $search => $replace) { foreach ($replacements as $search => $replace) {
$title = str_replace($search, $replace, $title); $title = str_replace($search, $replace, $title);
} }
if($this->courserecord->id == SITEID) { if ($this->courserecord->id == SITEID) {
$breadcrumbs = array(); $breadcrumbs = array();
} } else {
else {
$breadcrumbs = array($this->courserecord->shortname => $CFG->wwwroot.'/course/view.php?id='.$this->courserecord->id); $breadcrumbs = array($this->courserecord->shortname => $CFG->wwwroot.'/course/view.php?id='.$this->courserecord->id);
} }
$breadcrumbs[get_string('modulenameplural', 'game')] = $CFG->wwwroot.'/mod/game/index.php?id='.$this->courserecord->id; $breadcrumbs[get_string('modulenameplural', 'game')] = $CFG->wwwroot.'/mod/game/index.php?id='.$this->courserecord->id;
$breadcrumbs[format_string($this->activityrecord->name)] = $CFG->wwwroot.'/mod/game/view.php?id='.$this->modulerecord->id; $breadcrumbs[format_string($this->activityrecord->name)]
= $CFG->wwwroot.'/mod/game/view.php?id='.$this->modulerecord->id;
if(!empty($morebreadcrumbs)) { if (!empty($morebreadcrumbs)) {
$breadcrumbs = array_merge($breadcrumbs, $morebreadcrumbs); $breadcrumbs = array_merge($breadcrumbs, $morebreadcrumbs);
} }
/*
$total = count($breadcrumbs); if (empty($morebreadcrumbs) && $this->user_allowed_editing()) {
$current = 1;
$crumbtext = '';
foreach($breadcrumbs as $text => $href) {
if($current++ == $total) {
$crumbtext .= ' '.$text;
}
else {
$crumbtext .= ' <a href="'.$href.'">'.$text.'</a> ->';
}
}
*/
if(empty($morebreadcrumbs) && $this->user_allowed_editing()) {
$buttons = '<table><tr><td>'. $buttons = '<table><tr><td>'.
update_module_button($this->modulerecord->id, $this->courserecord->id, get_string('modulename', 'game')).'</td>'; update_module_button($this->modulerecord->id, $this->courserecord->id, get_string('modulename', 'game')).'</td>';
if(!empty($CFG->showblocksonmodpages)) { if (!empty($CFG->showblocksonmodpages)) {
$buttons .= '<td><form '.$CFG->frametarget.' method="get" action="view.php">'. $buttons .= '<td><form '.$CFG->frametarget.' method="get" action="view.php">'.
'<div>'. '<div>'.
'<input type="hidden" name="id" value="'.$this->modulerecord->id.'" />'. '<input type="hidden" name="id" value="'.$this->modulerecord->id.'" />'.
'<input type="hidden" name="edit" value="'.($this->user_is_editing()?'off':'on').'" />'. '<input type="hidden" name="edit" value="'.($this->user_is_editing() ? 'off' : 'on').'" />'.
'<input type="submit" value="'.get_string($this->user_is_editing()?'blockseditoff':'blocksediton').'" />'. '<input type="submit" value="'.get_string($this->user_is_editing() ? 'blockseditoff' : 'blocksediton').'" />'.
'</div></form></td>'; '</div></form></td>';
} }
$buttons .= '</tr></table>'; $buttons .= '</tr></table>';
} } else {
else {
$buttons = '&nbsp;'; $buttons = '&nbsp;';
} }
//print_header($title, $this->courserecord->fullname, $crumbtext, '', '', true, $buttons, navmenu($this->courserecord, $this->modulerecord),false,$bodytags);
print_header($title, $this->courserecord->fullname, $navigation);
print_header($title, $this->courserecord->fullname, $navigation);
} }
function get_type() { public function get_type() {
return PAGE_GAME_VIEW; return PAGE_GAME_VIEW;
} }
} }
?>

120
preview.php

@ -1,4 +1,19 @@
<?php // $Id: preview.php,v 1.10 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* This page prints a particular attempt of game * This page prints a particular attempt of game
* *
@ -6,62 +21,63 @@
* @version $Id: preview.php,v 1.10 2012/07/25 11:16:04 bdaloukas Exp $ * @version $Id: preview.php,v 1.10 2012/07/25 11:16:04 bdaloukas Exp $
* @package game * @package game
**/ **/
require_once("../../config.php");
require_once("lib.php");
require_once("locallib.php");
require_once( "hangman/play.php"); require_once("../../config.php");
require_once( "cross/play.php"); require_once("lib.php");
require_once( "cryptex/play.php"); require_once("locallib.php");
require_once( "millionaire/play.php");
require_once( "sudoku/play.php"); require_once( "hangman/play.php");
require_once( "bookquiz/play.php"); require_once( "cross/play.php");
require_once( "cryptex/play.php");
require_once( "headergame.php"); require_once( "millionaire/play.php");
require_once( "sudoku/play.php");
require_once( "bookquiz/play.php");
require_once( "headergame.php");
$context = game_get_context_module_instance( $cm->id);
$context = game_get_context_module_instance( $cm->id); if (!has_capability('mod/game:viewreports', $context)) {
print_error( get_string( 'only_teachers', 'game'));
}
if (!has_capability('mod/game:viewreports', $context)){ $action = required_param('action', PARAM_ALPHANUM);
print_error( get_string( 'only_teachers', 'game')); $gamekind = required_param('gamekind', PARAM_ALPHANUM);
} $update = required_param('update', PARAM_INT);
$action = required_param('action', PARAM_ALPHANUM); $attemptid = required_param('attemptid', PARAM_INT);
$gamekind = required_param('gamekind', PARAM_ALPHANUM); $attempt = $DB->get_record( 'game_attempts', array('id' => $attemptid));
$update = required_param('update', PARAM_INT); $game = $DB->get_record( 'game', array( 'id' => $attempt->gameid));
$detail = $DB->get_record( 'game_'.$gamekind, array( 'id' => $attemptid));
$solution = ($action == 'solution');
$attemptid = required_param('attemptid', PARAM_INT); $PAGE->navbar->add(get_string('preview', 'game'));
$attempt = $DB->get_record( 'game_attempts', array('id' => $attemptid));
$game = $DB->get_record( 'game', array( 'id' => $attempt->gameid));
$detail = $DB->get_record( 'game_'.$gamekind, array( 'id' => $attemptid));
$solution = ($action == 'solution');
$PAGE->navbar->add(get_string('preview', 'game')); switch( $gamekind) {
case 'cross':
switch( $gamekind) $g = '';
{ $onlyshow = true;
case 'cross': $endofgame = false;
$g = ''; $print = false;
$onlyshow = true; $checkbutton = false;
$endofgame = false; $showhtmlsolutions = false;
$print = false; $showhtmlprintbutton = true;
$checkbutton = false; $showstudentguess = false;
$showhtmlsolutions = false; game_cross_play( $update, $game, $attempt, $detail, $g, $onlyshow, $solution,
$showhtmlprintbutton = true; $endofgame, $print, $checkbutton, $showhtmlsolutions, $showhtmlprintbutton,
$showstudentguess = false; $showstudentguess, $context);
game_cross_play( $update, $game, $attempt, $detail, $g, $onlyshow, $solution, $endofgame, $print, $checkbutton, $showhtmlsolutions, $showhtmlprintbutton, $showstudentguess, $context); break;
break; case 'sudoku':
case 'sudoku': game_sudoku_play( $update, $game, $attempt, $detail, true, $solution, $context);
game_sudoku_play( $update, $game, $attempt, $detail, true, $solution, $context); break;
break; case 'hangman':
case 'hangman':
$preview = ($action == 'preview'); $preview = ($action == 'preview');
game_hangman_play( $update, $game, $attempt, $detail, $preview, $solution, $context); game_hangman_play( $update, $game, $attempt, $detail, $preview, $solution, $context);
break; break;
case 'cryptex': case 'cryptex':
$crossm = $DB->get_record( 'game_cross', array('id' => $attemptid)); $crossm = $DB->get_record( 'game_cross', array('id' => $attemptid));
game_cryptex_play( $update, $game, $attempt, $detail, $crossm, false, true, $solution, $context); game_cryptex_play( $update, $game, $attempt, $detail, $crossm, false, true, $solution, $context);
break; break;
} }
echo $OUTPUT->footer(); echo $OUTPUT->footer();

135
print.php

@ -1,4 +1,19 @@
<?php // $Id: print.php,v 1.7 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* This page export the game to html * This page export the game to html
* *
@ -6,80 +21,78 @@
* @version $Id: print.php,v 1.7 2012/07/25 11:16:04 bdaloukas Exp $ * @version $Id: print.php,v 1.7 2012/07/25 11:16:04 bdaloukas Exp $
* @package game * @package game
**/ **/
require_once("../../config.php"); require_once("../../config.php");
require_once("lib.php"); require_once("lib.php");
require_once("locallib.php"); require_once("locallib.php");
$id = required_param('id', PARAM_INT); // Course Module ID, or $id = required_param('id', PARAM_INT); // Course Module ID.
$gameid = required_param('gameid', PARAM_INT); $gameid = required_param('gameid', PARAM_INT);
$game = $DB->get_record( 'game', array( 'id' => $gameid)); $game = $DB->get_record( 'game', array( 'id' => $gameid));
require_login( $game->course); require_login( $game->course);
$context = game_get_context_module_instance( $id); $context = game_get_context_module_instance( $id);
require_capability('mod/game:view', $context); require_capability('mod/game:view', $context);
game_print( $game, $id, $context); game_print( $game, $id, $context);
function game_print( $game, $update, $context){ function game_print( $game, $update, $context) {
if ( $game->gamekind == 'cross') {
if( $game->gamekind == 'cross') game_print_cross( $game, $update, $context);
game_print_cross( $game, $update, $context); } else if ($game->gamekind == 'cryptex') {
else if( $game->gamekind == 'cryptex') game_print_cryptex( $game, $update, $context);
game_print_cryptex( $game, $update, $context);
} }
}
function game_print_cross( $game, $update, $context)
{ function game_print_cross( $game, $update, $context) {
require( "cross/play.php"); require( "cross/play.php");
$attempt = game_getattempt( $game, $crossrec); $attempt = game_getattempt( $game, $crossrec);
$g = ''; $g = '';
$onlyshow = true; $onlyshow = true;
$showsolution = false; $showsolution = false;
$endofgame = false; $endofgame = false;
$print = true; $print = true;
$checkbutton = false; $checkbutton = false;
$showhtmlsolutions = false; $showhtmlsolutions = false;
$showhtmlprintbutton = false; $showhtmlprintbutton = false;
$showstudentguess = false; $showstudentguess = false;
?> ?>
<html dir="ltr" lang="el" xml:lang="el" xmlns="http://www.w3.org/1999/xhtml"> <html dir="ltr" lang="el" xml:lang="el" xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<title>Print</title> <title>Print</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php <?php
game_cross_play( $update, $game, $attempt, $crossrec, $g, $onlyshow, $showsolution, $endofgame, $print, $checkbutton, $showhtmlsolutions, $showhtmlprintbutton,$showstudentguess, $context); game_cross_play( $update, $game, $attempt, $crossrec, $g, $onlyshow, $showsolution,
$endofgame, $print, $checkbutton, $showhtmlsolutions, $showhtmlprintbutton,
$showstudentguess, $context);
}
} function game_print_cryptex( $game, $update, $context) {
global $DB;
function game_print_cryptex( $game, $update, $context) require( 'cross/cross_class.php');
{ require( 'cross/crossdb_class.php');
global $DB; require( "cryptex/play.php");
require( 'cross/cross_class.php'); $attempt = game_getattempt( $game, $crossrec);
require( 'cross/crossdb_class.php');
require( "cryptex/play.php");
$attempt = game_getattempt( $game, $crossrec); $updateattempt = false;
$onlyshow = true;
$updateattempt = false; $showsolution = false;
$onlyshow = true; $showhtmlprintbutton = false;
$showsolution = false; $print = true;
$showhtmlprintbutton = false; $crossm = $DB->get_record_select( 'game_cross', "id=$attempt->id");
$print = true;
$crossm = $DB->get_record_select( 'game_cross', "id=$attempt->id");
?> ?>
<html dir="ltr" lang="el" xml:lang="el" xmlns="http://www.w3.org/1999/xhtml"> <html dir="ltr" lang="el" xml:lang="el" xmlns="http://www.w3.org/1999/xhtml">
<head> <head>
<title>Print</title> <title>Print</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<?php <?php
game_cryptex_play( $update, $game, $attempt, $crossrec, $crossm, $updateattempt, $onlyshow, $showsolution, $context, $print, $showhtmlprintbutton); game_cryptex_play( $update, $game, $attempt, $crossrec, $crossm, $updateattempt,
} $onlyshow, $showsolution, $context, $print, $showhtmlprintbutton);
}

131
report.php

@ -1,79 +1,76 @@
<?php // $Id: report.php,v 1.5 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
// This script uses installed report plugins to print game reports //
// Moodle is free software: you can redistribute it and/or modify
require_once("../../config.php"); // it under the terms of the GNU General Public License as published by
require_once($CFG->dirroot.'/mod/game/locallib.php'); // the Free Software Foundation, either version 3 of the License, or
require_once($CFG->dirroot.'/mod/game/report/reportlib.php'); // (at your option) any later version.
//
$id = optional_param('id',0,PARAM_INT); // Course Module ID, or // Moodle is distributed in the hope that it will be useful,
$q = optional_param('q',0,PARAM_INT); // game ID // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
$mode = optional_param('mode', 'overview', PARAM_ALPHA); // Report mode // GNU General Public License for more details.
//
if ($id) { // You should have received a copy of the GNU General Public License
if (! $cm = get_coursemodule_from_id('game', $id)) { // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
print_error( "There is no coursemodule with id $id");
} // This script uses installed report plugins to print game reports.
if (! $course = $DB->get_record('course', array( 'id' => $cm->course))) { require_once("../../config.php");
print_error( 'Course is misconfigured'); require_once($CFG->dirroot.'/mod/game/locallib.php');
} require_once($CFG->dirroot.'/mod/game/report/reportlib.php');
if (! $game = $DB->get_record( 'game', array( 'id' => $cm->instance))) { $id = optional_param('id', 0, PARAM_INT); // Course Module ID.
print_error( "The game with id $cm->instance corresponding to this coursemodule $id is missing"); $q = optional_param('q', 0, PARAM_INT); // Game ID.
}
$mode = optional_param('mode', 'overview', PARAM_ALPHA); // Report mode.
} else {
if (! $game = $DB->get_record( 'game', array( 'id' => $q))) { if ($id) {
print_error( "There is no game with id $q"); if (! $cm = get_coursemodule_from_id('game', $id)) {
} print_error( "There is no coursemodule with id $id");
if (! $course = $DB->get_record( 'course', array( 'id' => $game->course))) {
print_error( "The course with id $game->course that the game with id $a belongs to is missing");
}
if (! $cm = get_coursemodule_from_instance( 'game', $game->id, $course->id)) {
print_error( "The course module for the game with id $q is missing");
}
} }
require_login($course->id, false); if (! $course = $DB->get_record('course', array( 'id' => $cm->course))) {
$context = get_context_instance(CONTEXT_MODULE, $cm->id); print_error( 'Course is misconfigured');
require_capability('mod/game:viewreports', $context); }
// if no questions have been set up yet redirect to edit.php
//if (!$game->questions and has_capability('mod/game:manage', $context)) {
// redirect('edit.php?gameid='.$game->id);
//}
// Upgrade any attempts that have not yet been upgraded to the if (! $game = $DB->get_record( 'game', array( 'id' => $cm->instance))) {
// Moodle 1.5 model (they will not yet have the timestamp set) print_error( "The game with id $cm->instance corresponding to this coursemodule $id is missing");
//if ($attempts = get_records_sql("SELECT a.*". }
// " FROM {$CFG->prefix}game_attempts a, {$CFG->prefix}question_states s". } else {
// " WHERE a.game = '$game->id' AND s.attempt = a.uniqueid AND s.timestamp = 0")) { if (! $game = $DB->get_record( 'game', array( 'id' => $q))) {
// foreach ($attempts as $attempt) { print_error( "There is no game with id $q");
// game_upgrade_states($attempt); }
// } if (! $course = $DB->get_record( 'course', array( 'id' => $game->course))) {
//} print_error( "The course with id $game->course that the game with id $a belongs to is missing");
}
if (! $cm = get_coursemodule_from_instance( 'game', $game->id, $course->id)) {
print_error( "The course module for the game with id $q is missing");
}
}
add_to_log($course->id, "game", "report", "report.php?id=$cm->id", "$game->id", "$cm->id"); require_login($course->id, false);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/game:viewreports', $context);
/// Open the selected game report and display it add_to_log($course->id, "game", "report", "report.php?id=$cm->id", "$game->id", "$cm->id");
$mode = clean_param( $mode, PARAM_SAFEDIR); // Open the selected game report and display it.
if (! is_readable("report/$mode/report.php")) { $mode = clean_param( $mode, PARAM_SAFEDIR);
print_error("Report not known ($mode)");
}
include("report/default.php"); // Parent class if (! is_readable("report/$mode/report.php")) {
include("report/$mode/report.php"); print_error("Report not known ($mode)");
}
$report = new game_overview_report(); require("report/default.php"); // Parent class.
require("report/$mode/report.php");
if (! $report->display( $game, $cm, $course)) { // Run the report! $report = new game_overview_report();
print_error( 'Error occurred during pre-processing!');
}
/// Print footer if (! $report->display( $game, $cm, $course)) { // Run the report!
print_error( 'Error occurred during pre-processing!');
}
echo $OUTPUT->footer($course); // Print footer.
echo $OUTPUT->footer($course);

610
review.php

@ -1,327 +1,327 @@
<?php // $Id: review.php,v 1.12 2012/07/25 23:07:43 bdaloukas Exp $ <?php
/** // This file is part of Moodle - http://moodle.org/
* This page prints a review of a particular game attempt //
* // Moodle is free software: you can redistribute it and/or modify
* @version $Id: review.php,v 1.12 2012/07/25 23:07:43 bdaloukas Exp $ // it under the terms of the GNU General Public License as published by
* @license http://www.gnu.org/copyleft/gpl.html GNU Public License // the Free Software Foundation, either version 3 of the License, or
* @package game // (at your option) any later version.
*/ //
// Moodle is distributed in the hope that it will be useful,
require_once("../../config.php"); // but WITHOUT ANY WARRANTY; without even the implied warranty of
require_once("locallib.php"); // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
require_once("../../lib/questionlib.php"); // GNU General Public License for more details.
//
$attempt = required_param('attempt', PARAM_INT); // A particular attempt ID for review // You should have received a copy of the GNU General Public License
$page = optional_param('page', 0, PARAM_INT); // The required page // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
$showall = optional_param('showall', 0, PARAM_BOOL);
// This page prints a review of a particular game attempt.
if (! $attempt = $DB->get_record('game_attempts', array( 'id' => $attempt))) {
print_error("No such attempt ID exists"); require_once("../../config.php");
} require_once("locallib.php");
if (! $game = $DB->get_record('game', array( 'id' => $attempt->gameid))) { require_once("../../lib/questionlib.php");
print_error("The game with id $attempt->gameid belonging to attempt $attempt is missing");
} $attempt = required_param('attempt', PARAM_INT); // A particular attempt ID for review.
$page = optional_param('page', 0, PARAM_INT); // The required page.
game_compute_attempt_layout( $game, $attempt); $showall = optional_param('showall', 0, PARAM_BOOL);
if (! $course = $DB->get_record('course', array( 'id' => $game->course))) { if (! $attempt = $DB->get_record('game_attempts', array( 'id' => $attempt))) {
print_error("The course with id $game->course that the game with id $game->id belongs to is missing"); print_error("No such attempt ID exists");
} }
if (! $cm = get_coursemodule_from_instance("game", $game->id, $course->id)) { if (! $game = $DB->get_record('game', array( 'id' => $attempt->gameid))) {
print_error("The course module for the game with id $game->id is missing"); print_error("The game with id $attempt->gameid belonging to attempt $attempt is missing");
}
game_compute_attempt_layout( $game, $attempt);
if (! $course = $DB->get_record('course', array( 'id' => $game->course))) {
print_error("The course with id $game->course that the game with id $game->id belongs to is missing");
}
if (! $cm = get_coursemodule_from_instance("game", $game->id, $course->id)) {
print_error("The course module for the game with id $game->id is missing");
}
$grade = game_score_to_grade( $attempt->score, $game);
$feedback = game_feedback_for_grade( $grade, $attempt->gameid);
require_login( $course->id, false, $cm);
$context = get_context_instance( CONTEXT_MODULE, $cm->id);
$coursecontext = get_context_instance( CONTEXT_COURSE, $cm->course);
$isteacher = isteacher( $game->course, $USER->id);
$options = game_get_reviewoptions( $game, $attempt, $context);
$popup = $isteacher ? 0 : $game->popup; // Controls whether this is shown in a javascript-protected window.
add_to_log($course->id, "game", "review", "review.php?id=$cm->id&amp;attempt=$attempt->id", "$game->id", "$cm->id");
// Print the page header.
$strgames = get_string('modulenameplural', 'game');
$strreview = get_string('review', 'game');
$strscore = get_string('score', "game");
$strgrade = get_string('grade');
$strbestgrade = get_string('bestgrade', 'quiz');
$strtimetaken = get_string('timetaken', 'game');
$strtimecompleted = get_string('completedon', 'game');
$strupdatemodule = has_capability('moodle/course:manageactivities',
$coursecontext) ? update_module_button($cm->id, $course->id, get_string('modulename', 'game')) : '';
$strgames = get_string("modulenameplural", "game");
$strgame = get_string("modulename", "game");
if (function_exists( 'build_navigation')) {
$navigation = build_navigation('', $cm);
echo $OUTPUT->heading("$course->shortname: $game->name", "$course->shortname: $game->name", $navigation,
"", "", true, update_module_button($cm->id, $course->id, $strgame),
navmenu($course, $cm));
} else {
if ($course->category) {
$navigation = "<a href=\"{$CFG->wwwroot}/course/view.php?id=$course->id\">$course->shortname</a> ->";
} else {
$navigation = '';
} }
$grade = game_score_to_grade( $attempt->score, $game); echo $OUTPUT->heading("$course->shortname: $game->name", "$course->fullname",
$feedback = game_feedback_for_grade( $grade, $attempt->gameid); "$navigation <a href=index.php?id=$course->id>$strgames</a> -> $game->name",
"", "", true, update_module_button($cm->id, $course->id, $strgame),
require_login( $course->id, false, $cm); navmenu($course, $cm));
$context = get_context_instance( CONTEXT_MODULE, $cm->id); }
$coursecontext = get_context_instance( CONTEXT_COURSE, $cm->course);
$isteacher = isteacher( $game->course, $USER->id); echo '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>'; // For overlib.
$options = game_get_reviewoptions( $game, $attempt, $context);
$popup = $isteacher ? 0 : $game->popup; // Controls whether this is shown in a javascript-protected window. // Print heading and tabs if this is part of a preview.
if ($attempt->userid == $USER->id) {
add_to_log($course->id, "game", "review", "review.php?id=$cm->id&amp;attempt=$attempt->id", "$game->id", "$cm->id"); // This is the report on a preview.
$currenttab = 'preview';
/// Print the page header } else {
$currenttab = 'reports';
$strgames = get_string('modulenameplural', 'game'); $mode = '';
$strreview = get_string('review', 'game'); }
$strscore = get_string('score', "game");
$strgrade = get_string('grade'); require('tabs.php');
$strbestgrade = get_string('bestgrade', 'quiz');
$strtimetaken = get_string('timetaken', 'game'); // Load all the questions and states needed by this script.
$strtimecompleted = get_string('completedon', 'game'); // Load the questions needed by page.
$pagelist = $showall ? game_questions_in_game( $attempt->layout) : game_questions_on_page( $attempt->layout, $page);
$a = explode( ',', $pagelist);
$strupdatemodule = has_capability('moodle/course:manageactivities', $coursecontext) $pagelist = '';
? update_module_button($cm->id, $course->id, get_string('modulename', 'game')) foreach ($a as $item) {
: ""; if (substr( $item, 0, 1)) {
if (substr( $item, -1) != 'G') {
$strgames = get_string("modulenameplural", "game"); $pagelist .= ','.$item;
$strgame = get_string("modulename", "game");
if( function_exists( 'build_navigation')){
$navigation = build_navigation('', $cm);
echo $OUTPUT->heading("$course->shortname: $game->name", "$course->shortname: $game->name", $navigation,
"", "", true, update_module_button($cm->id, $course->id, $strgame),
navmenu($course, $cm));
}else{
if ($course->category) {
$navigation = "<a href=\"{$CFG->wwwroot}/course/view.php?id=$course->id\">$course->shortname</a> ->";
} else {
$navigation = '';
}
echo $OUTPUT->heading("$course->shortname: $game->name", "$course->fullname",
"$navigation <a href=index.php?id=$course->id>$strgames</a> -> $game->name",
"", "", true, update_module_button($cm->id, $course->id, $strgame),
navmenu($course, $cm));
}
echo '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>'; // for overlib
/// Print heading and tabs if this is part of a preview
//if (has_capability('mod/game:preview', $context)) {
if ($attempt->userid == $USER->id) { // this is the report on a preview
$currenttab = 'preview';
} else {
$currenttab = 'reports';
$mode = '';
} }
include('tabs.php');
//} else {
// print_heading(format_string($game->name));
//}
/// Load all the questions and states needed by this script
// load the questions needed by page
$pagelist = $showall ? game_questions_in_game( $attempt->layout) : game_questions_on_page( $attempt->layout, $page);
$a = explode( ',', $pagelist);
$pagelist = '';
foreach( $a as $item){
if( substr( $item, 0, 1)){
if( substr( $item, -1) != 'G'){
$pagelist .= ','.$item;
}
}
}
$pagelist = substr( $pagelist, 1);
if( $pagelist != ''){
$sql = "SELECT q.*, i.id AS instance,i.id as iid,".
"i.score AS score,i.studentanswer".
" FROM {question} q,".
" {game_queries} i".
" WHERE i.attemptid = '$attempt->id' AND q.id = i.questionid AND (i.sourcemodule='question' or i.sourcemodule = 'quiz')".
" AND q.id IN ($pagelist)";
if (!$questions = $DB->get_records_sql( $sql)) {
print_error('No questions found');
}
}else
{
$questions = array();
}
// Load the question type specific information
if (!get_question_options( $questions)) {
print_error('Could not load question options');
} }
}
$pagelist = substr( $pagelist, 1);
$states = game_compute_states( $game, $questions); if ($pagelist != '') {
/// Print infobox $sql = "SELECT q.*, i.id AS instance,i.id as iid,".
"i.score AS score,i.studentanswer".
//$timelimit = (int)$game->timelimit * 60; " FROM {question} q,".
$timelimit = 0; " {game_queries} i".
$overtime = 0; " WHERE i.attemptid = '$attempt->id' AND q.id = i.questionid AND (i.sourcemodule='question' or i.sourcemodule = 'quiz')".
" AND q.id IN ($pagelist)";
if ($attempt->timefinish) {
if ($timetaken = ($attempt->timefinish - $attempt->timestart)) { if (!$questions = $DB->get_records_sql( $sql)) {
if($timelimit && $timetaken > ($timelimit + 60)) { print_error('No questions found');
$overtime = $timetaken - $timelimit; }
$overtime = format_time($overtime); } else {
} $questions = array();
$timetaken = format_time($timetaken); }
} else {
$timetaken = "-"; // Load the question type specific information.
if (!get_question_options( $questions)) {
print_error('Could not load question options');
}
$states = game_compute_states( $game, $questions);
// Print infobox.
$timelimit = 0;
$overtime = 0;
if ($attempt->timefinish) {
if ($timetaken = ($attempt->timefinish - $attempt->timestart)) {
if ($timelimit && $timetaken > ($timelimit + 60)) {
$overtime = $timetaken - $timelimit;
$overtime = format_time($overtime);
} }
$timetaken = format_time($timetaken);
} else { } else {
$timetaken = get_string('unfinished', 'game'); $timetaken = "-";
} }
} else {
$timetaken = get_string('unfinished', 'game');
}
$table->align = array("right", "left");
if ($attempt->userid <> $USER->id) {
$student = $DB->get_record('user', array( 'id' => $attempt->userid));
$picture = print_user_picture($student->id, $course->id, $student->picture, false, true);
$table->data[] = array($picture,
'<a href="'.$CFG->wwwroot.'/user/view.php?id='.$student->id.'&amp;course='.
$course->id.'">'.fullname($student, true).'</a>');
}
$table->align = array("right", "left"); if (count($attempts = $DB->get_records('game_attempts', array( 'gameid' => $game->id,
if ($attempt->userid <> $USER->id) { 'userid' => $attempt->userid), 'attempt ASC')) > 1) {
$student = $DB->get_record('user', array( 'id' => $attempt->userid)); // Print list of attempts.
$picture = print_user_picture($student->id, $course->id, $student->picture, false, true); $attemptlist = '';
$table->data[] = array($picture, '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$student->id.'&amp;course='.$course->id.'">'.fullname($student, true).'</a>'); foreach ($attempts as $at) {
$attemptlist .= ($at->id == $attempt->id) ? '<strong>'.$at->attempt.'</strong>, ' : '<a href="review.php?attempt='.
$at->id.($showall ? '&amp;showall=true' : '').'">'.$at->attempt.'</a>, ';
} }
//if (has_capability('mod/game:grade', $context)){ $table->data[] = array(get_string('attempts', 'game').':', trim($attemptlist, ' ,'));
if( count($attempts = $DB->get_records('game_attempts', array( 'gameid' => $game->id, 'userid' => $attempt->userid), 'attempt ASC')) > 1) { }
// print list of attempts
$attemptlist = ''; $table->data[] = array(get_string('startedon', 'game').':', userdate($attempt->timestart));
foreach ($attempts as $at) { if ($attempt->timefinish) {
$attemptlist .= ($at->id == $attempt->id) $table->data[] = array("$strtimecompleted:", userdate($attempt->timefinish));
? '<strong>'.$at->attempt.'</strong>, ' $table->data[] = array("$strtimetaken:", $timetaken);
: '<a href="review.php?attempt='.$at->id.($showall?'&amp;showall=true':'').'">'.$at->attempt.'</a>, '; }
}
$table->data[] = array(get_string('attempts', 'game').':', trim($attemptlist, ' ,')); // If the student is allowed to see their score.
if ($options->scores) {
if ($game->grade) {
if ($overtime) {
$result->sumgrades = "0";
$result->grade = "0.0";
} }
//}
$table->data[] = array(get_string('startedon', 'game').':', userdate($attempt->timestart)); $a = new stdClass;
if ($attempt->timefinish) { $percentage = round($attempt->score * 100, 0);
$table->data[] = array("$strtimecompleted:", userdate($attempt->timefinish)); $a->grade = game_score_to_grade( $attempt->score, $game);
$table->data[] = array("$strtimetaken:", $timetaken); $a->maxgrade = $game->grade;
$table->data[] = array("$strscore:", "{$a->grade}/{$game->grade} ($percentage %)");
} }
//if the student is allowed to see their score }
if ($options->scores) {
if ($game->grade) { if ($options->overallfeedback && $feedback) {
if($overtime) { $table->data[] = array(get_string('feedback', 'game'), $feedback);
$result->sumgrades = "0"; }
$result->grade = "0.0";
} if ($isteacher and $attempt->userid == $USER->id) {
// The teacher is at the end of a preview. Print button to start new preview.
$a = new stdClass; unset($buttonoptions);
$percentage = round($attempt->score*100, 0); $buttonoptions['q'] = $game->id;
$a->grade = game_score_to_grade( $attempt->score, $game); $buttonoptions['forcenew'] = true;
$a->maxgrade = $game->grade; echo '<div class="controls">';
$table->data[] = array("$strscore:", "{$a->grade}/{$game->grade} ($percentage %)"); print_single_button($CFG->wwwroot.'/mod/game/attempt.php', $buttonoptions, get_string('startagain', 'game'));
//$table->data[] = array("$strgrade:", get_string('outof', 'game', $a)); echo '</div>';
} else {
// Print number of the attempt.
print_heading(get_string('reviewofattempt', 'game', $attempt->attempt));
}
print_table($table);
// Print javascript button to close the window, if necessary.
if (!$isteacher) {
include('attempt_close_js.php');
}
// Print the navigation panel if required.
$numpages = game_number_of_pages( $attempt->layout);
if ($numpages > 1 and !$showall) {
print_paging_bar($numpages, $page, 1, 'review.php?attempt='.$attempt->id.'&amp;');
echo '<div class="controls"><a href="review.php?attempt='.$attempt->id.'&amp;showall=true">';
print_string('showall', 'game');
echo '</a></div>';
}
// Print all the questions.
if ($pagelist) {
game_print_questions( $pagelist, $attempt, $questions, $options, $states, $game);
}
// Print the navigation panel if required.
if ($numpages > 1 and !$showall) {
print_paging_bar($numpages, $page, 1, 'review.php?attempt='.$attempt->id.'&amp;');
}
// Print javascript button to close the window, if necessary.
if (!$isteacher) {
require('attempt_close_js.php');
}
if (empty($popup)) {
echo $OUTPUT->footer($course);
}
function game_compute_states( $game, $questions) {
global $QTYPES;
// Restore the question sessions to their most recent states creating new sessions where required.
$states = array();
foreach ($questions as $question) {
$state = new StdClass;
$cmoptions->course = $game->course;
$cmoptions->optionflags->optionflags = 0;
$cmoptions->id = 0;
$cmoptions->shuffleanswers = 1;
$state->last_graded = new StdClass;
$state->last_graded->event = QUESTION_EVENTOPEN;
$state->raw_grade = 0;
$attempt = 0;
if (!$QTYPES[$question->qtype]->create_session_and_responses( $question, $state, $cmoptions, $attempt)) {
print_error( 'game_compute_states: problem');
} }
}
if ($options->overallfeedback && $feedback) {
$table->data[] = array(get_string('feedback', 'game'), $feedback);
}
if ($isteacher and $attempt->userid == $USER->id) {
// the teacher is at the end of a preview. Print button to start new preview
unset($buttonoptions);
$buttonoptions['q'] = $game->id;
$buttonoptions['forcenew'] = true;
echo '<div class="controls">';
print_single_button($CFG->wwwroot.'/mod/game/attempt.php', $buttonoptions, get_string('startagain', 'game'));
echo '</div>';
} else { // print number of the attempt
print_heading(get_string('reviewofattempt', 'game', $attempt->attempt));
}
print_table($table);
// print javascript button to close the window, if necessary $state->event = QUESTION_EVENTOPEN;
if (!$isteacher) { $state->manualcomment = '';
include('attempt_close_js.php');
}
/// Print the navigation panel if required $state->responses = array( '' => $question->studentanswer);
$numpages = game_number_of_pages( $attempt->layout); $state->attempt = $question->iid;
if ($numpages > 1 and !$showall) {
print_paging_bar($numpages, $page, 1, 'review.php?attempt='.$attempt->id.'&amp;');
echo '<div class="controls"><a href="review.php?attempt='.$attempt->id.'&amp;showall=true">';
print_string('showall', 'game');
echo '</a></div>';
}
/// Print all the questions $states[ $question->id] = $state;
if( $pagelist){
game_print_questions( $pagelist, $attempt, $questions, $options, $states, $game);
} }
return $states;
}
// Print the navigation panel if required function game_print_questions( $pagelist, $attempt, $questions, $options, $states, $game) {
if ($numpages > 1 and !$showall) { $pagequestions = explode(',', $pagelist);
print_paging_bar($numpages, $page, 1, 'review.php?attempt='.$attempt->id.'&amp;'); $number = game_first_questionnumber( $attempt->layout, $pagelist);
} foreach ($pagequestions as $i) {
if (!isset($questions[$i])) {
echo $OUTPUT->box_start('center', '90%');
echo '<strong><font size="+1">' . $number . '</font></strong><br />';
notify(get_string('errormissingquestion', 'quiz', $i));
echo $OUTPUT->box_end();
$number++; // Just guessing that the missing question would have lenght 1.
continue;
}
$options->validation = QUESTION_EVENTVALIDATE === $states[$i]->event;
$options->history = false;
unset( $options->questioncommentlink);
// print javascript button to close the window, if necessary // Print the question.
if (!$isteacher) { if ($i > 0) {
include('attempt_close_js.php'); echo "<br />\n";
} }
$questions[$i]->maxgrade = 0;
if (empty($popup)) { $options->correct_responses = 0;
echo $OUTPUT->footer($course); $options->feedback = 0;
$options->readonly = 0;
global $QTYPES;
unset( $cmoptions);
$cmoptions->course = $game->course;
$cmoptions->optionflags->optionflags = 0;
$cmoptions->id = 0;
$cmoptions->shuffleanswers = 1;
$attempt = 0;
$question = $questions[ $i];
if (!$QTYPES[$question->qtype]->create_session_and_responses( $question, $state, $cmoptions, $attempt)) {
print_error( 'game_sudoku_showquestions_quiz: problem');
}
$cmoptions->optionflags = 0;
print_question( $question, $states[$i], $number, $cmoptions, $options);
$number += $questions[$i]->length;
} }
}
function game_compute_states( $game, $questions)
{
global $QTYPES;
// Restore the question sessions to their most recent states
// creating new sessions where required
$states = array();
foreach ($questions as $question) {
$state = new StdClass;
$cmoptions->course = $game->course;
$cmoptions->optionflags->optionflags = 0;
$cmoptions->id = 0;
$cmoptions->shuffleanswers = 1;
$state->last_graded = new StdClass;
$state->last_graded->event = QUESTION_EVENTOPEN;
$state->raw_grade = 0;
$attempt = 0;
if (!$QTYPES[$question->qtype]->create_session_and_responses( $question, $state, $cmoptions, $attempt)) {
print_error( 'game_compute_states: problem');
}
$state->event = QUESTION_EVENTOPEN;
//$question->maxgrade = 100;
$state->manualcomment = '';
$state->responses = array( '' => $question->studentanswer);
$state->attempt = $question->iid;
$states[ $question->id] = $state;
}
return $states;
}
function game_print_questions( $pagelist, $attempt, $questions, $options, $states, $game)
{
$pagequestions = explode(',', $pagelist);
$number = game_first_questionnumber( $attempt->layout, $pagelist);
foreach ($pagequestions as $i) {
if (!isset($questions[$i])) {
echo $OUTPUT->box_start('center', '90%');
echo '<strong><font size="+1">' . $number . '</font></strong><br />';
notify(get_string('errormissingquestion', 'quiz', $i));
echo $OUTPUT->box_end();
$number++; // Just guessing that the missing question would have lenght 1
continue;
}
$options->validation = QUESTION_EVENTVALIDATE === $states[$i]->event;
//$options->history = ($isteacher and !$attempt->preview) ? 'all' : 'graded';
$options->history = false;
unset( $options->questioncommentlink);
// Print the question
if ($i > 0) {
echo "<br />\n";
}
$questions[$i]->maxgrade = 0;
$options->correct_responses = 0;
$options->feedback = 0;
$options->readonly = 0;
global $QTYPES;
unset( $cmoptions);
$cmoptions->course = $game->course;
$cmoptions->optionflags->optionflags = 0;
$cmoptions->id = 0;
$cmoptions->shuffleanswers = 1;
$attempt = 0;
$question = $questions[ $i];
if (!$QTYPES[$question->qtype]->create_session_and_responses( $question, $state, $cmoptions, $attempt)) {
print_error( 'game_sudoku_showquestions_quiz: problem');
}
$cmoptions->optionflags = 0;
print_question( $question, $states[$i], $number, $cmoptions, $options);
$number += $questions[$i]->length;
}
}
?>

19
settings.php

@ -1,4 +1,19 @@
<?php // $Id: settings.php <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* Form for creating and modifying a game * Form for creating and modifying a game
* *
@ -12,7 +27,7 @@ defined('MOODLE_INTERNAL') || die;
if ($ADMIN->fulltree) { if ($ADMIN->fulltree) {
require_once(dirname(__FILE__).'/lib.php'); require_once(dirname(__FILE__).'/lib.php');
// General settings // General settings.
$settings->add(new admin_setting_configcheckbox('game/hidebookquiz', $settings->add(new admin_setting_configcheckbox('game/hidebookquiz',
get_string('hidebookquiz', 'game'), get_string('confighidebookquiz', 'game'), 0)); get_string('hidebookquiz', 'game'), get_string('confighidebookquiz', 'game'), 0));

446
showanswers.php

@ -1,4 +1,19 @@
<?php // $Id: showanswers.php,v 1.7 2012/07/25 22:46:42 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* This page shows the answers of the current game * This page shows the answers of the current game
* *
@ -6,49 +21,53 @@
* @version $Id: showanswers.php,v 1.7 2012/07/25 22:46:42 bdaloukas Exp $ * @version $Id: showanswers.php,v 1.7 2012/07/25 22:46:42 bdaloukas Exp $
* @package game * @package game
**/ **/
require_once("../../config.php");
require_once( "headergame.php");
if (!has_capability('mod/game:viewreports', $context)){ require_once("../../config.php");
print_error( get_string( 'only_teachers', 'game')); require_once( "headergame.php");
}
if (!has_capability('mod/game:viewreports', $context)) {
print_error( get_string( 'only_teachers', 'game'));
}
$PAGE->navbar->add(get_string('showanswers', 'game')); $PAGE->navbar->add(get_string('showanswers', 'game'));
$action = optional_param('action', "", PARAM_ALPHANUM); // action $action = optional_param('action', "", PARAM_ALPHANUM); // Action.
if( $action == 'delstats') if ($action == 'delstats') {
$DB->delete_records('game_repetitions', array('gameid' => $game->id, 'userid' => $USER->id)); $DB->delete_records('game_repetitions', array('gameid' => $game->id, 'userid' => $USER->id));
if( $action == 'computestats') }
game_compute_repetitions($game); if ($action == 'computestats') {
game_compute_repetitions($game);
}
echo '<b>'.get_string('repetitions', 'game').': &nbsp;&nbsp;</b>'; echo '<b>'.get_string('repetitions', 'game').': &nbsp;&nbsp;</b>';
echo get_string('user').': '; echo get_string('user').': ';
game_showusers($game); game_showusers($game);
echo " &nbsp;<a href=\"{$CFG->wwwroot}/mod/game/showanswers.php?q=$q&action=delstats\">".get_string('clearrepetitions','game').'</a>'; echo " &nbsp;<a href=\"{$CFG->wwwroot}/mod/game/showanswers.php?q=$q&action=delstats\">".
echo " &nbsp;&nbsp;<a href=\"{$CFG->wwwroot}/mod/game/showanswers.php?q=$q&action=computestats\">".get_string('computerepetitions','game').'</a>'; get_string('clearrepetitions', 'game').'</a>';
echo '<br><br>'; echo " &nbsp;&nbsp;<a href=\"{$CFG->wwwroot}/mod/game/showanswers.php?q=$q&action=computestats\">".
get_string('computerepetitions', 'game').'</a>';
echo '<br><br>';
$existsbook = ($DB->get_record( 'modules', array( 'name' => 'book'), 'id,id')); $existsbook = ($DB->get_record( 'modules', array( 'name' => 'book'), 'id,id'));
game_showanswers( $game, $existsbook, $context); game_showanswers( $game, $existsbook, $context);
echo $OUTPUT->footer(); echo $OUTPUT->footer();
function game_compute_repetitions($game){ function game_compute_repetitions($game) {
global $DB, $USER; global $DB, $USER;
$DB->delete_records('game_repetitions', array('gameid' => $game->id,'userid' => $USER->id)); $DB->delete_records('game_repetitions', array('gameid' => $game->id, 'userid' => $USER->id));
$sql = "INSERT INTO {game_repetitions}( gameid,userid,questionid,glossaryentryid,repetitions) ". $sql = "INSERT INTO {game_repetitions}( gameid,userid,questionid,glossaryentryid,repetitions) ".
"SELECT $game->id,$USER->id,questionid,glossaryentryid,COUNT(*) ". "SELECT $game->id,$USER->id,questionid,glossaryentryid,COUNT(*) ".
"FROM {game_queries} WHERE gameid=$game->id AND userid=$USER->id GROUP BY questionid,glossaryentryid"; "FROM {game_queries} WHERE gameid=$game->id AND userid=$USER->id GROUP BY questionid,glossaryentryid";
if( !$DB->execute( $sql)) if (!$DB->execute( $sql)) {
print_error('Problem on computing statistics for repetitions'); print_error('Problem on computing statistics for repetitions');
}
} }
function game_showusers($game) function game_showusers($game) {
{
global $CFG, $USER; global $CFG, $USER;
$users = array(); $users = array();
@ -63,11 +82,13 @@ function game_showusers($game)
if ($guest = guest_user()) { if ($guest = guest_user()) {
$users[$guest->id] = fullname($guest); $users[$guest->id] = fullname($guest);
} }
$href = $CFG->wwwroot.'/mod/game/showanswers.php?q='.$game->id.'&userid=';
?> ?>
<script type="text/javascript"> <script type="text/javascript">
function onselectuser() function onselectuser()
{ {
window.location.href = "<?php echo $CFG->wwwroot.'/mod/game/showanswers.php?q='.$game->id.'&userid=';?>" + document.getElementById('menuuser').value; window.location.href =
"<?php echo $href;?>" + document.getElementById('menuuser').value;
} }
</script> </script>
<?php <?php
@ -76,11 +97,11 @@ function game_showusers($game)
$name = 'user'; $name = 'user';
$id = 'menu'.$name; $id = 'menu'.$name;
$class = 'menu'.$name; $class = 'menu'.$name;
$class = 'select ' . $class; /// Add 'select' selector always $class = 'select ' . $class; // Add 'select' selector always.
$nothing = get_string("allparticipants"); $nothing = get_string("allparticipants");
$nothingvalue='0'; $nothingvalue = '0';
$options = $users; $options = $users;
$selected = optional_param('userid',$USER->id,PARAM_INT); $selected = optional_param('userid', $USER->id, PARAM_INT);
$output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n"; $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
$output .= ' <option value="'. s($nothingvalue) .'"'. "\n"; $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
@ -106,219 +127,222 @@ function game_showusers($game)
echo $output . '</select>' . "\n"; echo $output . '</select>' . "\n";
} }
function game_showanswers( $game, $existsbook, $context) function game_showanswers( $game, $existsbook, $context) {
{ if ($game->gamekind == 'bookquiz' and $existsbook) {
if( $game->gamekind == 'bookquiz' and $existsbook){
game_showanswers_bookquiz( $game, $context); game_showanswers_bookquiz( $game, $context);
return; return;
} }
switch( $game->sourcemodule){ switch ($game->sourcemodule) {
case 'question': case 'question':
game_showanswers_question( $game, $context); game_showanswers_question( $game, $context);
break; break;
case 'glossary': case 'glossary':
game_showanswers_glossary( $game); game_showanswers_glossary( $game);
break; break;
case 'quiz': case 'quiz':
game_showanswers_quiz( $game, $context); game_showanswers_quiz( $game, $context);
break; break;
} }
} }
function game_showanswers_appendselect( $game) function game_showanswers_appendselect( $game) {
{ switch ($game->gamekind) {
switch( $game->gamekind){ case 'hangman':
case 'hangman': case 'cross':
case 'cross': case 'crypto':
case 'crypto': return " AND qtype='shortanswer'";
return " AND qtype='shortanswer'"; case 'millionaire':
case 'millionaire': return " AND qtype = 'multichoice'";
return " AND qtype = 'multichoice'"; case 'sudoku':
case 'sudoku': case 'bookquiz':
case 'bookquiz': case 'snakes':
case 'snakes': return " AND qtype in ('shortanswer', 'truefalse', 'multichoice')";
return " AND qtype in ('shortanswer', 'truefalse', 'multichoice')";
} }
return ''; return '';
} }
function game_showanswers_question( $game, $context) function game_showanswers_question( $game, $context) {
{
global $DB; global $DB;
if( $game->gamekind != 'bookquiz'){ if ($game->gamekind != 'bookquiz') {
$select = ' category='.$game->questioncategoryid; $select = ' category='.$game->questioncategoryid;
if( $game->subcategories){ if ($game->subcategories) {
$cats = question_categorylist( $game->questioncategoryid); $cats = question_categorylist( $game->questioncategoryid);
if( strpos( $cats, ',') > 0){ if (strpos( $cats, ',') > 0) {
$select = ' category in ('.$cats.')'; $select = ' category in ('.$cats.')';
} }
} }
}else } else {
{
$context2 = get_context_instance(50, $COURSE->id); $context2 = get_context_instance(50, $COURSE->id);
$select = " contextid in ($context2->id)"; $select = " contextid in ($context2->id)";
$select2 = ''; $select2 = '';
if( $recs = $DB->get_records_select( 'question_categories', $select, null, 'id,id')){ if ($recs = $DB->get_records_select( 'question_categories', $select, null, 'id,id')) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$select2 .= ','.$rec->id; $select2 .= ','.$rec->id;
} }
} }
$select = ' AND category IN ('.substr( $select2, 1).')'; $select = ' AND category IN ('.substr( $select2, 1).')';
} }
$select .= ' AND hidden = 0 '; $select .= ' AND hidden = 0 ';
$select .= game_showanswers_appendselect( $game); $select .= game_showanswers_appendselect( $game);
$showcategories = ($game->gamekind == 'bookquiz'); $showcategories = ($game->gamekind == 'bookquiz');
$order = ($showcategories ? 'category,questiontext' : 'questiontext'); $order = ($showcategories ? 'category,questiontext' : 'questiontext');
game_showanswers_question_select( $game, '{question} q', $select, '*', $order, $showcategories, $game->course, $context); game_showanswers_question_select( $game, '{question} q', $select, '*', $order, $showcategories, $game->course, $context);
} }
function game_showanswers_quiz( $game, $context) {
function game_showanswers_quiz( $game, $context)
{
global $CFG; global $CFG;
$select = "quiz='$game->quizid' ". $select = "quiz='$game->quizid' ".
' AND qqi.question=q.id'. ' AND qqi.question=q.id'.
' AND q.hidden=0'. ' AND q.hidden=0'.
game_showanswers_appendselect( $game); game_showanswers_appendselect( $game);
$table = '{question} q,{quiz_question_instances} qqi'; $table = '{question} q,{quiz_question_instances} qqi';
game_showanswers_question_select( $game, $table, $select, 'q.*', 'category,questiontext', false, $game->course, $context); game_showanswers_question_select( $game, $table, $select, 'q.*', 'category,questiontext', false, $game->course, $context);
} }
function game_showanswers_question_select( $game, $table, $select, $fields, $order, $showcategoryname, $courseid, $context) {
function game_showanswers_question_select( $game, $table, $select, $fields, $order, $showcategoryname, $courseid, $context)
{
global $CFG, $DB, $OUTPUT; global $CFG, $DB, $OUTPUT;
$sql = "SELECT $fields FROM $table WHERE $select ORDER BY $order"; $sql = "SELECT $fields FROM $table WHERE $select ORDER BY $order";
if( ($questions = $DB->get_records_sql( $sql)) === false){ if (($questions = $DB->get_records_sql( $sql)) === false) {
return; return;
} }
$table .= ",{game_repetitions} gr"; $table .= ",{game_repetitions} gr";
$select .= " AND gr.questionid=q.id AND gr.glossaryentryid=0 AND gr.gameid=".$game->id; $select .= " AND gr.questionid=q.id AND gr.glossaryentryid=0 AND gr.gameid=".$game->id;
$userid = optional_param('userid',0,PARAM_INT); $userid = optional_param('userid', 0, PARAM_INT);
if( $userid) if ($userid) {
$select .= " AND gr.userid=$userid"; $select .= " AND gr.userid=$userid";
}
$sql = "SELECT q.id as id,SUM(repetitions) as c FROM {$table} WHERE $select GROUP BY q.id"; $sql = "SELECT q.id as id,SUM(repetitions) as c FROM {$table} WHERE $select GROUP BY q.id";
$reps = $DB->get_records_sql( $sql); $reps = $DB->get_records_sql( $sql);
$categorynames = array(); $categorynames = array();
if( $showcategoryname){ if ($showcategoryname) {
$select = ''; $select = '';
$recs = $DB->get_records( 'question_categories', null, '', '*', 0, 1); $recs = $DB->get_records( 'question_categories', null, '', '*', 0, 1);
foreach( $recs as $rec){ foreach ($recs as $rec) {
if( array_key_exists( 'course', $rec)){ if (array_key_exists( 'course', $rec)) {
$select = "course=$courseid"; $select = "course=$courseid";
}else{ } else {
$context = get_context_instance(50, $courseid); $context = get_context_instance(50, $courseid);
$select = " contextid in ($context->id)"; $select = " contextid in ($context->id)";
} }
break; break;
} }
if( ($categories = $DB->get_records_select( 'question_categories', $select, null, '', 'id,name'))){ if (($categories = $DB->get_records_select( 'question_categories', $select, null, '', 'id,name'))) {
foreach( $categories as $rec){ foreach ($categories as $rec) {
$categorynames[ $rec->id] = $rec->name; $categorynames[ $rec->id] = $rec->name;
} }
} }
} }
echo '<table border="1">'; echo '<table border="1">';
echo '<tr><td></td>'; echo '<tr><td></td>';
if( $showcategoryname){ if ($showcategoryname) {
echo '<td><b>'.get_string( 'categories', 'quiz').'</b></td>'; echo '<td><b>'.get_string( 'categories', 'quiz').'</b></td>';
} }
echo '<td><b>'.get_string( 'questions', 'quiz').'</b></td>'; echo '<td><b>'.get_string( 'questions', 'quiz').'</b></td>';
echo '<td><b>'.get_string( 'answers', 'quiz').'</b></td>'; echo '<td><b>'.get_string( 'answers', 'quiz').'</b></td>';
echo '<td><b>'.get_string( 'feedbacks', 'game').'</b></td>'; echo '<td><b>'.get_string( 'feedbacks', 'game').'</b></td>';
if( $reps) if ($reps) {
echo '<td><b>'.get_string( 'repetitions', 'game').'</b></td>'; echo '<td><b>'.get_string( 'repetitions', 'game').'</b></td>';
}
echo "</tr>\r\n"; echo "</tr>\r\n";
$line = 0; $line = 0;
foreach( $questions as $question){ foreach ($questions as $question) {
echo '<tr>'; echo '<tr>';
echo '<td>'.(++$line); echo '<td>'.(++$line);
echo '</td>'; echo '</td>';
if( $showcategoryname){ if ($showcategoryname) {
echo '<td>'; echo '<td>';
if( array_key_exists( $question->category, $categorynames)){ if (array_key_exists( $question->category, $categorynames)) {
echo $categorynames[ $question->category]; echo $categorynames[ $question->category];
}else{ } else {
echo '&nbsp;'; echo '&nbsp;';
} }
echo '</td>'; echo '</td>';
} }
echo '<td>'; echo '<td>';
echo "<a title=\"Edit\" href=\"{$CFG->wwwroot}/question/question.php?inpopup=1&amp;id=$question->id&courseid=$courseid\" target=\"_blank\"><img src=\"".$OUTPUT->pix_url('t/edit')."\" alt=\"Edit\" /></a> "; echo "<a title=\"Edit\" ".
"href=\"{$CFG->wwwroot}/question/question.php?inpopup=1&amp;id=$question->id&courseid=$courseid\" target=\"_blank\">";
echo game_filterquestion(str_replace( array( "\'", '\"'), array( "'", '"'), $question->questiontext), $question->id, $context->id, $game->course); echo "<img src=\"".$OUTPUT->pix_url('t/edit')."\" alt=\"Edit\" /></a> ";
switch( $question->qtype){ echo game_filterquestion(str_replace( array( "\'", '\"'), array( "'", '"'),
case 'shortanswer': $question->questiontext), $question->id, $context->id, $game->course);
$recs = $DB->get_records( 'question_answers', array( 'question' => $question->id), 'fraction DESC', 'id,answer,feedback');
if( $recs == false){ switch ($question->qtype) {
$rec = false; case 'shortanswer':
}else{ $recs = $DB->get_records( 'question_answers',
foreach( $recs as $rec) array( 'question' => $question->id), 'fraction DESC', 'id,answer,feedback');
break; if ($recs == false) {
} $rec = false;
echo "<td>$rec->answer</td>"; } else {
if( $rec->feedback == '') foreach ($recs as $rec) {
$rec->feedback = '&nbsp;'; break;
echo "<td>$rec->feedback</td>"; }
break; }
case 'multichoice': echo "<td>$rec->answer</td>";
case 'truefalse': if ($rec->feedback == '') {
$recs = $DB->get_records( 'question_answers', array( 'question' => $question->id)); $rec->feedback = '&nbsp;';
$feedback = ''; }
echo '<td>'; echo "<td>$rec->feedback</td>";
$i = 0; break;
foreach( $recs as $rec){ case 'multichoice':
if( $i++ > 0) case 'truefalse':
echo '<br>'; $recs = $DB->get_records( 'question_answers', array( 'question' => $question->id));
if( $rec->fraction == 1){ $feedback = '';
echo " <b>$rec->answer</b>"; echo '<td>';
if( $rec->feedback == '') $i = 0;
$feedback .= '<br>'; foreach ($recs as $rec) {
else if ($i++ > 0) {
echo '<br>';
}
if ($rec->fraction == 1) {
echo " <b>$rec->answer</b>";
if ($rec->feedback == '') {
$feedback .= '<br>';
}
} else {
$feedback .= "<b>$rec->feedback</b><br>"; $feedback .= "<b>$rec->feedback</b><br>";
}
}else } else {
{ echo " $rec->answer";
echo " $rec->answer"; if ($rec->feedback == '') {
if( $rec->feedback == '') $feedback .= '<br>';
$feedback .= '<br>'; } else {
else
$feedback .= "<br>"; $feedback .= "<br>";
}
} }
} echo '</td>';
echo '</td>'; if ($feedback == '') {
if( $feedback == '') $feedback = '&nbsp;';
$feedback = '&nbsp;'; }
echo "<td>$feedback</td>"; echo "<td>$feedback</td>";
break; break;
default: default:
echo "<td>$question->qtype</td>"; echo "<td>$question->qtype</td>";
break; break;
} }
//Show repetitions // Show repetitions.
if( $reps){ if ($reps) {
if( array_key_exists( $question->id, $reps)){ if (array_key_exists( $question->id, $reps)) {
$rep = $reps[ $question->id]; $rep = $reps[ $question->id];
echo '<td><center>'.$rep->c.'</td>'; echo '<td><center>'.$rep->c.'</td>';
}else } else {
echo '<td>&nbsp;</td>'; echo '<td>&nbsp;</td>';
}
} }
echo "</tr>\r\n"; echo "</tr>\r\n";
@ -326,54 +350,57 @@ function game_showanswers_question_select( $game, $table, $select, $fields, $ord
echo "</table><br>\r\n\r\n"; echo "</table><br>\r\n\r\n";
} }
function game_showanswers_glossary( $game) function game_showanswers_glossary( $game) {
{
global $CFG, $DB; global $CFG, $DB;
$table = '{glossary_entries} ge'; $table = '{glossary_entries} ge';
$select = "glossaryid={$game->glossaryid}"; $select = "glossaryid={$game->glossaryid}";
if( $game->glossarycategoryid){ if ($game->glossarycategoryid) {
$select .= " AND gec.entryid = ge.id ". $select .= " AND gec.entryid = ge.id ".
" AND gec.categoryid = {$game->glossarycategoryid}"; " AND gec.categoryid = {$game->glossarycategoryid}";
$table .= ",{glossary_entries_categories} gec"; $table .= ",{glossary_entries_categories} gec";
} }
$sql = "SELECT ge.id,definition,concept FROM $table WHERE $select ORDER BY definition"; $sql = "SELECT ge.id,definition,concept FROM $table WHERE $select ORDER BY definition";
if( ($questions = $DB->get_records_sql( $sql)) === false){ if (($questions = $DB->get_records_sql( $sql)) === false) {
return; return;
} }
//Show repetitions of questions // Show repetitions of questions.
$table = "{glossary_entries} ge, {game_repetitions} gr"; $table = "{glossary_entries} ge, {game_repetitions} gr";
$select = "glossaryid={$game->glossaryid} AND gr.glossaryentryid=ge.id AND gr.gameid=".$game->id; $select = "glossaryid={$game->glossaryid} AND gr.glossaryentryid=ge.id AND gr.gameid=".$game->id;
$userid = optional_param('userid',0,PARAM_INT); $userid = optional_param('userid', 0, PARAM_INT);
if( $userid) if ($userid) {
$select .= " AND gr.userid=$userid"; $select .= " AND gr.userid=$userid";
if( $game->glossarycategoryid){ }
$select .= " AND gec.entryid = ge.id ". if ($game->glossarycategoryid) {
" AND gec.categoryid = {$game->glossarycategoryid}"; $select .= " AND gec.entryid = ge.id ".
" AND gec.categoryid = {$game->glossarycategoryid}";
$table .= ",{glossary_entries_categories} gec"; $table .= ",{glossary_entries_categories} gec";
} }
$sql = "SELECT ge.id,SUM(repetitions) as c FROM {$table} WHERE $select GROUP BY ge.id"; $sql = "SELECT ge.id,SUM(repetitions) as c FROM {$table} WHERE $select GROUP BY ge.id";
$reps = $DB->get_records_sql( $sql); $reps = $DB->get_records_sql( $sql);
echo '<table border="1">'; echo '<table border="1">';
echo '<tr><td></td>'; echo '<tr><td></td>';
echo '<td><b>'.get_string( 'questions', 'quiz').'</b></td>'; echo '<td><b>'.get_string( 'questions', 'quiz').'</b></td>';
echo '<td><b>'.get_string( 'answers', 'quiz').'</b></td>'; echo '<td><b>'.get_string( 'answers', 'quiz').'</b></td>';
if( $reps != false) if ($reps != false) {
echo '<td><b>'.get_string( 'repetitions', 'game').'</b></td>'; echo '<td><b>'.get_string( 'repetitions', 'game').'</b></td>';
}
echo "</tr>\r\n"; echo "</tr>\r\n";
$line = 0; $line = 0;
foreach( $questions as $question){ foreach ($questions as $question) {
if( $game->param7 == 0){ //Not allowed spaces if ($game->param7 == 0) { // Not allowed spaces.
if(!( strpos( $question->concept, ' ') === false)) if (!( strpos( $question->concept, ' ') === false)) {
continue; continue;
}
} }
if( $game->param8 == 0){ //Not allowed - if ($game->param8 == 0) { // Not allowed -.
if(!( strpos( $question->concept, '-') === false)) if (!( strpos( $question->concept, '-') === false)) {
continue; continue;
}
} }
echo '<tr>'; echo '<tr>';
echo '<td>'.(++$line); echo '<td>'.(++$line);
echo '</td>'; echo '</td>';
@ -383,30 +410,29 @@ function game_showanswers_glossary( $game)
$query->glossaryentryid = $question->id; $query->glossaryentryid = $question->id;
echo '<td>'.game_show_query( $game, $query, $question->definition).'</td>'; echo '<td>'.game_show_query( $game, $query, $question->definition).'</td>';
echo '<td>'.$question->concept.'</td>'; echo '<td>'.$question->concept.'</td>';
if( $reps != false){ if ($reps != false) {
if( array_key_exists( $question->id, $reps)) if (array_key_exists( $question->id, $reps)) {
{
$rep = $reps[ $question->id]; $rep = $reps[ $question->id];
echo '<td><center>'.$rep->c.'</td>'; echo '<td><center>'.$rep->c.'</td>';
}else } else {
echo '<td>&nbsp;</td>'; echo '<td>&nbsp;</td>';
}
} }
echo "</tr>\r\n"; echo "</tr>\r\n";
} }
echo "</table><br>\r\n\r\n"; echo "</table><br>\r\n\r\n";
} }
function game_showanswers_bookquiz( $game, $context) function game_showanswers_bookquiz( $game, $context) {
{
global $CFG; global $CFG;
$select = "gbq.questioncategoryid=q.category ". $select = "gbq.questioncategoryid=q.category ".
" AND gbq.gameid = $game->id ". " AND gbq.gameid = $game->id ".
" AND bc.id = gbq.chapterid"; " AND bc.id = gbq.chapterid";
$table = "{question} q,{game_bookquiz_questions} gbq,{book_chapters} bc"; $table = "{question} q,{game_bookquiz_questions} gbq,{book_chapters} bc";
$showcategories = ($game->gamekind == 'bookquiz'); $showcategories = ($game->gamekind == 'bookquiz');
game_showanswers_question_select( $game, $table, $select, "DISTINCT q.*", "bc.pagenum,questiontext", $showcategories, $game->course, $context); game_showanswers_question_select( $game, $table, $select, "DISTINCT q.*",
"bc.pagenum,questiontext", $showcategories, $game->course, $context);
} }

454
showattempts.php

@ -1,4 +1,19 @@
<?php // $Id: showattempts.php,v 1.6 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* This page shows the answers of the current game * This page shows the answers of the current game
* *
@ -6,256 +21,259 @@
* @version $Id: showattempts.php,v 1.6 2012/07/25 11:16:04 bdaloukas Exp $ * @version $Id: showattempts.php,v 1.6 2012/07/25 11:16:04 bdaloukas Exp $
* @package game * @package game
**/ **/
require_once("../../config.php");
require_once( "headergame.php");
if (!has_capability('mod/game:viewreports', $context)){ require_once("../../config.php");
print_error( get_string( 'only_teachers', 'game')); require_once( "headergame.php");
}
$PAGE->navbar->add(get_string('showattempts', 'game')); if (!has_capability('mod/game:viewreports', $context)) {
print_error( get_string( 'only_teachers', 'game'));
}
$action = optional_param('action', "", PARAM_ALPHANUM); // action $PAGE->navbar->add(get_string('showattempts', 'game'));
if( $action == 'delete'){
game_ondeleteattempt( $game); $action = optional_param('action', "", PARAM_ALPHANUM); // Action.
} if ($action == 'delete') {
game_ondeleteattempt( $game);
}
echo get_string( 'group').': ';
game_showgroups( $game);
echo ' &nbsp; '.get_string('user').': ';
game_showusers( $game);echo '<br><br>';
game_showattempts( $game);
echo $OUTPUT->footer();
function game_showusers($game) {
global $CFG, $USER, $DB;
echo get_string( 'group').': '; $users = array();
game_showgroups( $game);
echo ' &nbsp; '.get_string('user').': '; $context = game_get_context_course_instance( $game->course);
game_showusers( $game);echo '<br><br>';
$groupid = optional_param('groupid', 0, PARAM_INT);
game_showattempts( $game); $sql = "SELECT DISTINCT ra.userid,u.lastname,u.firstname FROM {role_assignments} ra, {user} u ".
" WHERE ra.contextid={$context->id} AND ra.userid=u.id";
echo $OUTPUT->footer(); if ($groupid != 0) {
$sql .= " AND ra.userid IN (SELECT gm.userid FROM {groups_members} gm WHERE gm.groupid=$groupid)";
}
function game_showusers($game) if (($recs = $DB->get_records_sql( $sql))) {
{ foreach ($recs as $rec) {
global $CFG, $USER, $DB; $users[ $rec->userid] = $rec->lastname.' '.$rec->firstname;
$users = array();
$context = game_get_context_course_instance( $game->course);
$groupid = optional_param('groupid',0, PARAM_INT);
$sql = "SELECT DISTINCT ra.userid,u.lastname,u.firstname FROM {role_assignments} ra, {user} u ".
" WHERE ra.contextid={$context->id} AND ra.userid=u.id";
if( $groupid != 0)
$sql .= " AND ra.userid IN (SELECT gm.userid FROM {groups_members} gm WHERE gm.groupid=$groupid)";
if( ($recs = $DB->get_records_sql( $sql))){
foreach( $recs as $rec){
$users[ $rec->userid] = $rec->lastname.' '.$rec->firstname;
}
}
if ($guest = guest_user()) {
$users[$guest->id] = fullname($guest);
} }
?> }
if ($guest = guest_user()) {
$users[$guest->id] = fullname($guest);
}
$href = $CFG->wwwroot.'/mod/game/showattempts.php?q='.$game->id.'&userid=';
?>
<script type="text/javascript"> <script type="text/javascript">
function onselectuser() function onselectuser()
{ {
window.location.href = "<?php echo $CFG->wwwroot.'/mod/game/showattempts.php?q='.$game->id.'&userid=';?>" + document.getElementById('menuuser').value + '&groupid=' + document.getElementById('menugroup').value; var groupid = document.getElementById('menugroup').value;
window.location.href = "<?php echo href;?>" + document.getElementById('menuuser').value + '&groupid=' + groupid;
} }
</script> </script>
<?php <?php
$attributes = 'onchange="javascript:onselectuser();"'; $attributes = 'onchange="javascript:onselectuser();"';
$name = 'user'; $name = 'user';
$id = 'menu'.$name; $id = 'menu'.$name;
$class = 'menu'.$name; $class = 'menu'.$name;
$class = 'select ' . $class; /// Add 'select' selector always $class = 'select ' . $class; // Add 'select' selector always.
$nothing = get_string("allparticipants"); $nothing = get_string("allparticipants");
$nothingvalue='0'; $nothingvalue = '0';
$options = $users; $options = $users;
$selected = optional_param('userid',0, PARAM_INT); $selected = optional_param('userid', 0, PARAM_INT);
$output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n"; $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
$output .= ' <option value="'. s($nothingvalue) .'"'. "\n"; $output .= ' <option value="'. s($nothingvalue) .'"'. "\n";
if ($nothingvalue === $selected) { if ($nothingvalue === $selected) {
$output .= ' selected="selected"'; $output .= ' selected="selected"';
} }
$output .= '>'. $nothing .'</option>' . "\n"; $output .= '>'. $nothing .'</option>' . "\n";
if (!empty($options)) { if (!empty($options)) {
foreach ($options as $value => $label) { foreach ($options as $value => $label) {
$output .= ' <option value="'. s($value) .'"'; $output .= ' <option value="'. s($value) .'"';
if ((string)$value == (string)$selected || if ((string)$value == (string)$selected ||
(is_array($selected) && in_array($value, $selected))) { (is_array($selected) && in_array($value, $selected))) {
$output .= ' selected="selected"'; $output .= ' selected="selected"';
} }
if ($label === '') { if ($label === '') {
$output .= '>'. $value .'</option>' . "\n"; $output .= '>'. $value .'</option>' . "\n";
} else { } else {
$output .= '>'. $label .'</option>' . "\n"; $output .= '>'. $label .'</option>' . "\n";
}
} }
} }
echo $output . '</select>' . "\n";
} }
echo $output . '</select>' . "\n";
}
function game_showgroups($game) function game_showgroups($game) {
{ global $CFG, $USER, $DB;
global $CFG, $USER, $DB;
$groups = array();
if( ($recs = $DB->get_records_sql( "SELECT id,name FROM {groups} WHERE courseid=$game->course ORDER BY name"))){
foreach( $recs as $rec){
$groups[ $rec->id] = $rec->name;
}
}
?> $groups = array();
if (($recs = $DB->get_records_sql( "SELECT id,name FROM {groups} WHERE courseid=$game->course ORDER BY name"))) {
foreach ($recs as $rec) {
$groups[ $rec->id] = $rec->name;
}
}
$href = $CFG->wwwroot.'/mod/game/showattempts.php?q='.$game->id.'&groupid=';
?>
<script type="text/javascript"> <script type="text/javascript">
function onselectgroup() function onselectgroup()
{ {
window.location.href = "<?php echo $CFG->wwwroot.'/mod/game/showattempts.php?q='.$game->id.'&groupid=';?>" + document.getElementById('menugroup').value; window.location.href = "<?php echo $href;?>" + document.getElementById('menugroup').value;
} }
</script> </script>
<?php <?php
$attributes = 'onchange="javascript:onselectgroup();"'; $attributes = 'onchange="javascript:onselectgroup();"';
$name = 'group'; $name = 'group';
$id = 'menu'.$name; $id = 'menu'.$name;
$class = 'menu'.$name; $class = 'menu'.$name;
$class = 'select ' . $class; /// Add 'select' selector always $class = 'select ' . $class; // Add 'select' selector always.
$nothing = get_string("allgroups"); $nothing = get_string("allgroups");
$nothingvalue='0'; $nothingvalue = '0';
$options = $groups; $options = $groups;
$selected = optional_param('groupid',0, PARAM_INT); $selected = optional_param('groupid', 0, PARAM_INT);
$output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n"; $output = '<select id="'. $id .'" class="'. $class .'" name="'. $name .'" '. $attributes .'>' . "\n";
$output .= ' <option value="'. s($nothingvalue) .'"'. "\n"; $output .= ' <option value="'. $nothingvalue .'"'. "\n";
if ($nothingvalue === $selected) { if ($nothingvalue === $selected) {
$output .= ' selected="selected"'; $output .= ' selected="selected"';
} }
$output .= '>'. $nothing .'</option>' . "\n"; $output .= '>'. $nothing .'</option>' . "\n";
if (!empty($options)) { if (!empty($options)) {
foreach ($options as $value => $label) { foreach ($options as $value => $label) {
$output .= ' <option value="'. s($value) .'"'; $output .= ' <option value="'. s($value) .'"';
if ((string)$value == (string)$selected || if ((string)$value == (string)$selected ||
(is_array($selected) && in_array($value, $selected))) { (is_array($selected) && in_array($value, $selected))) {
$output .= ' selected="selected"'; $output .= ' selected="selected"';
} }
if ($label === '') { if ($label === '') {
$output .= '>'. $value .'</option>' . "\n"; $output .= '>'. $value .'</option>' . "\n";
} else { } else {
$output .= '>'. $label .'</option>' . "\n"; $output .= '>'. $label .'</option>' . "\n";
}
} }
} }
echo $output . '</select>' . "\n";
} }
echo $output . '</select>' . "\n";
}
function game_showattempts($game){ function game_showattempts($game) {
global $CFG, $DB, $OUTPUT; global $CFG, $DB, $OUTPUT;
$allowdelete = optional_param('allowdelete', 0, PARAM_INT); $allowdelete = optional_param('allowdelete', 0, PARAM_INT);
$userid = optional_param('userid',0,PARAM_INT); $userid = optional_param('userid', 0, PARAM_INT);
$limitfrom = optional_param('limitfrom', 0, PARAM_INT); $limitfrom = optional_param('limitfrom', 0, PARAM_INT);
$gamekind = $game->gamekind; $gamekind = $game->gamekind;
$update = get_coursemodule_from_instance( 'game', $game->id, $game->course)->id; $update = get_coursemodule_from_instance( 'game', $game->id, $game->course)->id;
//Here are user attempts // Here are user attempts.
$table = "{game_attempts} as ga, {user} u, {game} as g"; $table = "{game_attempts} as ga, {user} u, {game} as g";
$select = "ga.userid=u.id AND ga.gameid={$game->id} AND g.id={$game->id}"; $select = "ga.userid=u.id AND ga.gameid={$game->id} AND g.id={$game->id}";
$fields = "ga.id, u.lastname, u.firstname, ga.attempts,". $fields = "ga.id, u.lastname, u.firstname, ga.attempts,".
"timestart, timefinish, timelastattempt, score, ga.lastip, ga.lastremotehost"; "timestart, timefinish, timelastattempt, score, ga.lastip, ga.lastremotehost";
if( $userid != 0) if ($userid != 0) {
$select .= ' AND u.id='.$userid; $select .= ' AND u.id='.$userid;
$sql = "SELECT COUNT(*) AS c FROM $table WHERE $select"; }
$count = $DB->count_records_sql( $sql); $sql = "SELECT COUNT(*) AS c FROM $table WHERE $select";
$maxlines = 20; $count = $DB->count_records_sql( $sql);
$recslimitfrom = $recslimitnum = ''; $maxlines = 20;
if( $count > $maxlines){ $recslimitfrom = $recslimitnum = '';
$recslimitfrom = ( $limitfrom ? $limitfrom * $maxlines : ''); if ($count > $maxlines) {
$recslimitnum = $maxlines; $recslimitfrom = ( $limitfrom ? $limitfrom * $maxlines : '');
$recslimitnum = $maxlines;
for($i=0; $i*$maxlines < $count; $i++){
if( $i == $limitfrom){ for ($i = 0; $i * $maxlines < $count; $i++) {
echo ($i+1).' '; if ($i == $limitfrom) {
}else echo ($i + 1).' ';
{ } else {
echo "<A HREF=\"{$CFG->wwwroot}/mod/game/showattempts.php?q={$game->id}&amp;limitfrom=$i&\">".($i+1)."</a>"; echo "<a href=\"{$CFG->wwwroot}/mod/game/showattempts.php?q={$game->id}&amp;limitfrom=$i&\">".($i + 1)."</a>";
echo ' &nbsp;'; echo ' &nbsp;';
}
} }
echo "<br>";
} }
echo "<br>";
}
$sql = "SELECT $fields FROM $table WHERE $select ORDER BY timelastattempt DESC,timestart DESC"; $sql = "SELECT $fields FROM $table WHERE $select ORDER BY timelastattempt DESC,timestart DESC";
if( ($recs = $DB->get_records_sql( $sql, null, $recslimitfrom, $recslimitnum)) != false){ if (($recs = $DB->get_records_sql( $sql, null, $recslimitfrom, $recslimitnum)) != false) {
echo '<table border="1">'; echo '<table border="1">';
echo '<tr><td><b>'.get_string( 'delete').'</td><td><b>'.get_string('user').'</td>'; echo '<tr><td><b>'.get_string( 'delete').'</td><td><b>'.get_string('user').'</td>';
echo '<td><b>'.get_string('lastip', 'game').'</b></td>'; echo '<td><b>'.get_string('lastip', 'game').'</b></td>';
echo '<td><b>'.get_string('timestart', 'game').'</b></td>'; echo '<td><b>'.get_string('timestart', 'game').'</b></td>';
echo '<td><b>'.get_string('timelastattempt', 'game').'</b></td>'; echo '<td><b>'.get_string('timelastattempt', 'game').'</b></td>';
echo '<td><b>'.get_string('timefinish', 'game').'</b></td>'; echo '<td><b>'.get_string('timefinish', 'game').'</b></td>';
echo '<td><b>'.get_string('score', 'game').'</b></td>'; echo '<td><b>'.get_string('score', 'game').'</b></td>';
echo '<td><b>'.get_string('attempts', 'game').'</b></td>'; echo '<td><b>'.get_string('attempts', 'game').'</b></td>';
echo '<td><b>'.get_string('preview', 'game').'</b></td>'; echo '<td><b>'.get_string('preview', 'game').'</b></td>';
echo '<td><b>'.get_string('showsolution', 'game').'</b></td>'; echo '<td><b>'.get_string('showsolution', 'game').'</b></td>';
echo "</tr>\r\n"; echo "</tr>\r\n";
foreach( $recs as $rec){ foreach ($recs as $rec) {
echo '<tr>'; echo '<tr>';
echo '<td><center>'; echo '<td><center>';
if( ($rec->timefinish == 0) or $allowdelete){ if (($rec->timefinish == 0) or $allowdelete) {
echo "\r\n<a href=\"{$CFG->wwwroot}/mod/game/showattempts.php?attemptid={$rec->id}&amp;q={$game->id}&amp;action=delete"; echo "\r\n<a href=\"{$CFG->wwwroot}/mod/game/showattempts.php?attemptid={$rec->id}";
if( $allowdelete) echo "&amp;q={$game->id}&amp;action=delete";
echo '&allowdelete=1'; if ($allowdelete) {
echo '">'; echo '&allowdelete=1';
echo '<img src="'.$OUTPUT->pix_url('t/delete').'" alt="'.get_string( 'delete').'" /></a>';
} }
echo '</center></td>'; echo '">';
echo '<td><center>'.$rec->firstname. ' '.$rec->lastname.'</center></td>'; echo '<img src="'.$OUTPUT->pix_url('t/delete').'" alt="'.get_string( 'delete').'" /></a>';
echo '<td><center>'.(strlen( $rec->lastremotehost) > 0 ? $rec->lastremotehost : $rec->lastip).'</center></td>'; }
echo '<td><center>'.( $rec->timestart != 0 ? userdate($rec->timestart) : '')."</center></td>\r\n"; echo '</center></td>';
echo '<td><center>'.( $rec->timelastattempt != 0 ? userdate($rec->timelastattempt) : '').'</center></td>'; echo '<td><center>'.$rec->firstname. ' '.$rec->lastname.'</center></td>';
echo '<td><center>'.( $rec->timefinish != 0 ? userdate($rec->timefinish) : '').'</center></td>'; echo '<td><center>'.(strlen( $rec->lastremotehost) > 0 ? $rec->lastremotehost : $rec->lastip).'</center></td>';
echo '<td><center>'.round($rec->score * 100).'</center></td>'; echo '<td><center>'.( $rec->timestart != 0 ? userdate($rec->timestart) : '')."</center></td>\r\n";
echo '<td><center>'.$rec->attempts.'</center></td>'; echo '<td><center>'.( $rec->timelastattempt != 0 ? userdate($rec->timelastattempt) : '').'</center></td>';
echo '<td><center>'; echo '<td><center>'.( $rec->timefinish != 0 ? userdate($rec->timefinish) : '').'</center></td>';
//Preview echo '<td><center>'.round($rec->score * 100).'</center></td>';
if( ($gamekind == 'cross') or ($gamekind == 'sudoku') or ($gamekind == 'hangman') or ($gamekind == 'cryptex')){ echo '<td><center>'.$rec->attempts.'</center></td>';
echo "\r\n<a href=\"{$CFG->wwwroot}/mod/game/preview.php?action=preview&amp;attemptid={$rec->id}&amp;gamekind=$gamekind"; echo '<td><center>';
echo '&amp;update='.$update."&amp;q={$game->id}\">";
echo '<img src="'.$OUTPUT->pix_url('t/preview').'" alt="'.get_string( 'preview', 'game').'" /></a>'; // Preview.
} if (($gamekind == 'cross') or ($gamekind == 'sudoku') or ($gamekind == 'hangman') or ($gamekind == 'cryptex')) {
echo '</center></td>'; echo "\r\n<a href=\"{$CFG->wwwroot}/mod/game/preview.php?action=preview&amp;";
echo "attemptid={$rec->id}&amp;gamekind=$gamekind";
//Show solution echo '&amp;update='.$update."&amp;q={$game->id}\">";
echo '<td><center>'; echo '<img src="'.$OUTPUT->pix_url('t/preview').'" alt="'.get_string( 'preview', 'game').'" /></a>';
if( ($gamekind == 'cross') or ($gamekind == 'sudoku') or ($gamekind == 'hangman') or ($gamekind == 'cryptex') ){ }
echo "\r\n<a href=\"{$CFG->wwwroot}/mod/game/preview.php?action=solution&amp;attemptid={$rec->id}&amp;gamekind={$gamekind}&amp;update=$update&amp;&amp;q={$game->id}\">"; echo '</center></td>';
echo '<img src="'.$OUTPUT->pix_url('t/preview').'" alt="'.get_string( 'showsolution', 'game').'" /></a>';
} // Show the solution.
echo '</center></td>'; echo '<td><center>';
echo "</tr>\r\n"; if (($gamekind == 'cross') or ($gamekind == 'sudoku') or ($gamekind == 'hangman') or ($gamekind == 'cryptex') ) {
echo "\r\n<a href=\"{$CFG->wwwroot}/mod/game/preview.php?action=solution&amp;".
"attemptid={$rec->id}&amp;gamekind={$gamekind}&amp;update=$update&amp;&amp;".
"q={$game->id}\">";
echo '<img src="'.$OUTPUT->pix_url('t/preview').'" alt="'.get_string( 'showsolution', 'game').'" /></a>';
} }
echo "</table>\r\n"; echo '</center></td>';
echo "</tr>\r\n";
} }
echo "</table>\r\n";
} }
}
function game_ondeleteattempt( $game) {
global $CFG, $DB;
function game_ondeleteattempt( $game) $attemptid = required_param('attemptid', PARAM_INT);
{
global $CFG, $DB; $attempt = $DB->get_record( 'game_attempts', array( 'id' => $attemptid));
$attemptid = required_param('attemptid', PARAM_INT); switch( $game->gamekind) {
case 'bookquiz':
$attempt = $DB->get_record( 'game_attempts', array( 'id' => $attemptid)); $DB->delete_records( 'game_bookquiz_chapters', array( 'attemptid' => $attemptid));
break;
switch( $game->gamekind) }
{ $DB->delete_records( 'game_queries', array( 'attemptid' => $attemptid));
case 'bookquiz': $DB->delete_records( 'game_attempts', array( 'id' => $attemptid));
$DB->delete_records( 'game_bookquiz_chapters', array( 'attemptid' => $attemptid)); }
break;
}
$DB->delete_records( 'game_queries', array( 'attemptid' => $attemptid));
$DB->delete_records( 'game_attempts', array( 'id' => $attemptid));
}

42
tabs.php

@ -1,4 +1,19 @@
<?php // $Id: tabs.php,v 1.7 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* Sets up the tabs used by the game pages based on the users capabilites. * Sets up the tabs used by the game pages based on the users capabilites.
* *
@ -8,7 +23,7 @@
*/ */
if (empty($game)) { if (empty($game)) {
print_error('You cannot call this script in that way'); print_error('You cannot call this script in that way');
} }
if (!isset($currenttab)) { if (!isset($currenttab)) {
$currenttab = ''; $currenttab = '';
@ -29,39 +44,34 @@ $activated = array();
global $USER; global $USER;
if (has_capability('mod/game:view', $context)) { if (has_capability('mod/game:view', $context)) {
$row[] = new tabobject('info', "{$CFG->wwwroot}/mod/game/view.php?q=$game->id", get_string('info', 'game')); $row[] = new tabobject('info', "{$CFG->wwwroot}/mod/game/view.php?q=$game->id", get_string('info', 'game'));
} }
if (has_capability('mod/game:viewreports', $context)) { if (has_capability('mod/game:viewreports', $context)) {
//if( isteacher( $game->course, $USER->id)){ $row[] = new tabobject('reports', "{$CFG->wwwroot}/mod/game/report.php?q=$game->id", get_string('results', 'game'));
$row[] = new tabobject('reports', "{$CFG->wwwroot}/mod/game/report.php?q=$game->id", get_string('results', 'game'));
//}
} }
if (has_capability('mod/game:preview', $context)) { if (has_capability('mod/game:preview', $context)) {
$row[] = new tabobject('preview', "{$CFG->wwwroot}/mod/game/attempt.php?a=$game->id", get_string('preview', 'game')); $row[] = new tabobject('preview', "{$CFG->wwwroot}/mod/game/attempt.php?a=$game->id", get_string('preview', 'game'));
} }
if (has_capability('mod/game:manage', $context)) { if (has_capability('mod/game:manage', $context)) {
//if( isteacher( $game->course, $USER->id)){ global $USER;
global $USER; $sesskey = $USER->sesskey;
$sesskey = $USER->sesskey; $url = "{$CFG->wwwroot}/course/mod.php?update=$cm->id&return=true&sesskey=$sesskey";
$url = "{$CFG->wwwroot}/course/mod.php?update=$cm->id&return=true&sesskey=$sesskey";
$row[] = new tabobject('edit', $url, get_string('edit')); $row[] = new tabobject('edit', $url, get_string('edit'));
//}
} }
if ($currenttab == 'info' && count($row) == 1) { if ( !($currenttab == 'info' && count($row) == 1)) {
// Don't show only an info tab (e.g. to students). // Don't show only an info tab (e.g. to students).
} else {
$tabs[] = $row; $tabs[] = $row;
} }
if ($currenttab == 'reports' and isset($mode)) { if ($currenttab == 'reports' and isset($mode)) {
$inactive[] = 'reports'; $inactive[] = 'reports';
$activated[] = 'reports'; $activated[] = 'reports';
$allreports = get_list_of_plugins("mod/game/report"); $allreports = get_list_of_plugins("mod/game/report");
$reportlist = array ('overview' /*, 'regrade' , 'grading' , 'analysis'*/); // Standard reports we want to show first // Standard reports we want to show first
$reportlist = array ('overview' /*, 'regrade' , 'grading' , 'analysis'*/);
foreach ($allreports as $report) { foreach ($allreports as $report) {
if (!in_array($report, $reportlist)) { if (!in_array($report, $reportlist)) {
@ -98,5 +108,3 @@ if ($currenttab == 'edit' and isset($mode)) {
} }
print_tabs($tabs, $currenttab, $inactive, $activated); print_tabs($tabs, $currenttab, $inactive, $activated);
?>

379
translate.php

@ -1,4 +1,19 @@
<?php // $Id: translate.php,v 1.10 2012/07/25 23:07:43 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* Check translation of module Game * Check translation of module Game
* *
@ -21,8 +36,9 @@ require( 'locallib.php');
$moodle19dir = '/var/www/moodle19'; $moodle19dir = '/var/www/moodle19';
$context = get_context_instance(CONTEXT_COURSE, $COURSE->id); $context = get_context_instance(CONTEXT_COURSE, $COURSE->id);
if (!has_capability('mod/game:viewreports', $context)) if (!has_capability('mod/game:viewreports', $context)) {
error( get_string( 'only_teachers', 'game')); error( get_string( 'only_teachers', 'game'));
}
$langname = array(); $langname = array();
$langname['ca'] = 'Català (ca)'; $langname['ca'] = 'Català (ca)';
@ -45,16 +61,16 @@ $langname['uk'] = 'Українська (uk)';
$langname['pt_br'] = 'Português - Brasil (pt_br)'; $langname['pt_br'] = 'Português - Brasil (pt_br)';
$langname['zh_cn'] = '简体中文 (zh_cn)'; $langname['zh_cn'] = '简体中文 (zh_cn)';
ksort( $langname); ksort( $langname);
$a = read_dir( $CFG->dirroot.'/mod/game','php'); $a = read_dir( $CFG->dirroot.'/mod/game', 'php');
$strings = array(); $strings = array();
$files = array(); $files = array();
foreach( $a as $file) foreach ($a as $file) {
$files[] = $file; $files[] = $file;
}
sort( $files); sort( $files);
foreach( $files as $file) foreach ($files as $file) {
{ readsourcecode( $file, $strings);
readsourcecode( $file, $strings);
} }
$strings[ 'game:attempt'] = '/db/access.php * game:attempt'; $strings[ 'game:attempt'] = '/db/access.php * game:attempt';
@ -86,150 +102,151 @@ unset( $en[ 'convertto']);
$langs = computelangs(); $langs = computelangs();
$sum = array(); $sum = array();
$destdir = game_export_createtempdir(); $destdir = game_export_createtempdir();
foreach( $langs as $lang) foreach ($langs as $lang) {
{ if ($lang != 'en' and $lang != 'CVS' and strpos( $lang, '_utf8') == 0 and strpos( $lang, '_uft8') == 0) {
if($lang != 'en' and $lang != 'CVS' and strpos( $lang, '_utf8') == 0 and strpos( $lang, '_uft8') == 0)
{
computediff( $en, $lang, $strings, $langname, $sum, $destdir, $untranslated); computediff( $en, $lang, $strings, $langname, $sum, $destdir, $untranslated);
$auntranslated[ $lang] = $untranslated; $auntranslated[ $lang] = $untranslated;
} }
} }
$file_no_translation = 'game_lang_no_translation.zip'; $filenotranslation = 'game_lang_no_translation.zip';
$filezip=game_create_zip( $destdir, $COURSE->id, $file_no_translation); $filezip = game_create_zip( $destdir, $COURSE->id, $filenotranslation);
remove_dir( $destdir); remove_dir( $destdir);
$ilang=0; $ilang = 0;
echo '<table border=1>'; echo '<table border=1>';
echo "<tr><td><b>Counter</td><td><b>Language</td><td><b>Missing words</td><td><b>Percent completed</td></tr>"; echo "<tr><td><b>Counter</td><td><b>Language</td><td><b>Missing words</td><td><b>Percent completed</td></tr>";
foreach($sum as $s) foreach ($sum as $s) {
echo '<tr><td>'.(++$ilang).'</td>'.$s."\r\n"; echo '<tr><td>'.(++$ilang).'</td>'.$s."\r\n";
}
echo "</table>"; echo "</table>";
echo "<br><a href=\"{$CFG->wwwroot}/file.php/1/export/$file_no_translation\">Words that is not translated yet in each language</a>"; echo "<br><a href=\"{$CFG->wwwroot}/file.php/1/export/$filenotranslation\">Words that is not translated yet in each language</a>";
//Find missing strings on en/game.php // Find missing strings on en/game.php.
$not = array(); $not = array();
$prevfile = ''; $prevfile = '';
foreach( $strings as $info) foreach ($strings as $info) {
{
$pos = strpos( $info, '*'); $pos = strpos( $info, '*');
$name = substr( $info, $pos+2); $name = substr( $info, $pos + 2);
$file = substr( $info, 0, $pos-1); $file = substr( $info, 0, $pos - 1);
if( substr( $file, 0, 1) == '/') if (substr( $file, 0, 1) == '/') {
$file = substr( $file, 1); $file = substr( $file, 1);
if( $file != $prevfile) }
{ if ($file != $prevfile) {
$prevfile = $file; $prevfile = $file;
} }
if( !array_key_exists( $name, $en)) if (!array_key_exists( $name, $en)) {
$not[ $info] = $info; $not[ $info] = $info;
}
} }
$oldfile=''; $oldfile = '';
unset( $not[ 'tabs.php * $report']); unset( $not[ 'tabs.php * $report']);
unset( $not[ 'mod_form.php * game_\'.$gamekin']); unset( $not[ 'mod_form.php * game_\'.$gamekin']);
unset( $not[ 'mod.html * game_\'.$form->gamekin']); unset( $not[ 'mod.html * game_\'.$form->gamekin']);
unset( $not[ '/report/overview/report.php * fullname\')."\t".get_string(\'startedon']); unset( $not[ '/report/overview/report.php * fullname\')."\t".get_string(\'startedon']);
unset( $not[ '/hangman/play.php * hangman_correct_\'.$ter']); unset( $not[ '/hangman/play.php * hangman_correct_\'.$ter']);
if( count( $not)) if (count( $not)) {
echo "<br><br>Missing strings on en/game.php<br>"; echo "<br><br>Missing strings on en/game.php<br>";
foreach( $not as $key => $value) }
{ foreach ($not as $key => $value) {
$pos = strpos( $value, '*'); $pos = strpos( $value, '*');
$file = trim( substr( $value, 0, $pos)); $file = trim( substr( $value, 0, $pos));
$key = trim( substr( $value, $pos+1)); $key = trim( substr( $value, $pos + 1));
if( $key == 'convertfrom' or $key == 'convertto') if ($key == 'convertfrom' or $key == 'convertto') {
continue; continue;
}
if( substr( $file, 0, 1) == '/')
if (substr( $file, 0, 1) == '/') {
$file = substr( $file, 1); $file = substr( $file, 1);
if( $file != $oldfile) }
{ if ($file != $oldfile) {
echo "<br>//$file<br>\r\n"; echo "<br>//$file<br>\r\n";
$fileold=$file; $fileold = $file;
} }
echo '$'."string[ '$key'] = \"\";<br>"; echo '$'."string[ '$key'] = \"\";<br>";
} }
//Finds translations to en that are not used now // Finds translations to en that are not used now.
$ret = ''; $ret = '';
foreach( $en as $key => $value) foreach ($en as $key => $value) {
{ if (!array_key_exists( $key, $strings)) {
if( !array_key_exists( $key, $strings))
$ret .= "$key = $value<br>"; $ret .= "$key = $value<br>";
}
} }
if( $ret != '') if ($ret != '') {
echo '<hr><b><center>Translations that are not used</center></b><br>'.$ret; echo '<hr><b><center>Translations that are not used</center></b><br>'.$ret;
}
//Creates the zip files of translations // Creates the zip files of translations.
$destdir = game_export_createtempdir(); $destdir = game_export_createtempdir();
sort( $strings); sort( $strings);
foreach( $langname as $lang => $name) foreach ($langname as $lang => $name) {
{ $stringslang = readlangfile( $lang, $header);
$strings_lang = readlangfile( $lang, $header); if (empty($stringlang)) {
if (empty($string_lang)) {
continue; continue;
} }
$ret = ''; $ret = '';
foreach( $strings_lang as $key => $value) foreach ($stringslang as $key => $value) {
{ if (!array_key_exists( $key, $en)) {
if( !array_key_exists( $key, $en)) if ($key != 'convertfrom' and $key != 'convertto') {
{
if( $key != 'convertfrom' and $key != 'convertto')
$ret .= '<br>'.$key."\r\n"; $ret .= '<br>'.$key."\r\n";
}
} }
} }
if( $ret != '') if ($ret != '') {
echo '<hr><b><center>Unused translation for lang '.$lang.'</center></b><br>'.substr( $ret, 4)."\r\n"; echo '<hr><b><center>Unused translation for lang '.$lang.'</center></b><br>'.substr( $ret, 4)."\r\n";
}
$ret = $header; $ret = $header;
foreach( $strings as $info) foreach ($strings as $info) {
{
$pos = strpos( $info, '*'); $pos = strpos( $info, '*');
$name = substr( $info, $pos+2); $name = substr( $info, $pos + 2);
$file = substr( $info, 0, $pos-1); $file = substr( $info, 0, $pos - 1);
if( substr( $file, 0, 1) == '/') if (substr( $file, 0, 1) == '/') {
$file = substr( $file, 1); $file = substr( $file, 1);
if( $file != $prevfile) }
{ if ($file != $prevfile) {
$prevfile = $file; $prevfile = $file;
$ret .= "\r\n//".$file."\r\n"; $ret .= "\r\n//".$file."\r\n";
} }
if( array_key_exists( $name, $strings_lang)) if (array_key_exists( $name, $stringslang)) {
$ret .= '$string'."[ '$name'] = ".$strings_lang[ $name]."\r\n"; $ret .= '$string'."[ '$name'] = ".$stringslang[ $name]."\r\n";
}
} }
if( $lang != 'en') if ($lang != 'en') {
{
$untranslated = $auntranslated[ $lang]; $untranslated = $auntranslated[ $lang];
if( $untranslated != '') if ($untranslated != '') {
$ret .= "\r\n//Untranslated\r\n".$untranslated; $ret .= "\r\n//Untranslated\r\n".$untranslated;
}
} }
mkdir( $destdir.'/'.$lang); mkdir( $destdir.'/'.$lang);
$file = $destdir.'/'.$lang.'/game.php'; $file = $destdir.'/'.$lang.'/game.php';
file_put_contents( $file, $ret); file_put_contents( $file, $ret);
} }
$file_sorted = 'game_lang_sorted.zip'; $filesorted = 'game_lang_sorted.zip';
$filezip=game_create_zip( $destdir, $COURSE->id, $file_sorted); $filezip = game_create_zip( $destdir, $COURSE->id, $filesorted);
remove_dir( $destdir); remove_dir( $destdir);
echo "<br><a href=\"{$CFG->wwwroot}/file.php/1/export/$file_sorted\">Sorted translation files</a>"; echo "<br><a href=\"{$CFG->wwwroot}/file.php/1/export/$filesorted\">Sorted translation files</a>";
asort( $en); asort( $en);
$sprev = ''; $sprev = '';
$keyprev = ''; $keyprev = '';
$ret = ''; $ret = '';
foreach( $en as $key => $s) foreach ($en as $key => $s) {
{ if ($s == $sprev) {
if( $s == $sprev)
$ret .= "<tr><td>$key</td><td>$keyprev</td><td>$s</td></tr>\r\n"; $ret .= "<tr><td>$key</td><td>$keyprev</td><td>$s</td></tr>\r\n";
}
$sprev = $s; $sprev = $s;
$keyprev = $key; $keyprev = $key;
} }
if( $ret != '') if ($ret != '') {
echo '<br><center><b>Same translations<center></b><br><table border=1><tr><td><b>Word1</td><td><b>Word2</td><td><b>Translation</td></tr>'.$ret.'</table>'; echo '<br><center><b>Same translations<center></b><br>';
echo '<table border=1><tr><td><b>Word1</td><td><b>Word2</td><td><b>Translation</td></tr>'.$ret.'</table>';
}
function readlangfile( $lang, &$header) function readlangfile( $lang, &$header) {
{
global $CFG; global $CFG;
$file = $CFG->dirroot.'/mod/game/lang/'.$lang.'/game.php'; $file = $CFG->dirroot.'/mod/game/lang/'.$lang.'/game.php';
@ -242,45 +259,45 @@ function readlangfile( $lang, &$header)
$lines = file( $file); $lines = file( $file);
$header = ''; $header = '';
$endofheader = false; $endofheader = false;
foreach( $lines as $line) foreach ($lines as $line) {
{ if ($endofheader == false) {
if( $endofheader == false) if (strpos( $line, '//') === false) {
{
if( strpos( $line, '//') === false)
$endofheader = true; $endofheader = true;
else } else {
$header .= $line; $header .= $line;
}
} }
if( splitlangdefinition($line,$name,$trans)) if (splitlangdefinition($line, $name, $trans)) {
$a[ $name] = $trans; $a[ $name] = $trans;
}
} }
if( $lang != 'en') if ($lang != 'en') {
readlangfile_repairmoodle19( $lang, $a); readlangfile_repairmoodle19( $lang, $a);
}
return $a; return $a;
} }
function splitlangdefinition($line,&$name,&$trans) function splitlangdefinition($line, &$name, &$trans) {
{
$pos1 = strpos( $line, '='); $pos1 = strpos( $line, '=');
if( $pos1 == 0) if ($pos1 == 0) {
return false; return false;
}
$pos2 = strpos( $line, '//'); $pos2 = strpos( $line, '//');
if( $pos2 != 0 or substr( $line, 0, 2) == '//') if ($pos2 != 0 or substr( $line, 0, 2) == '//') {
{ if ($pos2 < $pos1) {
if( $pos2 < $pos1) return false; // Commented line.
return false; //Commented line }
} }
$name = trim(substr( $line, 0, $pos1-1)); $name = trim(substr( $line, 0, $pos1 - 1));
$trans = trim(substr( $line, $pos1+1)); $trans = trim(substr( $line, $pos1 + 1));
$pos = strpos( $name, '\''); $pos = strpos( $name, '\'');
if( $pos) if ($pos) {
{ $name = substr( $name, $pos + 1);
$name = substr( $name, $pos+1);
$pos = strrpos( $name, '\''); $pos = strrpos( $name, '\'');
$name = substr( $name, 0, $pos); $name = substr( $name, 0, $pos);
} }
@ -288,122 +305,124 @@ function splitlangdefinition($line,&$name,&$trans)
return true; return true;
} }
function readsourcecode( $file, &$strings) function readsourcecode( $file, &$strings) {
{
global $CFG; global $CFG;
$lines = file( $file); $lines = file( $file);
foreach( $lines as $line) foreach ($lines as $line) {
{
parseline( $strings, $line, $file); parseline( $strings, $line, $file);
} }
return $strings; return $strings;
} }
function parseline( &$strings, $line, $filename) function parseline( &$strings, $line, $filename) {
{
global $CFG; global $CFG;
$filename = substr( $filename, strlen( $CFG->dirroot.'/mod/game/')); $filename = substr( $filename, strlen( $CFG->dirroot.'/mod/game/'));
if( strpos($filename, '/')) if (strpos($filename, '/')) {
$filename = '/'.$filename; $filename = '/'.$filename;
}
$pos0 = 0; $pos0 = 0;
for(;;) for (;;) {
{
$pos = strpos( $line, 'get_string', $pos0); $pos = strpos( $line, 'get_string', $pos0);
if( $pos == false) if ($pos == false) {
$pos = strpos( $line, 'print_string', $pos0); $pos = strpos( $line, 'print_string', $pos0);
if( $pos === false) }
if ($pos === false) {
break; break;
}
$pos1 = strpos( $line, '(', $pos); $pos1 = strpos( $line, '(', $pos);
$pos2 = strpos( $line, ',', $pos); $pos2 = strpos( $line, ',', $pos);
$pos3 = strpos( $line, ')', $pos); $pos3 = strpos( $line, ')', $pos);
if( $pos1 == 0 or $pos2 == 0 or $pos3 == 0) if ($pos1 == 0 or $pos2 == 0 or $pos3 == 0) {
{ $pos0 = $pos + 1;
$pos0 = $pos+1;
continue; continue;
} }
$name = gets( substr( $line, $pos1+1, $pos2-$pos1-1)); $name = gets( substr( $line, $pos1 + 1, $pos2 - $pos1 - 1));
$file = gets( substr( $line, $pos2+1, $pos3-$pos2-1)); $file = gets( substr( $line, $pos2 + 1, $pos3 - $pos2 - 1));
if( $file == 'game') if ($file == 'game') {
{ if (!array_key_exists( $name, $strings)) {
if( !array_key_exists( $name, $strings))
$strings[ $name] = $filename.' * '.$name; $strings[ $name] = $filename.' * '.$name;
}else }
{ } else {
$pos4 = strpos($file, '\''); $pos4 = strpos($file, '\'');
if( $pos4) if ($pos4) {
$file = substr( $file, 0, $pos4); $file = substr( $file, 0, $pos4);
}
$pos4 = strpos($file, '"'); $pos4 = strpos($file, '"');
if($pos4) if ($pos4) {
$file = substr( $file, 0, $pos4); $file = substr( $file, 0, $pos4);
}
if( $file == 'game') if ($file == 'game') {
{ if (!array_key_exists( $name, $strings)) {
if( !array_key_exists( $name, $strings))
$strings[ $name] = $filename.' * '.$name; $strings[ $name] = $filename.' * '.$name;
}
} }
} }
$pos0 = $pos+1; $pos0 = $pos + 1;
} }
} }
function gets( $s) function gets( $s) {
{
$s = trim( $s); $s = trim( $s);
if( substr( $s, 0, 1) == '"') if (substr( $s, 0, 1) == '"') {
$s = substr( $s, 1, -1); $s = substr( $s, 1, -1);
if( substr( $s, 0, 1) == '\'') }
if (substr( $s, 0, 1) == '\'') {
$s = substr( $s, 1, -1); $s = substr( $s, 1, -1);
}
return $s; return $s;
} }
function read_dir($dir, $ext) { function read_dir($dir, $ext) {
if( $ext != '') if ($ext != '') {
$ext = '.' .$ext; $ext = '.' .$ext;
}
$len = strlen( $ext); $len = strlen( $ext);
$a = array( $dir); $a = array( $dir);
$ret = array(); $ret = array();
while( count( $a)){ while (count( $a)) {
$dir = array_pop( $a); $dir = array_pop( $a);
if( strpos( $dir, '/lang/') != 0) if (strpos( $dir, '/lang/') != 0) {
continue; continue;
}
$d = dir($dir); $d = dir($dir);
while (false !== ($entry = $d->read())) { while (false !== ($entry = $d->read())) {
if($entry!='.' && $entry!='..') { if ($entry != '.' && $entry != '..') {
$entry = $dir.'/'.$entry; $entry = $dir.'/'.$entry;
if(is_dir($entry)) { if (is_dir($entry)) {
$a[] = $entry; $a[] = $entry;
} else { } else {
if( $len == 0) if ($len == 0) {
$ret[] = $entry; $ret[] = $entry;
else if( substr( $entry, -$len) == $ext) } else if (substr( $entry, -$len) == $ext) {
$ret[] = $entry; $ret[] = $entry;
}
} }
} }
} }
$d->close(); $d->close();
} }
return $ret; return $ret;
} }
function computelangs() function computelangs() {
{
global $CFG; global $CFG;
$dir = $CFG->dirroot.'/mod/game/lang'; $dir = $CFG->dirroot.'/mod/game/lang';
$ret = array(); $ret = array();
$d = dir( $dir); $d = dir( $dir);
while (false !== ($entry = $d->read())) { while (false !== ($entry = $d->read())) {
if( $entry != '.' and $entry != '..'){ if ($entry != '.' and $entry != '..') {
if(is_dir($dir.'/'.$entry)) { if (is_dir($dir.'/'.$entry)) {
$ret[] = $entry; $ret[] = $entry;
} }
} }
@ -412,14 +431,12 @@ function computelangs()
return $ret; return $ret;
} }
function computediff( $en, $lang, $strings, $langname, &$sum, $outdir, &$untranslated) function computediff( $en, $lang, $strings, $langname, &$sum, $outdir, &$untranslated) {
{
global $CFG; global $CFG;
$untranslated = ''; $untranslated = '';
$counten=count($en); $counten = count($en);
$trans = readlangfile( $lang, $header); $trans = readlangfile( $lang, $header);
foreach( $trans as $s => $key) foreach ($trans as $s => $key) {
{
unset( $en[ $s]); unset( $en[ $s]);
} }
@ -427,69 +444,69 @@ function computediff( $en, $lang, $strings, $langname, &$sum, $outdir, &$untrans
$lines = file( $file); $lines = file( $file);
$count = 0; $count = 0;
$s = ''; $s = '';
foreach( $lines as $line) foreach ($lines as $line) {
{
$s .= $line; $s .= $line;
if( ++$count >= 3) if (++$count >= 3) {
break; break;
}
} }
$a = array(); $a = array();
foreach( $en as $name => $t) foreach ($en as $name => $t) {
{ if (array_key_exists( $name, $strings)) {
if( array_key_exists( $name, $strings))
$file = $strings[ $name]; $file = $strings[ $name];
else } else {
$file = ''; $file = '';
}
$t = strip_tags( $t); $t = strip_tags( $t);
$a[ $file.' * '.$name] = '$'."string[ '$name'] = $t\r\n"; $a[ $file.' * '.$name] = '$'."string[ '$name'] = $t\r\n";
} }
ksort( $a); ksort( $a);
if( array_key_exists( $lang, $langname)) if (array_key_exists( $lang, $langname)) {
$langprint = $langname[ $lang]; $langprint = $langname[ $lang];
else } else {
$langprint = $lang; $langprint = $lang;
}
$sum[]="<td>$langprint</td><td><center>".count($a)."</td><td><center>".round(100*($counten-count($a))/$counten,0)." %</td>"; $sum[] = "<td>$langprint</td><td><center>".count($a)."</td><td><center>".
$prev_file = ''; round(100 * ($counten - count($a)) / $counten, 0)." %</td>";
foreach( $a as $key => $line) $prevfile = '';
{ foreach ($a as $key => $line) {
$pos = strpos( $key, '*'); $pos = strpos( $key, '*');
$file = trim( substr( $key, 0, $pos-1)); $file = trim( substr( $key, 0, $pos - 1));
if( substr( $file, 0, 1) == '/') if (substr( $file, 0, 1) == '/') {
$file = substr( $file, 1); $file = substr( $file, 1);
if( $file != $prev_file) }
{ if ($file != $prevfile) {
$s .= "\r\n//$file\r\n"; $s .= "\r\n//$file\r\n";
$prev_file = $file; $prevfile = $file;
} }
$s .= $line; $s .= $line;
$untranslated .= "//$prev_file ".$line; $untranslated .= "//$prevfile ".$line;
} }
$file = $outdir.'/'.$lang.'.php'; $file = $outdir.'/'.$lang.'.php';
file_put_contents( $file, $s); file_put_contents( $file, $s);
} }
//Copies the translation from Moodle 19 // Copies the translation from Moodle 19.
function readlangfile_repairmoodle19( $lang, &$strings_lang) function readlangfile_repairmoodle19( $lang, &$stringslang) {
{
global $moodle19dir; global $moodle19dir;
if( $moodle19dir == '') if ($moodle19dir == '') {
return; return;
}
$file = $moodle19dir.'/mod/game/lang/'.$lang.'_utf8/game.php'; $file = $moodle19dir.'/mod/game/lang/'.$lang.'_utf8/game.php';
$a = array(); $a = array();
$lines = file( $file); $lines = file( $file);
foreach( $lines as $line) foreach ($lines as $line) {
{ if (splitlangdefinition($line, $name, $trans)) {
if( splitlangdefinition($line,$name,$trans)) if (!array_key_exists( $name, $stringslang)) {
{ $stringslang[ $name] = $trans;
if( !array_key_exists( $name, $strings_lang)) }
$strings_lang[ $name] = $trans;
} }
} }
} }

39
version.php

@ -1,4 +1,19 @@
<?php // $Id: version.php,v 1.49 2012/07/25 22:46:42 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* Code fragment to define the version of game * Code fragment to define the version of game
* This fragment is called by moodle_needs_upgrading() and /admin/index.php * This fragment is called by moodle_needs_upgrading() and /admin/index.php
@ -10,22 +25,22 @@
defined('MOODLE_INTERNAL') || die(); defined('MOODLE_INTERNAL') || die();
if( !isset( $plugin)) if (!isset( $plugin)) {
{
$plugin = new stdClass; $plugin = new stdClass;
$useplugin = 0; $useplugin = 0;
}else if( $plugin == 'mod_game') } else if ($plugin == 'mod_game') {
{
$plugin = new stdClass; $plugin = new stdClass;
$useplugin = 1; $useplugin = 1;
}else } else {
$useplugin = 2; $useplugin = 2;
}
$plugin->component = 'mod_game'; // Full name of the plugin (used for diagnostics) $plugin->component = 'mod_game'; // Full name of the plugin (used for diagnostics).
$plugin->version = 2015122201; // The current module version (Date: YYYYMMDDXX) $plugin->version = 2015122501; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2010112400; // Requires Moodle 2.0 $plugin->requires = 2010112400; // Requires Moodle 2.0.
$plugin->cron = 0; // Period for cron to check this module (secs) $plugin->cron = 0; // Period for cron to check this module (secs).
$plugin->release = '3.36.22.1'; $plugin->release = '3.36.25.1';
if( $useplugin != 2) if ($useplugin != 2) {
$module = $plugin; $module = $plugin;
}

535
view.php

@ -1,308 +1,315 @@
<?php // $Id: view.php,v 1.14 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
// This page prints a particular instance of game //
// Moodle is free software: you can redistribute it and/or modify
require_once(dirname(__FILE__) . '/../../config.php'); // it under the terms of the GNU General Public License as published by
require_once($CFG->libdir.'/gradelib.php'); // the Free Software Foundation, either version 3 of the License, or
require_once($CFG->dirroot.'/mod/game/locallib.php'); // (at your option) any later version.
//
$id = optional_param('id', 0, PARAM_INT); // Course Module ID, or // Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
if (! $cm = get_coursemodule_from_id('game', $id)) { // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
print_error('invalidcoursemodule'); // GNU General Public License for more details.
} //
if (! $course = $DB->get_record('course', array('id' => $cm->course))) { // You should have received a copy of the GNU General Public License
print_error('coursemisconf'); // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
// This page prints a particular instance of game.
require_once(dirname(__FILE__) . '/../../config.php');
require_once($CFG->libdir.'/gradelib.php');
require_once($CFG->dirroot.'/mod/game/locallib.php');
$id = optional_param('id', 0, PARAM_INT); // Course Module ID.
if (! $cm = get_coursemodule_from_id('game', $id)) {
print_error('invalidcoursemodule');
}
if (! $course = $DB->get_record('course', array('id' => $cm->course))) {
print_error('coursemisconf');
}
if (! $game = $DB->get_record('game', array('id' => $cm->instance))) {
print_error('invalidcoursemodule');
}
// Check login and get context.
require_login($course->id, false, $cm);
$context = game_get_context_module_instance( $cm->id);
require_capability('mod/game:view', $context);
$timenow = time();
// Cache some other capabilites we use several times.
$canattempt = true;
$strtimeopenclose = '';
if ($timenow < $game->timeopen) {
$canattempt = false;
$strtimeopenclose = get_string('gamenotavailable', 'game', userdate($game->timeopen));
} else if ($game->timeclose && $timenow > $game->timeclose) {
$strtimeopenclose = get_string("gameclosed", "game", userdate($game->timeclose));
$canattempt = false;
} else {
if ($game->timeopen) {
$strtimeopenclose = get_string('gameopenedon', 'game', userdate($game->timeopen));
} }
if (! $game = $DB->get_record('game', array('id' => $cm->instance))) { if ($game->timeclose) {
print_error('invalidcoursemodule'); $strtimeopenclose = get_string('gamecloseson', 'game', userdate($game->timeclose));
} }
}
/// Check login and get context. if (has_capability('mod/game:manage', $context)) {
require_login($course->id, false, $cm);
$context = game_get_context_module_instance( $cm->id);
require_capability('mod/game:view', $context);
$timenow = time();
/// Cache some other capabilites we use several times.
$canattempt = true; $canattempt = true;
$strtimeopenclose = ''; }
if ($timenow < $game->timeopen) {
$canattempt = false;
$strtimeopenclose = get_string('gamenotavailable', 'game', userdate($game->timeopen));
} else if ($game->timeclose && $timenow > $game->timeclose) {
$strtimeopenclose = get_string("gameclosed", "game", userdate($game->timeclose));
$canattempt = false;
} else {
if ($game->timeopen) {
$strtimeopenclose = get_string('gameopenedon', 'game', userdate($game->timeopen));
}
if ($game->timeclose) {
$strtimeopenclose = get_string('gamecloseson', 'game', userdate($game->timeclose));
}
}
if (has_capability('mod/game:manage', $context)) {
$canattempt = true;
}
/// Log this request.
if( game_use_events())
{
require( 'classes/event/course_module_viewed.php');
\mod_game\event\course_module_viewed::viewed($game, $context)->trigger();
}else
add_to_log($course->id, 'game', 'view', "view.php?id=$cm->id", $game->id, $cm->id);
// Mark as viewed
$completion=new completion_info($course);
$completion->set_module_viewed($cm);
/// Initialize $PAGE, compute blocks
$PAGE->set_url('/mod/game/view.php', array('id' => $cm->id));
$edit = optional_param('edit', -1, PARAM_BOOL);
if ($edit != -1 && $PAGE->user_allowed_editing()) {
$USER->editing = $edit;
}
$title = $course->shortname . ': ' . format_string($game->name); // Log this request.
if (game_use_events()) {
if ($PAGE->user_allowed_editing() && !empty($CFG->showblocksonmodpages)) { require( 'classes/event/course_module_viewed.php');
$buttons = '<table><tr><td><form method="get" action="view.php"><div>'. \mod_game\event\course_module_viewed::viewed($game, $context)->trigger();
'<input type="hidden" name="id" value="'.$cm->id.'" />'. } else {
'<input type="hidden" name="edit" value="'.($PAGE->user_is_editing()?'off':'on').'" />'. add_to_log($course->id, 'game', 'view', "view.php?id=$cm->id", $game->id, $cm->id);
'<input type="submit" value="'.get_string($PAGE->user_is_editing()?'blockseditoff':'blocksediton').'" /></div></form></td></tr></table>'; }
$PAGE->set_button($buttons);
} // Mark as viewed.
$completion = new completion_info($course);
$PAGE->set_title($title); $completion->set_module_viewed($cm);
$PAGE->set_heading($course->fullname);
// Initialize $PAGE, compute blocks.
echo $OUTPUT->header(); $PAGE->set_url('/mod/game/view.php', array('id' => $cm->id));
/// Print game name and description $edit = optional_param('edit', -1, PARAM_BOOL);
echo $OUTPUT->heading(format_string($game->name)); if ($edit != -1 && $PAGE->user_allowed_editing()) {
$USER->editing = $edit;
/// Display information about this game. }
echo $OUTPUT->box_start('quizinfo'); $title = $course->shortname . ': ' . format_string($game->name);
if ($game->attempts != 1) {
echo get_string('gradingmethod', 'quiz', game_get_grading_option_name($game->grademethod)); if ($PAGE->user_allowed_editing() && !empty($CFG->showblocksonmodpages)) {
} $buttons = '<table><tr><td><form method="get" action="view.php"><div>'.
echo $OUTPUT->box_end(); '<input type="hidden" name="id" value="'.$cm->id.'" />'.
'<input type="hidden" name="edit" value="'.($PAGE->user_is_editing() ? 'off' : 'on').'" />'.
/// Show number of attempts summary to those who can view reports. '<input type="submit" value="'.
if (has_capability('mod/game:viewreports', $context)) { get_string($PAGE->user_is_editing() ? 'blockseditoff' : 'blocksediton').
if ($strattemptnum = game_get_user_attempts($game->id, $USER->id)) { '" /></div></form></td></tr></table>';
//echo '<div class="gameattemptcounts"><a href="report.php?mode=overview&amp;id=' . $PAGE->set_button($buttons);
// $cm->id . '">' . $strattemptnum . "</a></div>\n"; }
echo get_string( 'attempts', 'game').': '.count( $strattemptnum);
if( $game->maxattempts) $PAGE->set_title($title);
{ $PAGE->set_heading($course->fullname);
echo ' ('.get_string( 'max', 'quiz').': '.$game->maxattempts.')';
} echo $OUTPUT->header();
// Print game name and description.
echo $OUTPUT->heading(format_string($game->name));
// Display information about this game.
echo $OUTPUT->box_start('quizinfo');
if ($game->attempts != 1) {
echo get_string('gradingmethod', 'quiz', game_get_grading_option_name($game->grademethod));
}
echo $OUTPUT->box_end();
// Show number of attempts summary to those who can view reports.
if (has_capability('mod/game:viewreports', $context)) {
if ($strattemptnum = game_get_user_attempts($game->id, $USER->id)) {
echo get_string( 'attempts', 'game').': '.count( $strattemptnum);
if ($game->maxattempts) {
echo ' ('.get_string( 'max', 'quiz').': '.$game->maxattempts.')';
} }
} }
}
/// Get this user's attempts.
$attempts = game_get_user_attempts($game->id, $USER->id); // Get this user's attempts.
$lastfinishedattempt = end($attempts); $attempts = game_get_user_attempts($game->id, $USER->id);
$unfinished = false; $lastfinishedattempt = end($attempts);
if ($unfinishedattempt = game_get_user_attempt_unfinished($game->id, $USER->id)) { $unfinished = false;
$attempts[] = $unfinishedattempt; if ($unfinishedattempt = game_get_user_attempt_unfinished($game->id, $USER->id)) {
$unfinished = true; $attempts[] = $unfinishedattempt;
} $unfinished = true;
$numattempts = count($attempts); }
$numattempts = count($attempts);
/// Work out the final grade, checking whether it was overridden in the gradebook.
$mygrade = game_get_best_grade($game, $USER->id); // Work out the final grade, checking whether it was overridden in the gradebook.
$mygradeoverridden = false; $mygrade = game_get_best_grade($game, $USER->id);
$gradebookfeedback = ''; $mygradeoverridden = false;
$gradebookfeedback = '';
$grading_info = grade_get_grades($course->id, 'mod', 'game', $game->id, $USER->id);
if (!empty($grading_info->items)) { $gradinginfo = grade_get_grades($course->id, 'mod', 'game', $game->id, $USER->id);
$item = $grading_info->items[0]; if (!empty($gradinginfo->items)) {
if (isset($item->grades[$USER->id])) { $item = $gradinginfo->items[0];
$grade = $item->grades[$USER->id]; if (isset($item->grades[$USER->id])) {
$grade = $item->grades[$USER->id];
if ($grade->overridden) {
$mygrade = $grade->grade + 0; // Convert to number. if ($grade->overridden) {
$mygradeoverridden = true; $mygrade = $grade->grade + 0; // Convert to number.
} $mygradeoverridden = true;
if (!empty($grade->str_feedback)) { }
$gradebookfeedback = $grade->str_feedback; if (!empty($grade->str_feedback)) {
} $gradebookfeedback = $grade->str_feedback;
} }
} }
}
/// Print table with existing attempts // Print table with existing attempts.
if ($attempts) { if ($attempts) {
echo $OUTPUT->heading(get_string('summaryofattempts', 'quiz'));
echo $OUTPUT->heading(get_string('summaryofattempts', 'quiz')); // Work out which columns we need, taking account what data is available in each attempt.
list($someoptions, $alloptions) = game_get_combined_reviewoptions($game, $attempts, $context);
// Work out which columns we need, taking account what data is available in each attempt. $attemptcolumn = $game->attempts != 1;
list($someoptions, $alloptions) = game_get_combined_reviewoptions($game, $attempts, $context);
$attemptcolumn = $game->attempts != 1; $gradecolumn = $someoptions->scores && ($game->grade > 0);
$overallstats = $alloptions->scores;
$gradecolumn = $someoptions->scores && ($game->grade > 0); // Prepare table header.
//$markcolumn = $gradecolumn && ($game->grade != $game->sumgrades); $table = new html_table();
$overallstats = $alloptions->scores; $table->attributes['class'] = 'generaltable gameattemptsummary';
$table->head = array();
$table->align = array();
$table->size = array();
if ($attemptcolumn) {
$table->head[] = get_string('attempt', 'game');
$table->align[] = 'center';
$table->size[] = '';
}
$table->head[] = get_string('timecompleted', 'game');
$table->align[] = 'left';
$table->size[] = '';
// Prepare table header if ($gradecolumn) {
$table = new html_table(); $table->head[] = get_string('grade') . ' / ' . game_format_grade( $game, $game->grade);
$table->attributes['class'] = 'generaltable gameattemptsummary'; $table->align[] = 'center';
$table->head = array();
$table->align = array();
$table->size = array();
if ($attemptcolumn) {
$table->head[] = get_string('attempt', 'game');
$table->align[] = 'center';
$table->size[] = '';
}
$table->head[] = get_string('timecompleted', 'game');
$table->align[] = 'left';
$table->size[] = ''; $table->size[] = '';
}
if ($gradecolumn) { $table->head[] = get_string('timetaken', 'game');
$table->head[] = get_string('grade') . ' / ' . game_format_grade( $game, $game->grade); $table->align[] = 'left';
$table->align[] = 'center'; $table->size[] = '';
$table->size[] = '';
}
$table->head[] = get_string('timetaken', 'game'); // One row for each attempt.
$table->align[] = 'left'; foreach ($attempts as $attempt) {
$table->size[] = ''; $attemptoptions = game_get_reviewoptions($game, $attempt, $context);
$row = array();
// One row for each attempt // Add the attempt number, making it a link, if appropriate.
foreach ($attempts as $attempt) { if ($attemptcolumn) {
$attemptoptions = game_get_reviewoptions($game, $attempt, $context); if ($attempt->preview) {
$row = array(); $row[] = get_string('preview', 'game');
} else {
// Add the attempt number, making it a link, if appropriate. $row[] = $attempt->attempt;
if ($attemptcolumn) {
if ($attempt->preview) {
$row[] = get_string('preview', 'game');
} else {
$row[] = $attempt->attempt;
}
} }
}
// prepare strings for time taken and date completed // Prepare strings for time taken and date completed.
$timetaken = ''; $timetaken = '';
$datecompleted = '';
if ($attempt->timefinish > 0) {
// Attempt has finished.
$timetaken = format_time($attempt->timefinish - $attempt->timestart);
$datecompleted = userdate($attempt->timefinish);
} else {
// The a is still in progress.
$timetaken = format_time($timenow - $attempt->timestart);
$datecompleted = ''; $datecompleted = '';
if ($attempt->timefinish > 0) { }
// attempt has finished $row[] = $datecompleted;
$timetaken = format_time($attempt->timefinish - $attempt->timestart);
$datecompleted = userdate($attempt->timefinish);
} else
{
// The a is still in progress.
$timetaken = format_time($timenow - $attempt->timestart);
$datecompleted = '';
}
$row[] = $datecompleted;
// Ouside the if because we may be showing feedback but not grades. bdaloukas // Ouside the if because we may be showing feedback but not grades.
$attemptgrade = game_score_to_grade($attempt->score, $game); $attemptgrade = game_score_to_grade($attempt->score, $game);
if ($gradecolumn) { if ($gradecolumn) {
if ($attemptoptions->scores) { if ($attemptoptions->scores) {
$formattedgrade = game_format_grade($game, $attemptgrade); $formattedgrade = game_format_grade($game, $attemptgrade);
// highlight the highest grade if appropriate // Highlight the highest grade if appropriate.
if ($overallstats && !$attempt->preview && $numattempts > 1 && !is_null($mygrade) && if ($overallstats && !$attempt->preview && $numattempts > 1 && !is_null($mygrade) &&
$attemptgrade == $mygrade && $game->grademethod == QUIZ_GRADEHIGHEST) { $attemptgrade == $mygrade && $game->grademethod == QUIZ_GRADEHIGHEST) {
$table->rowclasses[$attempt->attempt] = 'bestrow'; $table->rowclasses[$attempt->attempt] = 'bestrow';
}
$row[] = $formattedgrade;
} else {
$row[] = '';
} }
}
$row[] = $timetaken;
if ($attempt->preview) { $row[] = $formattedgrade;
$table->data['preview'] = $row;
} else { } else {
$table->data[$attempt->attempt] = $row; $row[] = '';
} }
} // End of loop over attempts. }
echo html_writer::table($table);
}
/// Print information about the student's best score for this game if possible. $row[] = $timetaken;
if ($attempt->preview) {
$table->data['preview'] = $row;
} else {
$table->data[$attempt->attempt] = $row;
}
} // End of loop over attempts.
echo html_writer::table($table);
}
// Print information about the student's best score for this game if possible.
if ($numattempts && $gradecolumn && !is_null($mygrade)) {
$resultinfo = '';
if ($overallstats) {
$a = new stdClass;
$a->grade = game_format_grade($game, $mygrade);
$a->maxgrade = game_format_grade($game, $game->grade);
$a = get_string('outofshort', 'quiz', $a);
$resultinfo .= $OUTPUT->heading(get_string('yourfinalgradeis', 'game', $a), 2, 'main');
}
if ($numattempts && $gradecolumn && !is_null($mygrade)) { if ($mygradeoverridden) {
$resultinfo = ''; $resultinfo .= '<p class="overriddennotice">'.get_string('overriddennotice', 'grades')."</p>\n";
}
if ($overallstats) { if ($gradebookfeedback) {
$a = new stdClass; $resultinfo .= $OUTPUT->heading(get_string('comment', 'game'), 3, 'main');
$a->grade = game_format_grade($game, $mygrade); $resultinfo .= '<p class="gameteacherfeedback">'.$gradebookfeedback."</p>\n";
$a->maxgrade = game_format_grade($game, $game->grade); }
$a = get_string('outofshort', 'quiz', $a);
$resultinfo .= $OUTPUT->heading(get_string('yourfinalgradeis', 'game', $a), 2, 'main');
}
if ($mygradeoverridden) { if ($resultinfo) {
$resultinfo .= '<p class="overriddennotice">'.get_string('overriddennotice', 'grades')."</p>\n"; echo $OUTPUT->box($resultinfo, 'generalbox', 'feedback');
} }
if ($gradebookfeedback) { }
$resultinfo .= $OUTPUT->heading(get_string('comment', 'game'), 3, 'main');
$resultinfo .= '<p class="gameteacherfeedback">'.$gradebookfeedback."</p>\n";
}
if ($resultinfo) { // Determine if we should be showing a start/continue attempt button or a button to go back to the course page.
echo $OUTPUT->box($resultinfo, 'generalbox', 'feedback'); echo $OUTPUT->box_start('gameattempt');
} $buttontext = ''; // This will be set something if as start/continue attempt button should appear.
if ($unfinished) {
if ($canattempt) {
$buttontext = get_string('continueattemptgame', 'game');
}
} else {
// Game is finished. Check if max number of attempts is reached.
if (!game_can_start_new_attempt( $game)) {
$canattempt = false;
} }
/// Determine if we should be showing a start/continue attempt button, if ($canattempt) {
/// or a button to go back to the course page. echo '<br>';
echo $OUTPUT->box_start('gameattempt');
$buttontext = ''; // This will be set something if as start/continue attempt button should appear.
if ($unfinished) { if ($numattempts == 0) {
if ($canattempt) { $buttontext = get_string('attemptgamenow', 'game');
$buttontext = get_string('continueattemptgame', 'game'); } else {
} $buttontext = get_string('reattemptgame', 'game');
} else {
//Game is finished. Check if max number of attempts is reached
if( !game_can_start_new_attempt( $game))
$canattempt = false;
if ($canattempt) {
echo '<br>';
if ($numattempts == 0) {
$buttontext = get_string('attemptgamenow', 'game');
} else {
$buttontext = get_string('reattemptgame', 'game');
}
} }
} }
}
/// Now actually print the appropriate button. // Now actually print the appropriate button.
echo $strtimeopenclose;
echo $strtimeopenclose; if ($buttontext) {
global $OUTPUT;
if ($buttontext) { $strconfirmstartattempt = '';
global $OUTPUT; // Show the start button, in a div that is initially hidden.
echo '<div id="gamestartbuttondiv">';
$url = new moodle_url($CFG->wwwroot.'/mod/game/attempt.php', array('id' => $id));
$button = new single_button($url, $buttontext);
echo $OUTPUT->render($button);
echo "</div>\n";
} else {
echo $OUTPUT->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id);
}
echo $OUTPUT->box_end();
$strconfirmstartattempt = ''; echo $OUTPUT->footer();
/// Show the start button, in a div that is initially hidden.
echo '<div id="gamestartbuttondiv">';
$url = new moodle_url($CFG->wwwroot.'/mod/game/attempt.php', array('id' => $id));
$button = new single_button($url, $buttontext);
echo $OUTPUT->render($button);
echo "</div>\n";
} else {
echo $OUTPUT->continue_button($CFG->wwwroot . '/course/view.php?id=' . $course->id);
}
echo $OUTPUT->box_end();
echo $OUTPUT->footer();

Loading…
Cancel
Save