Browse Source

Fix:Coding style

MOODLE_20_STABLE
Vasilis Daloukas 9 years ago
parent
commit
0751505215
  1. 39
      backup/moodle2/backup_game_activity_task.class.php
  2. 12
      backup/moodle2/backup_game_settingslib.php
  3. 166
      backup/moodle2/backup_game_stepslib.php
  4. 170
      backup/moodle2/restore_game_activity_task.class.php
  5. 114
      backup/moodle2/restore_game_stepslib.php
  6. 1269
      bookquiz/importodt.php
  7. 490
      bookquiz/importppt.php
  8. 774
      bookquiz/play.php
  9. 302
      bookquiz/questions.php
  10. 110
      bookquiz/toc.php
  11. 174
      bookquiz/view.php

39
backup/moodle2/backup_game_activity_task.class.php

@ -1,5 +1,4 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
@ -23,10 +22,10 @@
* @version $Id: backup_game_activity_task.class.php,v 1.2 2012/07/25 11:16:04 bdaloukas Exp $
* @package game
**/
require_once($CFG->dirroot . '/mod/game/backup/moodle2/backup_game_stepslib.php'); // Because it exists (must)
require_once($CFG->dirroot . '/mod/game/backup/moodle2/backup_game_settingslib.php'); // Because it exists (optional)
require_once($CFG->dirroot . '/mod/game/backup/moodle2/backup_game_stepslib.php'); // Because it exists (must).
require_once($CFG->dirroot . '/mod/game/backup/moodle2/backup_game_settingslib.php'); // Because it exists (optional).
/**
* game backup task that provides all the settings and steps to perform one
* complete backup of the activity
@ -37,34 +36,34 @@ class backup_game_activity_task extends backup_activity_task {
* Define (add) particular settings this activity can have
*/
protected function define_my_settings() {
// No particular settings for this activity
// No particular settings for this activity.
}
/**
* Define (add) particular steps this activity can have
*/
protected function define_my_steps() {
// Game only has one structure step
$this->add_step(new backup_game_activity_structure_step('game_structure', 'game.xml'));
// Game only has one structure step.
$this->add_step(new backup_game_activity_structure_step('game_structure', 'game.xml'));
}
/**
* Code the transformations to perform in the activity in
* order to get transportable (encoded) links
*/
static public function encode_content_links($content) {
global $CFG;
$base = preg_quote($CFG->wwwroot,"/");
// Link to the list of gamess
$search="/(".$base."\/mod\/game\/index.php\?id\=)([0-9]+)/";
$content= preg_replace($search, '$@GAMEINDEX*$2@$', $content);
// Link to game view by moduleid
$search="/(".$base."\/mod\/game\/view.php\?id\=)([0-9]+)/";
$content= preg_replace($search, '$@GAMEVIEWBYID*$2@$', $content);
$base = preg_quote($CFG->wwwroot, "/");
// Link to the list of games.
$search = "/(".$base."\/mod\/game\/index.php\?id\=)([0-9]+)/";
$content = preg_replace($search, '$@GAMEINDEX*$2@$', $content);
// Link to game view by moduleid.
$search = "/(".$base."\/mod\/game\/view.php\?id\=)([0-9]+)/";
$content = preg_replace($search, '$@GAMEVIEWBYID*$2@$', $content);
return $content;
}
}

12
backup/moodle2/backup_game_settingslib.php

@ -1,5 +1,4 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
@ -14,14 +13,15 @@
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package moodlecore
* @subpackage backup-moodle2
* @copyright 2010 onwards YOUR_NAME_GOES_HERE {@link YOUR_URL_GOES_HERE}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
// This activity has not particular settings but the inherited from the generic
// backup_activity_task so here there isn't any class definition, like the ones
// existing in /backup/moodle2/backup_settingslib.php (activities section)
/** This activity has not particular settings but the inherited from the generic
* backup_activity_task so here there isn't any class definition, like the ones
* existing in /backup/moodle2/backup_settingslib.php (activities section)
*/

166
backup/moodle2/backup_game_stepslib.php

@ -1,5 +1,4 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
@ -20,8 +19,8 @@
* @subpackage backup-moodle2
* @author bdaloukas
* @version $Id: backup_game_stepslib.php,v 1.5 2012/07/25 11:16:04 bdaloukas Exp $
*/
*/
/**
* Define all the backup steps that will be used by the backup_game_activity_task
*/
@ -33,10 +32,10 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
protected function define_structure() {
// To know if we are including userinfo
// To know if we are including userinfo.
$userinfo = $this->get_setting_value('userinfo');
// Define each element separated
// Define each element separated.
$game = new backup_nested_element('game', array('id'), array(
'name', 'sourcemodule', 'timeopen', 'timeclose', 'quizid',
'glossaryid', 'glossarycategoryid', 'questioncategoryid', 'bookid',
@ -45,16 +44,17 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
'shuffle', 'timemodified', 'toptext', 'bottomtext',
'grademethod', 'grade', 'decimalpoints', 'popup',
'review', 'attempts', 'glossaryid2', 'glossarycategoryid2',
'language', 'subcategories', 'maxattempts'
'language', 'subcategories', 'maxattempts'
));
$exporthtmls = new backup_nested_element('game_export_htmls');
$exporthtml = new backup_nested_element('game_export_html', array('id'), array(
'filename', 'title', 'checkbutton', 'printbutton', 'inputsize', 'maxpicturewidth', 'maxpictureheight'));
'filename', 'title', 'checkbutton', 'printbutton', 'inputsize', 'maxpicturewidth', 'maxpictureheight'));
$exportjavames = new backup_nested_element('game_export_javames');
$exportjavame = new backup_nested_element('game_export_javame', array('id'), array(
'filename', 'icon', 'createdby', 'vendor', 'name', 'description', 'version', 'maxpicturewidth', 'maxpictureheight'));
'filename', 'icon', 'createdby', 'vendor', 'name', 'description', 'version',
'maxpicturewidth', 'maxpictureheight'));
$grades = new backup_nested_element('game_grades');
$grade = new backup_nested_element('game_grade', array('id'), array(
@ -63,122 +63,122 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$repetitions = new backup_nested_element('game_repetitions');
$repetition = new backup_nested_element('game_repetition', array('id'), array(
'userid', 'questionid', 'glossaryentryid', 'repetitions'));
$attempts = new backup_nested_element('game_attempts');
$attempts = new backup_nested_element('game_attempts');
$attempt = new backup_nested_element('game_attempt', array('id'), array(
'userid', 'timestart','timefinish', 'timelastattempt', 'lastip',
'lastremotehost', 'preview', 'attempt','score', 'attempts', 'language'));
'userid', 'timestart', 'timefinish', 'timelastattempt', 'lastip',
'lastremotehost', 'preview', 'attempt', 'score', 'attempts', 'language'));
$querys = new backup_nested_element('game_queries');
$query = new backup_nested_element('game_query', array('id'), array(
'gamekind', 'userid','sourcemodule', 'questionid', 'glossaryentryid',
'questiontext', 'score', 'timelastattempt','studentanswer', 'col', 'row',
'gamekind', 'userid', 'sourcemodule', 'questionid', 'glossaryentryid',
'questiontext', 'score', 'timelastattempt', 'studentanswer', 'col', 'row',
'horizontal', 'answertext', 'correct', 'attachment', 'answerid', 'tries'));
$bookquizs = new backup_nested_element('game_bookquizs');
$bookquizs = new backup_nested_element('game_bookquizs');
$bookquiz = new backup_nested_element('game_bookquiz', array('id'), array('lastchapterid'));
$bookquiz_chapters = new backup_nested_element('game_bookquiz_chapters');
$bookquiz_chapter = new backup_nested_element('game_bookquiz_chapter', array('id'), array( 'chapterid'));
$bookquiz_questions = new backup_nested_element('game_bookquiz_questions');
$bookquiz_question = new backup_nested_element('game_bookquiz_question', array('id'), array(
$bookquizchapters = new backup_nested_element('game_bookquiz_chapters');
$bookquizchapter = new backup_nested_element('game_bookquiz_chapter', array('id'), array( 'chapterid'));
$bookquizquestions = new backup_nested_element('game_bookquiz_questions');
$bookquizquestion = new backup_nested_element('game_bookquiz_question', array('id'), array(
'chapterid', 'questioncategoryid'));
$crosss = new backup_nested_element('game_crosss');
$crosss = new backup_nested_element('game_crosss');
$cross = new backup_nested_element('game_cross', array('id'), array(
'cols', 'rows', 'words', 'wordsall', 'createscore', 'createtries',
'cols', 'rows', 'words', 'wordsall', 'createscore', 'createtries',
'createtimelimit', 'createconnectors', 'createfilleds', 'createspaces', 'triesplay'));
$cryptexs = new backup_nested_element('game_cryptexs');
$cryptexs = new backup_nested_element('game_cryptexs');
$cryptex = new backup_nested_element('game_cryptex', array('id'), array('letters'));
$hangmans = new backup_nested_element('game_hangmans');
$hangmans = new backup_nested_element('game_hangmans');
$hangman = new backup_nested_element('game_hangman', array('id'), array(
'queryid', 'letters', 'allletters', 'try', 'maxtries', 'finishedword',
'queryid', 'letters', 'allletters', 'try', 'maxtries', 'finishedword',
'corrects', 'iscorrect'));
$hiddenpictures = new backup_nested_element('game_hiddenpictures');
$hiddenpictures = new backup_nested_element('game_hiddenpictures');
$hiddenpicture = new backup_nested_element('game_hiddenpicture', array('id'), array('correct', 'wrong', 'found'));
$millionaires = new backup_nested_element('game_millionaires');
$millionaires = new backup_nested_element('game_millionaires');
$millionaire = new backup_nested_element('game_millionaire', array('id'), array('queryid', 'state', 'level'));
$snakes = new backup_nested_element('game_snakes');
$snakes = new backup_nested_element('game_snakes');
$snake = new backup_nested_element('game_snake', array('id'), array('snakesdatabaseid', 'position', 'queryid', 'dice'));
$sudokus = new backup_nested_element('game_sudokus');
$sudokus = new backup_nested_element('game_sudokus');
$sudoku = new backup_nested_element('game_sudoku', array('id'), array('level', 'data', 'opened', 'guess'));
// Build the tree
$game->add_child($bookquiz_questions);
$bookquiz_questions->add_child($bookquiz_question);
// Build the tree.
$game->add_child( $bookquizquestions);
$bookquizquestions->add_child( $bookquizquestion);
$game->add_child( $exporthtmls);
$exporthtmls->add_child( $exporthtml);
$game->add_child( $exportjavames);
$exportjavames->add_child( $exportjavame);
$game->add_child( $grades);
$grades->add_child( $grade);
$game->add_child( $repetitions);
$repetitions->add_child( $repetition);
// All these source definitions only happen if we are including user info
// All these source definitions only happen if we are including user info.
if ($userinfo) {
$game->add_child( $attempts);
$attempts->add_child( $attempt);
$game->add_child( $attempts);
$attempts->add_child( $attempt);
$attempts->add_child( $querys);
$querys->add_child( $query);
$attempts->add_child( $querys);
$querys->add_child( $query);
$attempts->add_child( $bookquizs);
$bookquizs->add_child( $bookquiz);
$attempts->add_child( $bookquizs);
$bookquizs->add_child( $bookquiz);
$game->add_child( $bookquizchapters);
$bookquizchapters->add_child($bookquizchapter);
$game->add_child($bookquiz_chapters);
$bookquiz_chapters->add_child($bookquiz_chapter);
$attempts->add_child( $crosss);
$crosss->add_child( $cross);
$attempts->add_child( $crosss);
$crosss->add_child( $cross);
$attempts->add_child( $cryptexs);
$cryptexs->add_child( $cryptex);
$attempts->add_child( $cryptexs);
$cryptexs->add_child( $cryptex);
$attempts->add_child( $hangmans);
$hangmans->add_child( $hangman);
$attempts->add_child( $hangmans);
$hangmans->add_child( $hangman);
$attempts->add_child( $hiddenpictures);
$hiddenpictures->add_child( $hiddenpicture);
$attempts->add_child( $hiddenpictures);
$hiddenpictures->add_child( $hiddenpicture);
$attempts->add_child( $millionaires);
$millionaires->add_child( $millionaire);
$attempts->add_child( $millionaires);
$millionaires->add_child( $millionaire);
$attempts->add_child( $snakes);
$snakes->add_child( $snake);
$attempts->add_child( $snakes);
$snakes->add_child( $snake);
$attempts->add_child( $sudokus);
$sudokus->add_child( $sudoku);
}
// Define sources
$attempts->add_child( $sudokus);
$sudokus->add_child( $sudoku);
}
// Define sources.
$game->set_source_table('game', array('id' => backup::VAR_ACTIVITYID));
$bookquiz_question->set_source_table('game_bookquiz_questions', array('gameid' => backup::VAR_ACTIVITYID));
$bookquizquestion->set_source_table('game_bookquiz_questions', array('gameid' => backup::VAR_ACTIVITYID));
$exporthtml->set_source_table('game_export_html', array('id' => backup::VAR_ACTIVITYID));
$exportjavame->set_source_table('game_export_javame', array('id' => backup::VAR_ACTIVITYID));
// All the rest of elements only happen if we are including user info
// All the rest of elements only happen if we are including user info.
if ($userinfo) {
$grade->set_source_table('game_grades', array('gameid' => backup::VAR_ACTIVITYID));
$repetition->set_source_table('game_repetitions', array('gameid' => backup::VAR_ACTIVITYID));
$attempt->set_source_table('game_attempts', array( 'gameid' => backup::VAR_ACTIVITYID));
$attempt->set_source_table('game_queries', array( 'attemptid' => backup::VAR_PARENTID));
$bookquiz->set_source_table('game_bookquiz', array( 'id' => backup::VAR_ACTIVITYID));
$bookquiz_chapter->set_source_table('game_bookquiz_chapters', array( 'id' => backup::VAR_PARENTID));
$bookquizchapter->set_source_table('game_bookquiz_chapters', array( 'id' => backup::VAR_PARENTID));
$cross->set_source_table('game_cross', array( 'id' => backup::VAR_PARENTID));
$cryptex->set_source_table('game_cryptex', array( 'id' => backup::VAR_PARENTID));
$hangman->set_source_table('game_hangman', array( 'id' => backup::VAR_PARENTID));
@ -187,7 +187,7 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$snake->set_source_table('game_snakes', array( 'id' => backup::VAR_PARENTID));
$sudoku->set_source_table('game_sudoku', array( 'id' => backup::VAR_PARENTID));
}
// Define id annotations
// Define id annotations.
$attempt->annotate_ids('user', 'userid');
$grade->annotate_ids('user', 'userid');
$repetition->annotate_ids('user', 'userid');
@ -198,17 +198,17 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$query->annotate_ids('glossary_enrty', 'glossaryentryid');
$query->annotate_ids('question_answer', 'answerid');
$bookquiz_question->annotate_ids('book_chapter', 'chapterid');
$bookquiz_question->annotate_ids('question_category', 'questioncategoryid');
$bookquiz_chapter->annotate_ids('book_chapter', 'chapterid');
$bookquizquestion->annotate_ids('book_chapter', 'chapterid');
$bookquizquestion->annotate_ids('question_category', 'questioncategoryid');
$bookquizchapter->annotate_ids('book_chapter', 'chapterid');
$hangman->annotate_ids('game_query', 'queryid');
$millionaire->annotate_ids('game_query', 'queryid');
// Define file annotations
$game->annotate_files('mod_game', 'snakes_file', null); // This file area hasn't itemid
$game->annotate_files('mod_game', 'snakes_board', null); // This file area hasn't itemid
// Return the root element (game), wrapped into standard activity structure
// Define file annotations.
$game->annotate_files('mod_game', 'snakes_file', null); // This file area hasn't itemid.
$game->annotate_files('mod_game', 'snakes_board', null); // This file area hasn't itemid.
// Return the root element (game), wrapped into standard activity structure.
return $this->prepare_activity_structure( $game);
}
}

170
backup/moodle2/restore_game_activity_task.class.php

@ -1,5 +1,4 @@
<?php // $Id: restore_game_activity_task.class.php,v 1.3 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
@ -23,7 +22,7 @@
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->dirroot . '/mod/game/backup/moodle2/restore_game_stepslib.php'); // Because it exists (must)
require_once($CFG->dirroot . '/mod/game/backup/moodle2/restore_game_stepslib.php'); // Because it exists (must).
/**
* game restore task that provides all the settings and steps to perform one
@ -35,14 +34,14 @@ class restore_game_activity_task extends restore_activity_task {
* Define (add) particular settings this activity can have
*/
protected function define_my_settings() {
// No particular settings for this activity
// No particular settings for this activity.
}
/**
* Define (add) particular steps this activity can have
*/
protected function define_my_steps() {
// Game only has one structure step
// Game only has one structure step.
$this->add_step(new restore_game_activity_structure_step('game_structure', 'game.xml'));
}
@ -77,7 +76,7 @@ class restore_game_activity_task extends restore_activity_task {
*/
static public function define_restore_log_rules() {
$rules = array();
$rules[] = new restore_log_rule('game', 'add', 'view.php?id={course_module}', '{game}');
$rules[] = new restore_log_rule('game', 'update', 'view.php?id={course_module}', '{game}');
$rules[] = new restore_log_rule('game', 'view', 'view.php?id={course_module}', '{game}');
@ -87,7 +86,7 @@ class restore_game_activity_task extends restore_activity_task {
return $rules;
}
/**
* Define the restore log rules that will be applied
* by the {@link restore_logs_processor} when restoring
@ -100,134 +99,149 @@ class restore_game_activity_task extends restore_activity_task {
*/
static public function define_restore_log_rules_for_course() {
$rules = array();
// Fix old wrong uses (missing extension)
// Fix old wrong uses (missing extension).
$rules[] = new restore_log_rule('game', 'view all', 'index?id={course}', null,
null, null, 'index.php?id={course}');
$rules[] = new restore_log_rule('game', 'view all', 'index.php?id={course}', null);
return $rules;
}
public function after_restore() {
// Do something at end of restore
// Do something at end of restore.
global $DB;
// Get the blockid
// Get the blockid.
$gameid = $this->get_activityid();
// Extract Game configdata and update it to point to the new glossary
$rec = $DB->get_record_select( 'game', 'id='.$gameid, null,
'id,quizid,glossaryid,glossarycategoryid,questioncategoryid,bookid,glossaryid2,glossarycategoryid2');
// Extract Game configdata and update it to point to the new glossary.
$rec = $DB->get_record_select( 'game', 'id='.$gameid,
null, 'id,quizid,glossaryid,glossarycategoryid,questioncategoryid,bookid,glossaryid2,glossarycategoryid2');
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'quiz', $rec->quizid);
if( $ret != false)
if ($ret != false) {
$rec->quizid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid);
if( $ret != false)
if ($ret != false) {
$rec->glossaryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid);
if( $ret != false)
if ($ret != false) {
$rec->glossarycategoryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_categories', $rec->questioncategoryid);
if( $ret != false)
if ($ret != false) {
$rec->questioncategoryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book', $rec->bookid);
if( $ret != false)
if ($ret != false) {
$rec->bookid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid2);
if( $ret != false)
if ($ret != false) {
$rec->glossaryid2 = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid);
if( $ret != false)
if ($ret != false) {
$rec->glossarycategoryid = $ret->newitemid;
}
$DB->update_record( 'game', $rec);
//game_repetitions
// Read game_repetitions.
$recs = $DB->get_records_select( 'game_repetitions', 'gameid='.$gameid, null, '',
'id,questionid,glossaryentryid');
if( $recs != false){
foreach( $recs as $rec){
if ($recs != false) {
foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid);
if( $ret != false)
if ($ret != false) {
$rec->questionid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid);
if( $ret != false)
if ($ret != false) {
$rec->glossaryentryid = $ret->newitemid;
}
$DB->update_record( 'game_repetitions', $rec);
}
}
}
//game_queries
// Read game_queries.
$recs = $DB->get_records_select( 'game_queries', 'gameid='.$gameid, null, '',
'id,questionid,glossaryentryid,answerid');
if( $recs != false){
foreach( $recs as $rec){
if ($recs != false) {
foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid);
if( $ret != false)
if ($ret != false) {
$rec->questionid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid);
if( $ret != false)
if ($ret != false) {
$rec->glossaryentryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_answers', $rec->glossaryentryid);
if( $ret != false)
if ($ret != false) {
$rec->answerid = $ret->newitemid;
$DB->update_record( 'game_queries', $rec);
}
}
$DB->update_record( 'game_queries', $rec);
}
}
//bookquiz
// Read bookquiz.
$recs = $DB->get_records_select( 'game_bookquiz', 'id='.$gameid, null, '', 'id,lastchapterid');
if( $recs != false){
foreach( $recs as $rec){
if ($recs != false) {
foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->lastchapterid);
if( $ret != false)
if ($ret != false) {
$rec->lastchapterid = $ret->newitemid;
$DB->update_record( 'game_bookquiz', $rec);
}
}
$DB->update_record( 'game_bookquiz', $rec);
}
}
//bookquiz_chapters
$sql = "SELECT gbc.* FROM {game_bookquiz_chapters} gbc LEFT JOIN {game_attempts} a ON gbc.attemptid = a.id WHERE a.gameid=$gameid";
// Read bookquiz_chapters.
$sql = "SELECT gbc.* ".
"FROM {game_bookquiz_chapters} gbc LEFT JOIN {game_attempts} a ON gbc.attemptid = a.id".
" WHERE a.gameid=$gameid";
$recs = $DB->get_records_sql( $sql);
if( $recs != false){
foreach( $recs as $rec){
if ($recs != false) {
foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid);
if( $ret != false)
if ($ret != false) {
$rec->chapterid = $ret->newitemid;
$DB->update_record( 'game_bookquiz_chapter', $rec);
}
}
}
$DB->update_record( 'game_bookquiz_chapter', $rec);
}
}
//bookquiz_questions
// Read bookquiz_questions.
$recs = $DB->get_records_select( 'game_bookquiz_questions', 'id='.$gameid, null, '', 'id,chapterid,questioncategoryid');
if( $recs != false){
foreach( $recs as $rec){
if ($recs != false) {
foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid);
if( $ret != false)
if ($ret != false) {
$rec->chapterid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->questioncategoryid);
if( $ret != false)
if ($ret != false) {
$rec->questioncategoryid = $ret->newitemid;
$DB->update_record( 'game_bookquiz_questions', $rec);
}
}
$DB->update_record( 'game_bookquiz_questions', $rec);
}
}
}
}

114
backup/moodle2/restore_game_stepslib.php

@ -1,5 +1,4 @@
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
@ -29,23 +28,25 @@
* Structure step to restore one game activity
*/
class restore_game_activity_structure_step extends restore_activity_structure_step {
protected function define_structure() {
$paths = array();
$userinfo = $this->get_setting_value('userinfo');
$paths[] = new restore_path_element('game', '/activity/game');
$paths[] = new restore_path_element('game_export_html', '/activity/game/game_export_htmls/game_export_html');
$paths[] = new restore_path_element('game_export_javame', '/activity/game/game_export_htmls/game_export_javame');
$paths[] = new restore_path_element('game_bookquiz_question', '/activity/game/game_bookquiz_questions/game_bookquiz_question');
$paths[] = new restore_path_element(
'game_bookquiz_question', '/activity/game/game_bookquiz_questions/game_bookquiz_question');
if ($userinfo) {
$paths[] = new restore_path_element('game_grade', '/activity/game/game_grades/game_grade');
$paths[] = new restore_path_element('game_repetition', '/activity/game/game_repetiotions/game_repetition');
$paths[] = new restore_path_element('game_attempt', '/activity/game/game_attempts/game_attempt');
$paths[] = new restore_path_element('game_query', '/activity/game/game_querys/game_query');
$paths[] = new restore_path_element('game_bookquiz', '/activity/game/game_bookquizs/game_bookquiz');
$paths[] = new restore_path_element('game_bookquiz_chapter', '/activity/game/game_bookquiz_chapters/game_bookquiz_chapter');
$paths[] = new restore_path_element('game_bookquiz_chapter',
'/activity/game/game_bookquiz_chapters/game_bookquiz_chapter');
$paths[] = new restore_path_element('game_cross', '/activity/game/game_crosss/game_cross');
$paths[] = new restore_path_element('game_cryptex', '/activity/game/game_cryptexs/game_cryptex');
$paths[] = new restore_path_element('game_hangman', '/activity/game/game_hangmans/game_hangman');
@ -54,50 +55,48 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$paths[] = new restore_path_element('game_snake', '/activity/game/game_snakes/game_snake');
$paths[] = new restore_path_element('game_sudoku', '/activity/game/game_sudokus/game_sudoku');
}
// Return the paths wrapped into standard activity structure
// Return the paths wrapped into standard activity structure.
return $this->prepare_activity_structure($paths);
}
protected function process_game($data) {
global $DB;
$data = (object)$data;
$oldid = $data->id;
$data->course = $this->get_courseid();
$data->course = $this->get_courseid();
$data->timemodified = $this->apply_date_offset($data->timemodified);
// insert the game record
// Insert the game record.
$newitemid = $DB->insert_record('game', $data);
// immediately after inserting "activity" record, call this
// Immediately after inserting "activity" record, call this.
$this->apply_activity_instance($newitemid);
}
protected function process_game_export_html($data) {
global $DB;
$data = (object)$data;
$data->id = $this->get_new_parentid('game');
if( $data->id == 0)
return;
$DB->insert_record('game_export_html', $data);
if ($data->id ! 0) {
$DB->insert_record('game_export_html', $data);
}
}
protected function process_game_export_javame($data) {
global $DB;
$data = (object)$data;
$data->id = $this->get_new_parentid('game');
if( $data->id == 0)
return;
$DB->insert_record('game_export_javame', $data);
}
if ($data->id != 0) {
$DB->insert_record('game_export_javame', $data);
}
}
protected function process_game_grade($data) {
global $DB;
@ -109,7 +108,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$DB->insert_record('game_grades', $data);
}
protected function process_game_repetition($data) {
global $DB;
@ -118,10 +117,10 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->gameid = $this->get_new_parentid('game');
$data->userid = $this->get_mappingid('user', $data->userid);
$DB->insert_record('game_repetitions', $data);
}
protected function process_game_attempt($data) {
global $DB;
@ -131,13 +130,16 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->gameid = $this->get_new_parentid('game');
$data->userid = $this->get_mappingid('user', $data->userid);
if( !isset( $data->timestart))
if (!isset( $data->timestart)) {
$data->timestart = 0;
if( !isset( $data->timefinish))
}
if (!isset( $data->timefinish)) {
$data->timefinish = 0;
if( !isset( $data->timelastattempt))
$data->timelastattempt = 0;
}
if (!isset( $data->timelastattempt)) {
$data->timelastattempt = 0;
}
$data->timestart = $this->apply_date_offset($data->timestart);
$data->timefinish = $this->apply_date_offset($data->timefinish);
$data->timelastattempt = $this->apply_date_offset($data->timelastattempt);
@ -145,7 +147,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$newitemid = $DB->insert_record('game_attempts', $data);
$this->set_mapping('game_attempt', $oldid, $newitemid);
}
protected function process_game_query($data) {
global $DB;
@ -158,8 +160,8 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$newitemid = $DB->insert_record('game_queries', $data);
$this->set_mapping('game_query', $oldid, $newitemid);
}
}
protected function process_game_bookquiz($data) {
global $DB;
@ -168,7 +170,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->id = $this->get_new_parentid('game');
$DB->insert_record('game_bookquiz', $data);
}
}
protected function process_game_bookquiz_chapter($data) {
global $DB;
@ -178,17 +180,17 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->gameid = $this->get_new_parentid('game');
$DB->insert_record('game_bookquiz_chapters', $data);
}
}
protected function process_game_bookquiz_question($data) {
global $DB;
$data = (object)$data;
$data->gameid = $this->get_new_parentid('game');
$DB->insert_record('game_bookquiz_questions', $data);
}
}
protected function process_game_cross($data) {
global $DB;
@ -198,7 +200,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->id = $this->get_new_parentid('game');
$DB->insert_record('game_cross', $data);
}
}
protected function process_game_cryptex($data) {
global $DB;
@ -208,7 +210,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->id = $this->get_new_parentid('game');
$DB->insert_record('game_cryptex', $data);
}
}
protected function process_game_hangman($data) {
global $DB;
@ -219,7 +221,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->queryid = $this->get_mappingid('game_query', $data->queryid);
$DB->insert_record('game_hangman', $data);
}
}
protected function process_game_hiddenpicture($data) {
global $DB;
@ -229,7 +231,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->id = $this->get_new_parentid('game');
$DB->insert_record('game_hiddenpicture', $data);
}
}
protected function process_game_millionaire($data) {
global $DB;
@ -240,9 +242,9 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->queryid = $this->get_mappingid('game_query', $data->queryid);
$DB->insert_record('game_millionaire', $data);
}
protected function process_game_snake($data) {
}
protected function process_game_snake($data) {
global $DB;
$data = (object)$data;
@ -252,7 +254,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$DB->insert_record('game_snakes', $data);
}
protected function process_game_sudoku($data) {
global $DB;
@ -262,9 +264,9 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$DB->insert_record('game_sudoku', $data);
}
protected function after_execute() {
// Add Game related files, no need to match by itemname (just internally handled context)
// Add Game related files, no need to match by itemname (just internally handled context).
$this->add_related_files('mod_game', 'snakes_file', null);
$this->add_related_files('mod_game', 'snakes_board', null);
}

1269
bookquiz/importodt.php

File diff suppressed because it is too large

490
bookquiz/importppt.php

@ -1,4 +1,19 @@
<?php // $Id: importppt.php,v 1.3 2012/07/25 11:16:05 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 is a very rough importer for powerpoint slides
* Export a powerpoint presentation with powerpoint as html pages
@ -13,141 +28,146 @@
* @package lesson
**/
require_once("../../config.php");
require_once("locallib.php");
require_once("../../config.php");
require_once("locallib.php");
$id = required_param('id', PARAM_INT); // Course Module ID
$pageid = optional_param('pageid', '', PARAM_INT); // Page ID
global $matches;
if (! $cm = get_coursemodule_from_id('lesson', $id)) {
print_error('Course Module ID was incorrect');
}
$id = required_param('id', PARAM_INT); // Course Module ID.
$pageid = optional_param('pageid', '', PARAM_INT); // Page ID.
global $matches;
if (! $course = $DB->get_record('course', array( 'id' => $cm->course))) {
print_error('Course is misconfigured');
}
// allows for adaption for multiple modules
if(! $modname = $DB->get_field('modules', 'name', array( 'id' => $cm->module))) {
print_error('Could not find module name');
}
if (! $cm = get_coursemodule_from_id('lesson', $id)) {
print_error('Course Module ID was incorrect');
}
if (! $mod = $DB->get_record($modname, array( "id" => $cm->instance))) {
print_error('Course module is incorrect');
}
if (! $course = $DB->get_record('course', array( 'id' => $cm->course))) {
print_error('Course is misconfigured');
}
require_login($course->id, false);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/lesson:edit', $context);
// Allows for adaption for multiple modules.
if (!$modname = $DB->get_field('modules', 'name', array( 'id' => $cm->module))) {
print_error('Could not find module name');
}
$strimportppt = get_string("importppt", "lesson");
$strlessons = get_string("modulenameplural", "lesson");
if (! $mod = $DB->get_record($modname, array( "id" => $cm->instance))) {
print_error('Course module is incorrect');
}
echo $OUTPUT->heading("$strimportppt", " $strimportppt", "<a href=\"index.php?id=$course->id\">$strlessons</a> -> <a href=\"{$CFG->wwwroot}/mod/$modname/view.php?id=$cm->id\">".format_string($mod->name,true)."</a>-> $strimportppt");
require_login($course->id, false);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/lesson:edit', $context);
if ($form = data_submitted()) { /// Filename
$strimportppt = get_string("importppt", "lesson");
$strlessons = get_string("modulenameplural", "lesson");
if (empty($_FILES['newfile'])) { // file was just uploaded
notify(get_string("uploadproblem") );
}
echo $OUTPUT->heading("$strimportppt", " $strimportppt",
"<a href=\"index.php?id=$course->id\">$strlessons</a>".
" -> <a href=\"{$CFG->wwwroot}/mod/$modname/view.php?id=$cm->id\">".format_string($mod->name, true)."</a>-> $strimportppt");
if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) {
notify(get_string("uploadnofilefound") );
} else { // Valid file is found
if ($rawpages = readdata($_FILES, $course->id, $modname))
{ // first try to reall all of the data in
$pageobjects = extract_data($rawpages, $course->id, $mod->name, $modname); // parse all the html files into objects
clean_temp(); // all done with files so dump em
$mod_create_objects = $modname.'_create_objects';
$mod_save_objects = $modname.'_save_objects';
$objects = $mod_create_objects($pageobjects, $mod->id); // function to preps the data to be sent to DB
if(! $mod_save_objects($objects, $mod->id, $pageid)) { // sends it to DB
print_error( 'could not save');
}
} else {
print_error('could not get data');
}
if ($form = data_submitted()) { // Filename.
if (empty($_FILES['newfile'])) { // File was just uploaded.
notify(get_string("uploadproblem") );
}
echo "<hr>";
print_continue("{$CFG->wwwroot}/mod/$modname/view.php?id=$cm->id");
echo $OUTPUT->footer($course);
exit;
if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) {
notify(get_string("uploadnofilefound") );
} else {
// Valid file is found.
if ($rawpages = readdata($_FILES, $course->id, $modname)) {
// First try to reall all of the data in.
// parse all the html files into objects.
$pageobjects = extract_data($rawpages, $course->id, $mod->name, $modname);
clean_temp(); // All done with files so dump em.
$modcreateobjects = $modname.'_create_objects';
$modsaveobjects = $modname.'_save_objects';
// Function to preps the data to be sent to DB.
$objects = $modcreateobjects($pageobjects, $mod->id);
if (! $modsaveobjects($objects, $mod->id, $pageid)) {
// Sends it to DB.
print_error( 'could not save');
}
} else {
print_error('could not get data');
}
echo "<hr>";
print_continue("{$CFG->wwwroot}/mod/$modname/view.php?id=$cm->id");
echo $OUTPUT->footer($course);
exit;
}
}
/// Print upload form
// Print upload form.
print_heading_with_help($strimportppt, "importppt", "lesson");
print_heading_with_help($strimportppt, "importppt", "lesson");
echo $OUTPUT->box_start('center');
echo "<form id=\"theform\" enctype=\"multipart/form-data\" method=\"post\">";
echo "<input type=\"hidden\" name=\"id\" value=\"$cm->id\" />\n";
echo "<input type=\"hidden\" name=\"pageid\" value=\"$pageid\" />\n";
echo "<table cellpadding=\"5\">";
echo $OUTPUT->box_start('center');
echo "<form id=\"theform\" enctype=\"multipart/form-data\" method=\"post\">";
echo "<input type=\"hidden\" name=\"id\" value=\"$cm->id\" />\n";
echo "<input type=\"hidden\" name=\"pageid\" value=\"$pageid\" />\n";
echo "<table cellpadding=\"5\">";
echo "<tr><td align=\"right\">";
print_string("upload");
echo ":</td><td>";
echo "<input name=\"newfile\" type=\"file\" size=\"50\" />";
echo "</td></tr><tr><td>&nbsp;</td><td>";
echo "<input type=\"submit\" name=\"save\" value=\"".get_string("uploadthisfile")."\" />";
echo "</td></tr>";
echo "<tr><td align=\"right\">";
print_string("upload");
echo ":</td><td>";
echo "<input name=\"newfile\" type=\"file\" size=\"50\" />";
echo "</td></tr><tr><td>&nbsp;</td><td>";
echo "<input type=\"submit\" name=\"save\" value=\"".get_string("uploadthisfile")."\" />";
echo "</td></tr>";
echo "</table>";
echo "</form>";
echo $OUTPUT->box_end();
echo "</table>";
echo "</form>";
echo $OUTPUT->box_end();
echo $OUTPUT->footer($course);
echo $OUTPUT->footer($course);
// START OF FUNCTIONS
// START OF FUNCTIONS.
/* this function expects a zip file to be uploaded. Then it parses
* outline.htm to determine the slide path. Then parses each
* slide to get data for the content
*/
function readdata($file, $courseid, $modname) {
// this function expects a zip file to be uploaded. Then it parses
// outline.htm to determine the slide path. Then parses each
// slide to get data for the content
global $CFG;
// create an upload directory in temp
make_upload_directory('temp/'.$modname);
// Create an upload directory in temp.
make_upload_directory('temp/'.$modname);
$base = $CFG->dataroot."/temp/$modname/";
$zipfile = $_FILES["newfile"]["name"];
$tempzipfile = $_FILES["newfile"]["tmp_name"];
// create our directory
$path_parts = pathinfo($zipfile);
$dirname = substr($zipfile, 0, strpos($zipfile, '.'.$path_parts['extension'])); // take off the extension
// Create our directory.
$pathparts = pathinfo($zipfile);
// Take off the extension.
$dirname = substr($zipfile, 0, strpos($zipfile, '.'.$pathparts['extension']));
if (!file_exists($base.$dirname)) {
mkdir($base.$dirname);
}
// move our uploaded file to temp/lesson
// Move our uploaded file to temp/lesson.
move_uploaded_file($tempzipfile, $base.$zipfile);
// unzip it!
// Unzip it!
unzip_file($base.$zipfile, $base, false);
$base = $base.$dirname; // update the base
// this is the file where we get the names of the files for the slides (in the correct order too)
$base = $base.$dirname; // Update the base.
// This is the file where we get the names of the files for the slides (in the correct order too).
$outline = $base.'/outline.htm';
$pages = array();
if (file_exists($outline) and is_readable($outline)) {
$outlinecontents = file_get_contents($outline);
$filenames = array();
preg_match_all("/javascript:GoToSld\('(.*)'\)/", $outlinecontents, $filenames); // this gets all of our files names
// This gets all of our files names.
preg_match_all("/javascript:GoToSld\('(.*)'\)/", $outlinecontents, $filenames);
// file $pages with the contents of all of the slides
// File $pages with the contents of all of the slides.
foreach ($filenames[1] as $file) {
$path = $base.'/'.$file;
if (is_readable($path)) {
@ -155,12 +175,13 @@ function readdata($file, $courseid, $modname) {
} else {
return false;
}
}
}
} else {
// cannot find the outline, so grab all files that start with slide
// Cannot find the outline, so grab all files that start with slide.
$dh = opendir($base);
while (false !== ($file = readdir($dh))) { // read throug the directory
if ('slide' == substr($file, 0, 5)) { // check for name (may want to check extension later)
while (false !== ($file = readdir($dh))) { // Read throug the directory.
if ('slide' == substr($file, 0, 5)) {
// Check for name (may want to check extension later).
$path = $base.'/'.$file;
if (is_readable($path)) {
$pages[$path] = file_get_contents($path);
@ -170,43 +191,45 @@ function readdata($file, $courseid, $modname) {
}
}
ksort($pages); // order them by file name
ksort($pages); // Order them by file name.
}
if (empty($pages)) {
return false;
}
return $pages;
}
/* This function attempts to extract the content out of the slides
* the slides are ugly broken xml. and the xml is broken... yeah...
*/
function extract_data($pages, $courseid, $lessonname, $modname) {
// this function attempts to extract the content out of the slides
// the slides are ugly broken xml. and the xml is broken... yeah...
global $CFG;
global $matches;
$extratedpages = array();
// directory for images
make_mod_upload_directory($courseid); // make sure moddata is made
make_upload_directory($courseid.'/moddata/'.$modname, false); // we store our images in a subfolder in here
// Directory for images.
make_mod_upload_directory($courseid); // Make sure moddata is made.
// We store our images in a subfolder in here.
make_upload_directory($courseid.'/moddata/'.$modname, false);
$imagedir = $CFG->dataroot.'/'.$courseid.'/moddata/'.$modname;
if ($CFG->slasharguments) {
$imagelink = $CFG->wwwroot.'/file.php/'.$courseid.'/moddata/'.$modname;
} else {
$imagelink = $CFG->wwwroot.'/file.php?file=/'.$courseid.'/moddata/'.$modname;
}
// try to make a unique subfolder to store the images
$lessonname = str_replace(' ', '_', $lessonname); // get rid of spaces
// Try to make a unique subfolder to store the images.
$lessonname = str_replace(' ', '_', $lessonname); // Get rid of spaces.
$i = 0;
while(true) {
while (true) {
if (!file_exists($imagedir.'/'.$lessonname.$i)) {
// ok doesnt exist so make the directory and update our paths
// Ok doesnt exist so make the directory and update our paths.
mkdir($imagedir.'/'.$lessonname.$i);
$imagedir = $imagedir.'/'.$lessonname.$i;
$imagelink = $imagelink.'/'.$lessonname.$i;
@ -214,68 +237,71 @@ function extract_data($pages, $courseid, $lessonname, $modname) {
}
$i++;
}
foreach ($pages as $file => $content) {
// to make life easier on our preg_match_alls, we strip out all tags except
// for div and img (where our content is). We want div because sometimes we
// can identify the content in the div based on the div's class
$tags = '<div><img>'; // should also allow <b><i>
$string = strip_tags($content,$tags);
//echo s($string);
/* to make life easier on our preg_match_alls, we strip out all tags except
* for div and img (where our content is). We want div because sometimes we
* can identify the content in the div based on the div's class
*/
$tags = '<div><img>'; // Should also allow <b><i>.
$string = strip_tags($content, $tags);
$matches = array();
// this will look for a non nested tag that is closed
// want to allow <b><i>(maybe more) tags but when we do that
// the preg_match messes up.
/* this will look for a non nested tag that is closed
* want to allow <b><i>(maybe more) tags but when we do that
* the preg_match messes up.
*/
preg_match_all("/(<([\w]+)[^>]*>)([^<\\2>]*)(<\/\\2>)/", $string, $matches);
//(<([\w]+)[^>]*>)([^<\\2>]*)(<\/\\2>) original pattern
//(<(div+)[^>]*>)[^(<div*)](<\/div>) work in progress
$path_parts = pathinfo($file);
$file = substr($path_parts['basename'], 0, strpos($path_parts['basename'], '.')); // get rid of the extension
$pathparts = pathinfo($file);
// Get rid of the extension.
$file = substr($pathparts['basename'], 0, strpos($pathparts['basename'], '.'));
$imgs = array();
// this preg matches all images
// This preg matches all images.
preg_match_all("/<img[^>]*(src\=\"(".$file."\_image[^>^\"]*)\"[^>]*)>/i", $string, $imgs);
// start building our page
// Start building our page.
$page = new stdClass;
$page->title = '';
$page->contents = array();
$page->images = array();
$page->source = $path_parts['basename']; // need for book only
// this foreach keeps the style intact. Found it doesn't help much. But if you want back uncomment
// this foreach and uncomment the line with the comment imgstyle in it. Also need to comment out
// the $page->images[]... line in the next foreach
/*foreach ($imgs[1] as $img) {
$page->images[] = '<img '.str_replace('src="', "src=\"$imagelink/", $img).' />';
}*/
$page->source = $pathparts['basename']; // Need for book only.
/* This foreach keeps the style intact.
* Found it doesn't help much. But if you want back uncomment
* this foreach and uncomment the line with the comment imgstyle in it.
* Also need to comment out
* the $page->images[]... line in the next foreach
*/
foreach ($imgs[2] as $img) {
copy($path_parts['dirname'].'/'.$img, $imagedir.'/'.$img);
$page->images[] = "<img src=\"$imagelink/$img\" title=\"$img\" />"; // comment out this line if you are using the above foreach loop
copy($pathparts['dirname'].'/'.$img, $imagedir.'/'.$img);
// Comment out this line if you are using the above foreach loop.
$page->images[] = "<img src=\"$imagelink/$img\" title=\"$img\" />";
}
for($i = 0; $i < count($matches[1]); $i++) { // go through all of our div matches
$class = isolate_class($matches[1][$i]); // first step in isolating the class
// check for any static classes
for ($i = 0; $i < count($matches[1]); $i++) { // Go through all of our div matches.
$class = isolate_class($matches[1][$i]); // First step in isolating the class.
// Check for any static classes.
switch ($class) {
case 'T': // class T is used for Titles
case 'T': // Class T is used for Titles.
$page->title = $matches[3][$i];
break;
case 'B': // I would guess that all bullet lists would start with B then go to B1, B2, etc
case 'B1': // B1-B4 are just insurance, should just hit B and all be taken care of
// I would guess that all bullet lists would start with B then go to B1, B2, etc.
case 'B':
// B1-B4 are just insurance, should just hit B and all be taken care of.
case 'B1':
case 'B2':
case 'B3':
case 'B4':
$page->contents[] = build_list('<ul>', $i, 0); // this is a recursive function that will grab all the bullets and rebuild the list in html
// This is a recursive function that will grab all the bullets and rebuild the list in html.
$page->contents[] = build_list('<ul>', $i, 0);
break;
default:
if ($matches[3][$i] != '&#13;') { // odd crap generated... sigh
if (substr($matches[3][$i], 0, 1) == ':') { // check for leading : ... hate MS ...
$page->contents[] = substr($matches[3][$i], 1); // get rid of :
if ($matches[3][$i] != '&#13;') { // Odd crap generated... sigh.
if (substr($matches[3][$i], 0, 1) == ':') {// Check for leading : ..hate MS .
$page->contents[] = substr($matches[3][$i], 1); // Get rid of :.
} else {
$page->contents[] = $matches[3][$i];
}
@ -284,94 +310,89 @@ function extract_data($pages, $courseid, $lessonname, $modname) {
}
}
// add the page to the array;
// Add the page to the array.
$extratedpages[] = $page;
} // end $pages foreach loop
} // End $pages foreach loop.
return $extratedpages;
}
/**
A recursive function to build a html list
*/
// A recursive function to build a html list.
function build_list($list, &$i, $depth) {
global $matches; // not sure why I global this...
while($i < count($matches[1])) {
global $matches; // Not sure why I global this...
while ($i < count($matches[1])) {
$class = isolate_class($matches[1][$i]);
if (strstr($class, 'B')) { // make sure we are still working with bullet classes
if (strstr($class, 'B')) { // Make sure we are still working with bullet classes.
if ($class == 'B') {
$this_depth = 0; // calling class B depth 0
$thisdepth = 0; // Calling class B depth 0.
} else {
// set the depth number. So B1 is depth 1 and B2 is depth 2 and so on
$this_depth = substr($class, 1);
if (!is_numeric($this_depth)) {
print_error( 'Depth not parsed!');
}
}
if ($this_depth < $depth) {
// we are moving back a level in the nesting
// Set the depth number. So B1 is depth 1 and B2 is depth 2 and so on.
$thisdepth = substr($class, 1);
if (!is_numeric($thisdepth)) {
print_error( 'Depth not parsed!');
}
if ($thisdepth < $depth) {
// We are moving back a level in the nesting.
break;
}
if ($this_depth > $depth) {
// we are moving in a lvl in nesting
if ($thisdepth > $depth) {
// We are moving in a lvl in nesting.
$list .= '<ul>';
$list = build_list($list, $i, $this_depth);
// once we return back, should go to the start of the while
$list = build_list($list, $i, $thisdepth);
// Once we return back, should go to the start of the while.
continue;
}
// no depth changes, so add the match to our list
// No depth changes, so add the match to our list.
if ($cleanstring = ppt_clean_text($matches[3][$i])) {
$list .= '<li>'.ppt_clean_text($matches[3][$i]).'</li>';
}
$i++;
} else {
// not a B class, so get out of here...
// Not a B class, so get out of here...
break;
}
}
// end the list and return it
// End the list and return it.
$list .= '</ul>';
return $list;
}
/**
Given an html tag, this function will
*/
// Given an html tag, this function will.
function isolate_class($string) {
if($class = strstr($string, 'class=')) { // first step in isolating the class
$class = substr($class, strpos($class, '=')+1); // this gets rid of <div blawblaw class= there are no "" or '' around the class name ...sigh...
if ($class = strstr($string, 'class=')) {
// First step in isolating the class.
// This gets rid of <div blawblaw class= there are no "" or '' around the clas name ...sigh...
$class = substr($class, strpos($class, '=') + 1);
if (strstr($class, ' ')) {
// spaces found, so cut off everything off after the first space
// Spaces found, so cut off everything off after the first space.
return substr($class, 0, strpos($class, ' '));
} else {
// no spaces so nothing else in the div tag, cut off the >
// No spaces so nothing else in the div tag, cut off the >.
return substr($class, 0, strpos($class, '>'));
}
} else {
// no class defined in the tag
// No class defined in the tag.
return '';
}
}
/**
This function strips off the random chars that ppt puts infront of bullet lists
*/
// This function strips off the random chars that ppt puts infront of bullet lists.
function ppt_clean_text($string) {
$chop = 1; // default: just a single char infront of the content
// look for any other crazy things that may be infront of the content
if (strstr($string, '&lt;') and strpos($string, '&lt;') == 0) { // look for the &lt; in the sting and make sure it is in the front
$chop = 4; // increase the $chop
$chop = 1; // Default: just a single char infront of the content.
// Look for any other crazy things that may be infront of the content.
if (strstr($string, '&lt;') and strpos($string, '&lt;') == 0) {
// Look for the &lt; in the sting and make sure it is in the front.
$chop = 4; // Increase the $chop.
}
// may need to add more later....
// May need to add more later....
$string = substr($string, $chop);
if ($string != '&#13;') {
return $string;
} else {
@ -379,41 +400,36 @@ function ppt_clean_text($string) {
}
}
/**
Clean up the temp directory
*/
// Clean up the temp directory.
function clean_temp() {
global $CFG;
// this function is broken, use it to clean up later
// should only clean up what we made as well because someone else could be importing ppt as well
//delDirContents($CFG->dataroot.'/temp/lesson');
/* this function is broken, use it to clean up later
* should only clean up what we made as well because someone else could be importing ppt as well
* delDirContents($CFG->dataroot.'/temp/lesson');
*/
}
/**
Creates objects an chapter object that is to be inserted into the database
*/
// Creates objects an chapter object that is to be inserted into the database.
function book_create_objects($pageobjects, $bookid) {
$chapters = array();
$chapter = new stdClass;
// same for all chapters
// Same for all chapters.
$chapter->bookid = $bookid;
$chapter->pagenum = $DB->count_records('book_chapters', array( 'bookid' => $bookid))+1;
$chapter->pagenum = $DB->count_records('book_chapters', array( 'bookid' => $bookid)) + 1;
$chapter->timecreated = time();
$chapter->timemodified = time();
$chapter->subchapter = 0;
$i = 1;
$i = 1;
foreach ($pageobjects as $pageobject) {
$page = prep_page($pageobject, $i); // get title and contents
$chapter->importsrc = addslashes($pageobject->source); // add the source
$page = prep_page($pageobject, $i); // Get title and contents.
$chapter->importsrc = addslashes($pageobject->source); // Add the source.
$chapter->title = $page->title;
$chapter->content = $page->contents;
$chapters[] = $chapter;
// increment our page number and our counter
$chapters[] = $chapter;
// Increment our page number and our counter.
$chapter->pagenum = $chapter->pagenum + 1;
$i++;
}
@ -421,44 +437,40 @@ function book_create_objects($pageobjects, $bookid) {
return $chapters;
}
/**
Builds the title and content strings from an object
*/
// Builds the title and content strings from an object.
function prep_page($pageobject, $count) {
if ($pageobject->title == '') {
$page->title = "Page $count"; // no title set so make a generic one
$page->title = "Page $count"; // No title set so make a generic one.
} else {
$page->title = addslashes($pageobject->title);
$page->title = addslashes($pageobject->title);
}
$page->contents = '';
// nab all the images first
// Nab all the images first.
foreach ($pageobject->images as $image) {
$image = str_replace("\n", '', $image);
$image = str_replace("\r", '', $image);
$image = str_replace("'", '"', $image); // imgstyle
$image = str_replace("'", '"', $image); // Imgstyle.
$page->contents .= addslashes($image);
}
// go through the contents array and put <p> tags around each element and strip out \n which I have found to be uneccessary
// Go through the contents array and put <p> tags around each element and strip out \n which I have found to be uneccessary.
foreach ($pageobject->contents as $content) {
$content = str_replace("\n", '', $content);
$content = str_replace("\r", '', $content);
$content = str_replace('&#13;', '', $content); // puts in returns?
$content = str_replace('&#13;', '', $content); // Puts in returns?
$content = '<p>'.$content.'</p>';
$page->contents .= addslashes($content);
}
return $page;
}
/**
Save the chapter objects to the database
*/
// Save the chapter objects to the database.
function book_save_objects($chapters, $bookid, $pageid='0') {
global $DB;
// nothing fancy, just save them all in order
// Nothing fancy, just save them all in order.
foreach ($chapters as $chapter) {
if (!$chapter->id = $DB->insert_record('book_chapters', $chapter)) {
print_error('Could not update your book');

774
bookquiz/play.php

@ -1,382 +1,392 @@
<?php // $Id: play.php,v 1.8 2012/07/25 22:46:42 bdaloukas Exp $
function game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $chapterid, $context)
{
if( $attempt != false and $bookquiz != false){
return game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context);
}
if( $attempt == false){
$attempt = game_addattempt( $game);
}
$bookquiz = new stdClass();
$bookquiz->lastchapterid = 0;
$bookquiz->id = $attempt->id;
$bookquiz->bookid = $game->bookid;
if( !game_insert_record( 'game_bookquiz', $bookquiz)){
print_error( 'game_bookquiz_continue: error inserting in game_bookquiz');
}
return game_bookquiz_play( $id, $game, $attempt, $bookquiz, 0, $context);
}
function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context)
{
global $DB, $OUTPUT, $cm;
if( $bookquiz->lastchapterid == 0){
game_bookquiz_play_computelastchapter( $game, $bookquiz);
if( $bookquiz->lastchapterid == 0){
print_error( get_string( 'bookquiz_empty', 'game'));
}
}
if( $chapterid == 0){
$chapterid = $bookquiz->lastchapterid;
}else
{
if( ($DB->set_field( 'game_bookquiz', 'lastchapterid', $chapterid, array( 'id' => $bookquiz->id))) == false){
print_error( "Can't update table game_bookquiz with lastchapterid to $chapterid");
}
}
$book = $DB->get_record( 'book', array('id' => $game->bookid));
if( !$chapter = $DB->get_record( 'book_chapters', array('id' => $chapterid))){
print_error('Error reading book chapters.');
}
$select = "bookid = $game->bookid AND hidden = 0";
$chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden');
$okchapters = array();
if( ($recs = $DB->get_records( 'game_bookquiz_chapters', array( 'attemptid' => $attempt->id))) != false){
foreach( $recs as $rec){
//1 means correct answer
$okchapters[ $rec->chapterid] = 1;
}
}
//2 means current
//$okchapters[ $chapterid] = 2;
$showquestions = false;
$a = array( 'gameid' => $game->id, 'chapterid' => $chapterid);
if( ($questions = $DB->get_records( 'game_bookquiz_questions', $a)) === false){
if( !array_key_exists( $chapterid, $okchapters)){
$okchapters[ $chapterid] = 1;
$newrec = new stdClass();
$newrec->attemptid = $attempt->id;
$newrec->chapterid = $chapterid;
if( !$DB->insert_record( 'game_bookquiz_chapters', $newrec)){
print_error( "Can't insert to table game_bookquiz_chapters");
}
}
}else
{
//Have to select random one question
$questionid = game_bookquiz_selectrandomquestion( $questions);
if( $questionid != 0){
$showquestions = true;
}
}
/// prepare chapter navigation icons
$previd = null;
$nextid = null;
$found = 0;
$scoreattempt = 0;
$lastid = 0;
foreach ($chapters as $ch) {
$scoreattempt++;
if ($found) {
$nextid= $ch->id;
break;
}
if ($ch->id == $chapter->id) {
$found = 1;
}
if (!$found) {
$previd = $ch->id;
}
$lastid = $ch->id;
}
if ($ch == current($chapters)) {
$nextid = $ch->id;
}
if( count( $chapters)){
$scoreattempt = ($scoreattempt-1) / count( $chapters);
}
$chnavigation = '';
if ($previd) {
$chnavigation .= '<a title="'.get_string('navprev', 'book').'" href="attempt.php?id='.$id.'&chapterid='.$previd.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_prev', 'mod_game').'" class="bigicon" alt="'.get_string('navprev', 'book').'"/></a>';
} else {
$chnavigation .= '<img src="'.$OUTPUT->pix_url('bookquiz/nav_prev_dis', 'mod_game').'" class="bigicon" alt="" />';
}
$nextbutton = '';
if ($nextid) {
if( !$showquestions){
$chnavigation .= '<a title="'.get_string('navnext', 'book').'" href="attempt.php?id='.$id.'&chapterid='.$nextid.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_next', 'mod_game').'" class="bigicon" alt="'.get_string('navnext', 'book').'" ></a>';
$nextbutton = '<center>';
$nextbutton .= '<form name="form" method="get" action="attempt.php">';
$nextbutton .= '<input type="hidden" name="id" value="'.$id.'" >'."\r\n";
$nextbutton .= '<input type="hidden" name="chapterid" value="'.$nextid.'" >'."\r\n";
$nextbutton .= '<input type="submit" value="'.get_string( 'continue').'">';
$nextbutton .= '</center>';
$showquestions = false;
game_updateattempts_maxgrade( $game, $attempt, $scoreattempt, 0);
}
} else {
game_updateattempts_maxgrade( $game, $attempt, 1, 0);
$sec = '';
if( !isset( $cm))
{
$cm = get_coursemodule_from_instance('game', $game->id, $game->course);
}
if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) {
$sec = $section->section;
}
if (! $cm = $DB->get_record('course_modules', array( 'id' => $id))) {
print_error("Course Module ID was incorrect id=$id");
}
$chnavigation .= '<a title="'.get_string('navexit', 'book').'" href="attempt.php?id='.$id.'&chapterid='.$lastid.'><img src="'.$OUTPUT->pix_url('bookquiz/nav_exit', 'mod_game').'" class="bigicon" alt="'.get_string('navexit', 'book').'" /></a>';
}
require( 'toc.php');
$tocwidth = '10%';
if( $showquestions){
if( $game->param3 == 0)
game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context);
}
?>
<table border="0" cellspacing="0" width="100%" valign="top" cellpadding="2">
<!-- subchapter title and upper navigation row //-->
<tr>
<td width="<?php echo 10;?>" valign="bottom">
</td>
<td valign="top">
<table border="0" cellspacing="0" width="100%" valign="top" cellpadding="0">
<tr>
<td align="right"><?php echo $chnavigation ?></td>
</tr>
</table>
</td>
</tr>
<!-- toc and chapter row //-->
<tr>
<td width="<?php echo $tocwidth ?>" valign="top" align="left">
<?php
echo $OUTPUT->box_start('generalbox');
echo $toc;
echo $OUTPUT->box_end();
?>
</td>
<td valign="top" align="left">
<?php
echo $OUTPUT->box_start('generalbox');
$content = '';
if (!$book->customtitles) {
if ($currsubtitle == '&nbsp;') {
$content .= '<p class="book_chapter_title">'.$currtitle.'</p>';
} else {
$content .= '<p class="book_chapter_title">'.$currtitle.'<br />'.$currsubtitle.'</p>';
}
}
$cmbook = get_coursemodule_from_instance( 'book', $game->bookid, $game->course);
$modcontext = game_get_context_module_instance( $cmbook->id);
$content .= game_filterbook( $chapter->content, $chapter->id, $modcontext->id, $game->course);
$nocleanoption = new object();
$nocleanoption->noclean = true;
echo '<div>';
if( $nextbutton != ''){
echo $nextbutton;
}
echo format_text($content, FORMAT_HTML, $nocleanoption);
if( $nextbutton != ''){
echo $nextbutton;
}
echo '</div>';
echo $OUTPUT->box_end();
/// lower navigation
echo '<p align="right">'.$chnavigation.'</p>';
?>
</td>
</tr>
</table>
<?php
if( $showquestions){
if( $game->param3 != 0)
game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context);
}
}
function game_bookquiz_play_computelastchapter( $game, &$bookquiz)
{
global $DB;
if( $game->bookid == 0)
{
print_error( 'Not defined a book on this game');
}
$pagenum = $DB->get_field( 'book_chapters', 'min(pagenum) as p', array('bookid' => $game->bookid));
if( $pagenum){
$bookquiz->lastchapterid = $DB->get_field( 'book_chapters', 'id', array('bookid' => $game->bookid, 'pagenum' => $pagenum));
if( $bookquiz->lastchapterid){
//update the data in table game_bookquiz
if( ($DB->set_field( 'game_bookquiz', 'lastchapterid', $bookquiz->lastchapterid, array('id' => $bookquiz->id))) == false){
print_error( "Can't update table game_bookquiz with lastchapterid to $bookquiz->lastchapterid");
}
}
}
}
function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapterid, $scoreattempt, $game, $context)
{
$onlyshow = false;
$showsolution = false;
$questionlist = $questionid;
$questions = game_sudoku_getquestions( $questionlist);
global $CFG;
/// Start the form
echo "<form id=\"responseform\" method=\"post\" action=\"{$CFG->wwwroot}/mod/game/attempt.php\" onclick=\"this.autocomplete='off'\">\n";
if( ($onlyshow === false) and ($showsolution === false)){
echo "<center><input type=\"submit\" name=\"finishattempt\" value=\"".get_string('sudoku_submit', 'game')."\"></center>\n";
}
// Add a hidden field with the quiz id
echo '<div>';
echo '<input type="hidden" name="id" value="' . s($id) . "\" />\n";
echo '<input type="hidden" name="action" value="bookquizcheck" />';
echo '<input type="hidden" name="chapterid" value="'.$chapterid.'" />';
echo '<input type="hidden" name="scoreattempt" value="'.$scoreattempt.'" />';
echo '<input type="hidden" name="nextchapterid" value="'.$nextchapterid.'" />';
/// Print all the questions
// Add a hidden field with questionids
echo '<input type="hidden" name="questionids" value="'.$questionlist."\" />\n";
$number=0;
foreach ($questions as $question) {
game_print_question( $game, $question, $context);
}
echo "</div>";
// Finish the form
echo '</div>';
if( ($onlyshow === false) and ($showsolution === false)){
echo "<center><input type=\"submit\" name=\"finishattempt\" value=\"".get_string('sudoku_submit', 'game')."\"></center>\n";
}
echo "</form>\n";
}
function game_bookquiz_selectrandomquestion( $questions)
{
global $DB;
$categorylist = '';
if( $questions == false){
return 0;
}
foreach( $questions as $rec){
$categorylist .= ',' . $rec->questioncategoryid;
}
$select = 'category in ('.substr( $categorylist, 1). ") AND qtype in ('shortanswer', 'truefalse', 'multichoice')";
if( ($recs = $DB->get_records_select( 'question', $select, null, '', 'id,id')) == false){
return 0;
}
$a = array();
foreach( $recs as $rec){
$a[ $rec->id] = $rec->id;
}
if( count( $a) == 0){
return 0;
}else
{
return array_rand( $a);
}
}
function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $context)
{
global $USER, $DB;
$scoreattempt = optional_param('scoreattempt', 0, PARAM_INT);
$responses = data_submitted();
$questionlist = $responses->questionids;
$questions = game_sudoku_getquestions( $questionlist);
$grades = game_grade_questions( $questions);
$scorequestion = 0;
$scoreattempt = 0;
$chapterid = required_param('chapterid', PARAM_INT);
$nextchapterid = required_param('nextchapterid', PARAM_INT);
foreach($questions as $question) {
if( !array_key_exists( $question->id, $grades)){
//no answered
continue;
}
$grade = $grades[ $question->id];
if( $grade->grade < 0.99){
continue;
}
//found one correct answer
if( !$DB->get_field( 'game_bookquiz_chapters', 'id', array( 'attemptid' => $attempt->id, 'chapterid' => $chapterid)))
{
$newrec = new stdClass();
$newrec->attemptid = $attempt->id;
$newrec->chapterid = $chapterid;
if( !$DB->insert_record( 'game_bookquiz_chapters', $newrec, false)){
print_object( $newrec);
print_error( "Can't insert to table game_bookquiz_chapters");
}
}
//Have to go to next page.
$bookquiz->lastchapterid = $nextchapterid;
$scorequestion = 1;
break;
}
$query = new stdClass();
$query->id = 0;
$query->attemptid = $attempt->id;
$query->gameid = $game->id;
$query->userid = $USER->id;
$query->sourcemodule = 'question';
$query->questionid = $question->id;
$query->glossaryentryid = 0;
$query->questiontext = $question->questiontext;
$query->timelastattempt = time();
game_update_queries( $game, $attempt, $query, $scorequestion, '');
game_updateattempts( $game, $attempt, $scoreattempt, 0);
game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $bookquiz->lastchapterid, $context);
}
<?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/>.
function game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $chapterid, $context) {
if ($attempt != false and $bookquiz != false) {
return game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context);
}
if ($attempt == false) {
$attempt = game_addattempt( $game);
}
$bookquiz = new stdClass();
$bookquiz->lastchapterid = 0;
$bookquiz->id = $attempt->id;
$bookquiz->bookid = $game->bookid;
if ( !game_insert_record( 'game_bookquiz', $bookquiz)) {
print_error( 'game_bookquiz_continue: error inserting in game_bookquiz');
}
return game_bookquiz_play( $id, $game, $attempt, $bookquiz, 0, $context);
}
function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context) {
global $DB, $OUTPUT, $cm;
if ($bookquiz->lastchapterid == 0) {
game_bookquiz_play_computelastchapter( $game, $bookquiz);
if ($bookquiz->lastchapterid == 0) {
print_error( get_string( 'bookquiz_empty', 'game'));
}
}
if ($chapterid == 0) {
$chapterid = $bookquiz->lastchapterid;
} else {
if (($DB->set_field( 'game_bookquiz', 'lastchapterid', $chapterid, array( 'id' => $bookquiz->id))) == false) {
print_error( "Can't update table game_bookquiz with lastchapterid to $chapterid");
}
}
$book = $DB->get_record( 'book', array('id' => $game->bookid));
if (!$chapter = $DB->get_record( 'book_chapters', array('id' => $chapterid))) {
print_error('Error reading book chapters.');
}
$select = "bookid = $game->bookid AND hidden = 0";
$chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden');
$okchapters = array();
if (($recs = $DB->get_records( 'game_bookquiz_chapters', array( 'attemptid' => $attempt->id))) != false) {
foreach ($recs as $rec) {
// The 1 means correct answer.
$okchapters[ $rec->chapterid] = 1;
}
}
// The 2 means current.
$showquestions = false;
$a = array( 'gameid' => $game->id, 'chapterid' => $chapterid);
if (($questions = $DB->get_records( 'game_bookquiz_questions', $a)) === false) {
if (!array_key_exists( $chapterid, $okchapters)) {
$okchapters[ $chapterid] = 1;
$newrec = new stdClass();
$newrec->attemptid = $attempt->id;
$newrec->chapterid = $chapterid;
if (!$DB->insert_record( 'game_bookquiz_chapters', $newrec)) {
print_error( "Can't insert to table game_bookquiz_chapters");
}
}
} else {
// Have to select random one question.
$questionid = game_bookquiz_selectrandomquestion( $questions);
if ($questionid != 0) {
$showquestions = true;
}
}
// Prepare chapter navigation icons.
$previd = null;
$nextid = null;
$found = 0;
$scoreattempt = 0;
$lastid = 0;
foreach ($chapters as $ch) {
$scoreattempt++;
if ($found) {
$nextid = $ch->id;
break;
}
if ($ch->id == $chapter->id) {
$found = 1;
}
if (!$found) {
$previd = $ch->id;
}
$lastid = $ch->id;
}
if ($ch == current($chapters)) {
$nextid = $ch->id;
}
if (count( $chapters)) {
$scoreattempt = ($scoreattempt - 1) / count( $chapters);
}
$chnavigation = '';
if ($previd) {
$chnavigation .= '<a title="'.get_string('navprev', 'book').'" href="attempt.php?id='.$id.
'&chapterid='.$previd.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_prev', 'mod_game').
'" class="bigicon" alt="'.get_string('navprev', 'book').'"/></a>';
} else {
$chnavigation .= '<img src="'.$OUTPUT->pix_url('bookquiz/nav_prev_dis', 'mod_game').'" class="bigicon" alt="" />';
}
$nextbutton = '';
if ($nextid) {
if (!$showquestions) {
$chnavigation .= '<a title="'.get_string('navnext', 'book').'" href="attempt.php?id='.
$id.'&chapterid='.$nextid.'"><img src="'.
$OUTPUT->pix_url('bookquiz/nav_next', 'mod_game').'" class="bigicon" alt="'.get_string('navnext', 'book').'" ></a>';
$nextbutton = '<center>';
$nextbutton .= '<form name="form" method="get" action="attempt.php">';
$nextbutton .= '<input type="hidden" name="id" value="'.$id.'" >'."\r\n";
$nextbutton .= '<input type="hidden" name="chapterid" value="'.$nextid.'" >'."\r\n";
$nextbutton .= '<input type="submit" value="'.get_string( 'continue').'">';
$nextbutton .= '</center>';
$showquestions = false;
game_updateattempts_maxgrade( $game, $attempt, $scoreattempt, 0);
}
} else {
game_updateattempts_maxgrade( $game, $attempt, 1, 0);
$sec = '';
if (!isset( $cm)) {
$cm = get_coursemodule_from_instance('game', $game->id, $game->course);
}
if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) {
$sec = $section->section;
}
if (! $cm = $DB->get_record('course_modules', array( 'id' => $id))) {
print_error("Course Module ID was incorrect id=$id");
}
$chnavigation .= '<a title="'.get_string('navexit', 'book').'" href="attempt.php?id='.
$id.'&chapterid='.$lastid.'><img src="'.$OUTPUT->pix_url('bookquiz/nav_exit', 'mod_game').
'" class="bigicon" alt="'.get_string('navexit', 'book').'" /></a>';
}
require( 'toc.php');
$tocwidth = '10%';
if ($showquestions) {
if ($game->param3 == 0) {
game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context);
}
}
?>
<table border="0" cellspacing="0" width="100%" valign="top" cellpadding="2">
<!-- subchapter title and upper navigation row //-->
<tr>
<td width="<?php echo 10;?>" valign="bottom">
</td>
<td valign="top">
<table border="0" cellspacing="0" width="100%" valign="top" cellpadding="0">
<tr>
<td align="right"><?php echo $chnavigation ?></td>
</tr>
</table>
</td>
</tr>
<!-- toc and chapter row //-->
<tr>
<td width="<?php echo $tocwidth ?>" valign="top" align="left">
<?php
echo $OUTPUT->box_start('generalbox');
echo $toc;
echo $OUTPUT->box_end();
?>
</td>
<td valign="top" align="left">
<?php
echo $OUTPUT->box_start('generalbox');
$content = '';
if (!$book->customtitles) {
if ($currsubtitle == '&nbsp;') {
$content .= '<p class="book_chapter_title">'.$currtitle.'</p>';
} else {
$content .= '<p class="book_chapter_title">'.$currtitle.'<br />'.$currsubtitle.'</p>';
}
}
$cmbook = get_coursemodule_from_instance( 'book', $game->bookid, $game->course);
$modcontext = game_get_context_module_instance( $cmbook->id);
$content .= game_filterbook( $chapter->content, $chapter->id, $modcontext->id, $game->course);
$nocleanoption = new object();
$nocleanoption->noclean = true;
echo '<div>';
if ($nextbutton != '') {
echo $nextbutton;
}
echo format_text($content, FORMAT_HTML, $nocleanoption);
if ($nextbutton != '') {
echo $nextbutton;
}
echo '</div>';
echo $OUTPUT->box_end();
// Lower navigation.
echo '<p align="right">'.$chnavigation.'</p>';
?>
</td>
</tr>
</table>
<?php
if ($showquestions) {
if ($game->param3 != 0) {
game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context);
}
}
}
function game_bookquiz_play_computelastchapter( $game, &$bookquiz) {
global $DB;
if ($game->bookid == 0) {
print_error( 'Not defined a book on this game');
}
$pagenum = $DB->get_field( 'book_chapters', 'min(pagenum) as p', array('bookid' => $game->bookid));
if ($pagenum) {
$bookquiz->lastchapterid = $DB->get_field( 'book_chapters', 'id', array('bookid' => $game->bookid, 'pagenum' => $pagenum));
if ($bookquiz->lastchapterid) {
// Update the data in table game_bookquiz.
if (($DB->set_field( 'game_bookquiz', 'lastchapterid', $bookquiz->lastchapterid,
array('id' => $bookquiz->id))) == false) {
print_error( "Can't update table game_bookquiz with lastchapterid to $bookquiz->lastchapterid");
}
}
}
}
function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapterid, $scoreattempt, $game, $context) {
$onlyshow = false;
$showsolution = false;
$questionlist = $questionid;
$questions = game_sudoku_getquestions( $questionlist);
global $CFG;
// Start the form.
echo "<form id=\"responseform\" method=\"post\" action=\"{$CFG->wwwroot}/mod/game/attempt.php\" ".
" onclick=\"this.autocomplete='off'\">\n";
if (($onlyshow === false) and ($showsolution === false)) {
echo "<center><input type=\"submit\" name=\"finishattempt\" value=\"".get_string('sudoku_submit', 'game')."\"></center>\n";
}
// Add a hidden field with the quiz id.
echo '<div>';
echo '<input type="hidden" name="id" value="' . s($id) . "\" />\n";
echo '<input type="hidden" name="action" value="bookquizcheck" />';
echo '<input type="hidden" name="chapterid" value="'.$chapterid.'" />';
echo '<input type="hidden" name="scoreattempt" value="'.$scoreattempt.'" />';
echo '<input type="hidden" name="nextchapterid" value="'.$nextchapterid.'" />';
// Print all the questions.
// Add a hidden field with questionids.
echo '<input type="hidden" name="questionids" value="'.$questionlist."\" />\n";
$number = 0;
foreach ($questions as $question) {
game_print_question( $game, $question, $context);
}
echo "</div>";
// Finish the form.
echo '</div>';
if (($onlyshow === false) and ($showsolution === false)) {
echo "<center><input type=\"submit\" name=\"finishattempt\" value=\"".get_string('sudoku_submit', 'game')."\"></center>\n";
}
echo "</form>\n";
}
function game_bookquiz_selectrandomquestion( $questions) {
global $DB;
$categorylist = '';
if ($questions == false) {
return 0;
}
foreach ($questions as $rec) {
$categorylist .= ',' . $rec->questioncategoryid;
}
$select = 'category in ('.substr( $categorylist, 1). ") AND qtype in ('shortanswer', 'truefalse', 'multichoice')";
if (($recs = $DB->get_records_select( 'question', $select, null, '', 'id,id')) == false) {
return 0;
}
$a = array();
foreach ($recs as $rec) {
$a[ $rec->id] = $rec->id;
}
if (count( $a) == 0) {
return 0;
} else {
return array_rand( $a);
}
}
function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $context) {
global $USER, $DB;
$scoreattempt = optional_param('scoreattempt', 0, PARAM_INT);
$responses = data_submitted();
$questionlist = $responses->questionids;
$questions = game_sudoku_getquestions( $questionlist);
$grades = game_grade_questions( $questions);
$scorequestion = 0;
$scoreattempt = 0;
$chapterid = required_param('chapterid', PARAM_INT);
$nextchapterid = required_param('nextchapterid', PARAM_INT);
foreach ($questions as $question) {
if (!array_key_exists( $question->id, $grades)) {
// No answered.
continue;
}
$grade = $grades[ $question->id];
if ($grade->grade < 0.99) {
continue;
}
// Found one correct answer.
if (!$DB->get_field( 'game_bookquiz_chapters', 'id', array( 'attemptid' => $attempt->id, 'chapterid' => $chapterid))) {
$newrec = new stdClass();
$newrec->attemptid = $attempt->id;
$newrec->chapterid = $chapterid;
if (!$DB->insert_record( 'game_bookquiz_chapters', $newrec, false)) {
print_error( "Can't insert to table game_bookquiz_chapters");
}
}
// Have to go to next page.
$bookquiz->lastchapterid = $nextchapterid;
$scorequestion = 1;
break;
}
$query = new stdClass();
$query->id = 0;
$query->attemptid = $attempt->id;
$query->gameid = $game->id;
$query->userid = $USER->id;
$query->sourcemodule = 'question';
$query->questionid = $question->id;
$query->glossaryentryid = 0;
$query->questiontext = $question->questiontext;
$query->timelastattempt = time();
game_update_queries( $game, $attempt, $query, $scorequestion, '');
game_updateattempts( $game, $attempt, $scoreattempt, 0);
game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $bookquiz->lastchapterid, $context);
}

302
bookquiz/questions.php

@ -1,4 +1,19 @@
<?php // $Id: questions.php,v 1.6 2012/07/25 11:16:05 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/>.
/**
* The script supports book
*
@ -7,96 +22,91 @@
* @package game
**/
require_once("../../../config.php");
require_once( "../headergame.php");
require_once("../locallib.php");
require_once("../../../config.php");
require_once( "../headergame.php");
require_once("../locallib.php");
$attempt = game_getattempt( $game, $detail);
if ($game->bookid == 0) {
print_error( get_string( 'bookquiz_not_select_book', 'game'));
}
if ($form = data_submitted()) { // Filename.
$ids = explode( ',', $form->ids);
game_bookquiz_save( $game->id, $game->bookid, $ids, $form);
}
$attempt = game_getattempt( $game, $detail);
if( $game->bookid == 0){
print_error( get_string( 'bookquiz_not_select_book', 'game'));
// Print upload form.
$OUTPUT->heading( $course->fullname);
$select = "gameid={$game->id}";
$categories = array();
if (($recs = $DB->get_records_select( 'game_bookquiz_questions', $select, null, '', 'chapterid,questioncategoryid')) != false) {
foreach ($recs as $rec) {
$categories[ $rec->chapterid] = $rec->questioncategoryid;
}
}
$context = game_get_context_course_instance( $COURSE->id);
$select = " contextid in ($context->id)";
if ($form = data_submitted())
{ /// Filename
$ids = explode( ',', $form->ids);
game_bookquiz_save( $game->id, $game->bookid, $ids, $form);
//redirect("{$CFG->wwwroot}/mod/game/bookquiz/questions.php?id=$cm->id", '', 0);
$a = array();
if ($recs = $DB->get_records_select( 'question_categories', $select, null, 'id,name')) {
foreach ($recs as $rec) {
$s = $rec->name;
if (($count = $DB->count_records( 'question', array( 'category' => $rec->id))) != 0) {
$s .= " ($count)";
}
$a[ $rec->id] = $s;
}
}
/// Print upload form
$OUTPUT->heading( $course->fullname);
$select = "gameid={$game->id}";
$categories = array();
if( ($recs = $DB->get_records_select( 'game_bookquiz_questions', $select, null, '', 'chapterid,questioncategoryid')) != false){
foreach( $recs as $rec){
$categories[ $rec->chapterid] = $rec->questioncategoryid;
}
}
$context = game_get_context_course_instance( $COURSE->id);
$select = " contextid in ($context->id)";
$a = array();
if( $recs = $DB->get_records_select( 'question_categories', $select, null, 'id,name')){
foreach( $recs as $rec){
$s = $rec->name;
if( ($count = $DB->count_records( 'question', array( 'category' => $rec->id))) != 0){
$s .= " ($count)";
}
$a[ $rec->id] = $s;
}
$sql = "SELECT chapterid, COUNT(*) as c ".
"FROM {game_bookquiz_questions} gbq,{question} q ".
"WHERE gbq.questioncategoryid=q.category ".
"AND gameid=$game->id ".
"GROUP BY chapterid";
$numbers = array();
if (($recs = $DB->get_records_sql( $sql)) != false) {
foreach ($recs as $rec) {
$numbers[ $rec->chapterid] = $rec->c;
}
}
echo '<form name="form" method="post" action="questions.php">';
echo '<table border=1>';
echo '<tr>';
echo '<td><center>'.get_string( 'bookquiz_chapters', 'game').'</td>';
echo '<td><center>'.get_string( 'bookquiz_categories', 'game').'</td>';
echo '<td><center>'.get_string( 'bookquiz_numquestions', 'game').'</td>';
echo "</tr>\r\n";
$ids = '';
if (($recs = $DB->get_records( 'book_chapters', array('bookid' => $game->bookid), 'pagenum', 'id,title')) != false) {
foreach ($recs as $rec) {
echo '<tr>';
echo '<td>'.$rec->title.'</td>';
echo '<td>';
if (array_key_exists( $rec->id, $categories)) {
$categoryid = $categories[ $rec->id];
} else {
$categoryid = 0;
}
echo game_showselectcontrol( 'categoryid_'.$rec->id, $a, $categoryid, '');
echo '</td>';
echo '<td>';
if (array_key_exists( $rec->id, $numbers)) {
echo '<center>'.$numbers[ $rec->id].'</center>';
} else {
echo '&nbsp;';
}
$sql = "SELECT chapterid, COUNT(*) as c ".
"FROM {game_bookquiz_questions} gbq,{question} q ".
"WHERE gbq.questioncategoryid=q.category ".
"AND gameid=$game->id ".
"GROUP BY chapterid";
$numbers = array();
if( ($recs = $DB->get_records_sql( $sql)) != false){
foreach( $recs as $rec){
$numbers[ $rec->chapterid] = $rec->c;
}
}
echo '<form name="form" method="post" action="questions.php">';
echo '<table border=1>';
echo '<tr>';
echo '<td><center>'.get_string( 'bookquiz_chapters', 'game').'</td>';
echo '<td><center>'.get_string( 'bookquiz_categories', 'game').'</td>';
echo '<td><center>'.get_string( 'bookquiz_numquestions', 'game').'</td>';
echo "</tr>\r\n";
$ids = '';
if( ($recs =$DB->get_records( 'book_chapters', array('bookid' => $game->bookid), 'pagenum', 'id,title')) != false)
{
foreach( $recs as $rec){
echo '<tr>';
echo '<td>'.$rec->title.'</td>';
echo '<td>';
if( array_key_exists( $rec->id, $categories))
$categoryid = $categories[ $rec->id];
else
$categoryid = 0;
echo game_showselectcontrol( 'categoryid_'.$rec->id, $a, $categoryid, '');
echo '</td>';
echo '<td>';
if( array_key_exists( $rec->id, $numbers)){
echo '<center>'.$numbers[ $rec->id].'</center>';
}else
{
echo '&nbsp;';
}
echo '</td>';
echo "</tr>\r\n";
$ids .= ','.$rec->id;
}
}
echo '</td>';
echo "</tr>\r\n";
$ids .= ','.$rec->id;
}
}
?>
</table>
<br>
@ -111,70 +121,66 @@
</form>
<?php
echo $OUTPUT->footer($course);
echo $OUTPUT->footer($course);
function game_bookquiz_save( $gameid, $bookid, $ids, $form)
{
function game_bookquiz_save( $gameid, $bookid, $ids, $form) {
global $DB;
$questions = array();
$recids = array();
if( ($recs = $DB->get_records( 'game_bookquiz_questions', array( 'gameid' => $gameid), '', 'id,chapterid,questioncategoryid')) != false){
foreach( $recs as $rec){
$questions[ $rec->chapterid] = $rec->questioncategoryid;
$recids[ $rec->chapterid] = $rec->id;
}
}
foreach( $ids as $chapterid){
$name = 'categoryid_'.$chapterid;
$categoryid = $form->$name;
if( !array_key_exists( $chapterid, $questions)){
if( $categoryid == 0){
continue;
}
$rec = new stdClass();
$rec->gameid = $gameid;
$rec->chapterid = $chapterid;
$rec->questioncategoryid = $categoryid;
if (($newid=$DB->insert_record('game_bookquiz_questions', $rec)) == false) {
print_object( $rec);
print_error( "Can't insert to game_bookquiz_questions");
}
continue;
}
$cat = $questions[ $chapterid];
if( $cat == $categoryid){
$recids[ $chapterid] = 0;
continue;
}
if( $categoryid == 0){
if( !delete_records( 'game_bookquiz_questions', 'id', $recids[ $chapterid])){
print_error( "Can't delete game_bookquiz_questions");
}
}else
{
$updrec = new StdClass;
$updrec->id = $recids[ $chapterid];
$updrec->questioncategoryid = $categoryid;
if (($DB->update_record( 'game_bookquiz_questions', $updrec)) == false) {
print_object( $rec);
print_error( "Can't update game_bookquiz_questions");
}
}
$recids[ $chapterid] = 0;
}
foreach( $recids as $chapterid => $id){
if( $id == 0){
continue;
}
}
$questions = array();
$recids = array();
if (($recs = $DB->get_records( 'game_bookquiz_questions',
array( 'gameid' => $gameid), '', 'id,chapterid,questioncategoryid')) != false) {
foreach ($recs as $rec) {
$questions[ $rec->chapterid] = $rec->questioncategoryid;
$recids[ $rec->chapterid] = $rec->id;
}
}
foreach ($ids as $chapterid) {
$name = 'categoryid_'.$chapterid;
$categoryid = $form->$name;
if (!array_key_exists( $chapterid, $questions)) {
if ($categoryid == 0) {
continue;
}
$rec = new stdClass();
$rec->gameid = $gameid;
$rec->chapterid = $chapterid;
$rec->questioncategoryid = $categoryid;
if (($newid = $DB->insert_record('game_bookquiz_questions', $rec)) == false) {
print_error( "Can't insert to game_bookquiz_questions");
}
continue;
}
$cat = $questions[ $chapterid];
if ($cat == $categoryid) {
$recids[ $chapterid] = 0;
continue;
}
if ($categoryid == 0) {
if (!delete_records( 'game_bookquiz_questions', 'id', $recids[ $chapterid])) {
print_error( "Can't delete game_bookquiz_questions");
}
} else {
$updrec = new StdClass;
$updrec->id = $recids[ $chapterid];
$updrec->questioncategoryid = $categoryid;
if (($DB->update_record( 'game_bookquiz_questions', $updrec)) == false) {
print_error( "Can't update game_bookquiz_questions");
}
}
$recids[ $chapterid] = 0;
}
foreach ($recids as $chapterid => $id) {
if ($id == 0) {
continue;
}
}
}

110
bookquiz/toc.php

@ -1,33 +1,48 @@
<?PHP // $Id: toc.php,v 1.1 2008/03/26 17:40:38 arborrow 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/>.
defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
define('NUM_NONE', '0');
define('NUM_NUMBERS', '1');
define('NUM_BULLETS', '2');
define('NUM_INDENTED', '3');
/// included from mod/book/view.php and print.php
///
/// uses:
/// $chapters - all book chapters
/// $chapter - may be false
/// $cm - course module
/// $book - book
/// $edit - force editing view
/// fills:
/// $toc
/// $title (not for print)
/* Included from mod/book/view.php and print.php.
*
* uses:
* $chapters - all book chapters
* $chapter - may be false
* $cm - course module
* $book - book
* $edit - force editing view
*
* fills:
* $toc
* $title (not for print)
*/
$currtitle = ''; //active chapter title (plain text)
$currsubtitle = ''; //active subchapter if any
$currtitle = ''; // Active chapter title (plain text).
$currsubtitle = ''; // Active subchapter if any.
$prevtitle = '&nbsp;';
$toc = ''; //representation of toc (HTML)
$toc = ''; // Representation of toc (HTML).
$nch = 0; //chapter number
$ns = 0; //subchapter number
$nch = 0; // Chapter number.
$ns = 0; // Subchapter number.
$title = '';
$first = 1;
@ -36,22 +51,22 @@ if (!isset($print)) {
}
switch ($book->numbering) {
case NUM_NONE:
$toc .= '<div class="book_toc_none">';
break;
case NUM_NUMBERS:
$toc .= '<div class="book_toc_numbered">';
break;
case NUM_BULLETS:
$toc .= '<div class="book_toc_bullets">';
break;
case NUM_INDENTED:
$toc .= '<div class="book_toc_indented">';
break;
case NUM_NONE:
$toc .= '<div class="book_toc_none">';
break;
case NUM_NUMBERS:
$toc .= '<div class="book_toc_numbered">';
break;
case NUM_BULLETS:
$toc .= '<div class="book_toc_bullets">';
break;
case NUM_INDENTED:
$toc .= '<div class="book_toc_indented">';
break;
}
if ($print) { ///TOC for printing
if ($print) {
// TOC for printing.
$toc .= '<a name="toc"></a>';
if ($book->customtitles) {
$toc .= '<h1>'.get_string('toc', 'book').'</h1>';
@ -60,7 +75,7 @@ if ($print) { ///TOC for printing
}
$titles = array();
$toc .= '<ul>';
foreach($chapters as $ch) {
foreach ($chapters as $ch) {
$title = trim(strip_tags($ch->title));
if (!$ch->hidden) {
if (!$ch->subchapter) {
@ -68,13 +83,13 @@ if ($print) { ///TOC for printing
$ns = 0;
$toc .= ($first) ? '<li>' : '</ul></li><li>';
if ($book->numbering == NUM_NUMBERS) {
$title = "$nch $title";
$title = "$nch $title";
}
} else {
$ns++;
$toc .= ($first) ? '<li><ul><li>' : '<li>';
if ($book->numbering == NUM_NUMBERS) {
$title = "$nch.$ns $title";
$title = "$nch.$ns $title";
}
}
$titles[$ch->id] = $title;
@ -84,9 +99,10 @@ if ($print) { ///TOC for printing
}
}
$toc .= '</ul></li></ul>';
} else { //normal students view
} else {
// Normal students view.
$toc .= '<font size="-1"><ul>';
foreach($chapters as $ch) {
foreach ($chapters as $ch) {
$title = trim(strip_tags($ch->title));
if (!$ch->hidden) {
if (!$ch->subchapter) {
@ -96,7 +112,7 @@ if ($print) { ///TOC for printing
if ($book->numbering == NUM_NUMBERS) {
$title = "$nch $title";
}
$prevtitle = $title;
$prevtitle = $title;
} else {
$ns++;
$toc .= ($first) ? '<li><ul><li>' : '<li>';
@ -114,12 +130,12 @@ if ($print) { ///TOC for printing
$currsubtitle = '&nbsp;';
}
} else {
if( array_key_exists( $ch->id, $okchapters)){
$toc .= '<a title="'.htmlspecialchars($title).'" href="attempt.php?id='.$id.'&chapterid='.$ch->id.'">'.$title.'</a>';
}else
{
$toc .= htmlspecialchars($title);
}
if (array_key_exists( $ch->id, $okchapters)) {
$toc .= '<a title="'.htmlspecialchars($title).'" href="attempt.php?id='
$id.'&chapterid='.$ch->id.'">'.$title.'</a>';
} else {
$toc .= htmlspecialchars($title);
}
}
$toc .= (!$ch->subchapter) ? '<ul>' : '</li>';
$first = 0;
@ -130,6 +146,4 @@ if ($print) { ///TOC for printing
$toc .= '</div>';
$toc = str_replace('<ul></ul>', '', $toc); //cleanup of invalid structures
?>
$toc = str_replace('<ul></ul>', '', $toc); // Cleanup of invalid structures.

174
bookquiz/view.php

@ -1,20 +1,35 @@
<?PHP // $Id: view.php,v 1.5 2012/07/25 11:16:05 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('../../config.php');
require_once('lib.php');
$id = required_param('id', PARAM_INT); // Course Module ID
$chapterid = optional_param('chapterid', 0, PARAM_INT); // Chapter ID
$edit = optional_param('edit', -1, PARAM_BOOL); // Edit mode
$id = required_param('id', PARAM_INT); // Course Module ID.
$chapterid = optional_param('chapterid', 0, PARAM_INT); // Chapter ID.
$edit = optional_param('edit', -1, PARAM_BOOL); // Edit mode.
// =========================================================================
// security checks START - teachers edit; students view
// =========================================================================
/* =========================================================================
* security checks START - teachers edit; students view
* =========================================================================
*/
if (!$cm = get_coursemodule_from_id('book', $id)) {
print_error('Course Module ID was incorrect');
}
if (!$course = $DB->get_record('course', array( 'id'=> $cm->course))) {
if (!$course = $DB->get_record('course', array( 'id' => $cm->course))) {
print_error('Course is misconfigured');
}
@ -26,13 +41,14 @@ require_course_login($course, true, $cm);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
/// read chapters
// Read chapters.
$select = $allowedit ? "bookid = $book->id" : "bookid = $book->id AND hidden = 0";
$chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden');
/// check chapterid and read chapter data
if ($chapterid == '0') { // go to first chapter if no given
foreach($chapters as $ch) {
// Check chapterid and read chapter data.
if ($chapterid == '0') {
// Go to first chapter if no given.
foreach ($chapters as $ch) {
if ($allowedit) {
$chapterid = $ch->id;
break;
@ -44,55 +60,51 @@ if ($chapterid == '0') { // go to first chapter if no given
}
}
if (!$chapter = $DB->get_record('book_chapters', array('id' => $chapterid))) {
print_error('Error reading book chapters.');
}
//check all variables
// Check all variables.
unset($id);
unset($chapterid);
/// chapter is hidden for students
// Chapter is hidden for students.
if (!$allowedit && $chapter->hidden) {
print_error('Error reading book chapters.');
print_error('Error reading book chapters.');
}
/// chapter not part of this book!
// Chapter not part of this book!
if ($chapter->bookid != $book->id) {
print_error('Chapter not part of this book!');
print_error('Chapter not part of this book!');
}
// =========================================================================
// security checks END
// =========================================================================
/* =========================================================================
* security checks END
* =========================================================================
*/
add_to_log($course->id, 'book', 'view', 'view.php?id='.$cm->id.'&amp;chapterid='.$chapter->id, $book->id, $cm->id);
///read standard strings
// Read standard strings.
$strbooks = get_string('modulenameplural', 'book');
$strbook = get_string('modulename', 'book');
$strTOC = get_string('TOC', 'book');
/// prepare header
// Prepare header.
if ($course->category) {
$navigation = '<a href="../../course/view.php?id='.$course->id.'">'.$course->shortname.'</a> ->';
} else {
$navigation = '';
}
$buttons = $allowedit ? '<table cellspacing="0" cellpadding="0"><tr><td>'.update_module_button($cm->id, $course->id, $strbook).'</td>'.
'<td>&nbsp;</td><td>'.book_edit_button($cm->id, $course->id, $chapter->id).'</td></tr></table>'
: '&nbsp;';
$buttons = $allowedit ? '<table cellspacing="0" cellpadding="0"><tr><td>'.
update_module_button($cm->id, $course->id, $strbook).'</td>'.
'<td>&nbsp;</td><td>'.book_edit_button($cm->id, $course->id, $chapter->id).'</td></tr></table>' : '&nbsp;';
/// prepare chapter navigation icons
// Prepare chapter navigation icons.
$previd = null;
$nextid = null;
$found = 0;
foreach ($chapters as $ch) {
if ($found) {
$nextid= $ch->id;
$nextid = $ch->id;
break;
}
if ($ch->id == $chapter->id) {
@ -109,36 +121,51 @@ $chnavigation = '';
echo "previd=$previd nextid=$nextid<br>";
if ($previd) {
$chnavigation .= '<a title="'.get_string('navprev', 'book').'" href="view.php?id='.$cm->id.'&amp;chapterid='.$previd.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_prev', 'mod_game').'" class="bigicon" alt="'.get_string('navprev', 'book').'"/></a>';
$chnavigation .= '<a title="'.get_string('navprev', 'book').'" href="view.php?id='.$cm->id.
'&amp;chapterid='.$previd.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_prev', 'mod_game').
'" class="bigicon" alt="'.get_string('navprev', 'book').'"/></a>';
} else {
$chnavigation .= '<img src="'.$OUTPUT->pix_url('bookquiz/nav_prev_dis', 'mod_game').'" class="bigicon" alt="" />';
}
if ($nextid) {
$chnavigation .= '<a title="'.get_string('navnext', 'book').'" href="view.php?id='.$cm->id.'&amp;chapterid='.$nextid.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_next', 'mod_game').'" class="bigicon" alt="'.get_string('navnext', 'book').'" /></a>';
$chnavigation .= '<a title="'.get_string('navnext', 'book').'" href="view.php?id='.$cm->id.
'&amp;chapterid='.$nextid.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_next', 'mod_game').
'" class="bigicon" alt="'.get_string('navnext', 'book').'" /></a>';
} else {
$sec = '';
if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) {
$sec = $section->section;
}
$chnavigation .= '<a title="'.get_string('navexit', 'book').'" href="../../course/view.php?id='.$course->id.'#section-'.$sec.'"><img src="'.$OUTPUT->pix_url('bookquiz/nav_exit', 'mod_game').'" class="bigicon" alt="'.get_string('navexit', 'book').'" /></a>';
$chnavigation .= '<a title="'.get_string('navexit', 'book').'" href="../../course/view.php?id='.
$course->id.'#section-'.$sec.'"><img src="'.
$OUTPUT->pix_url('bookquiz/nav_exit', 'mod_game').'" class="bigicon" alt="'.get_string('navexit', 'book').
'" /></a>';
}
echo "chnavigation=$chnavigation<br>";
/// prepare print icons
// Prepare print icons.
if ($book->disableprinting) {
$printbook = '';
$printchapter = '';
} else {
$printbook = '<a title="'.get_string('printbook', 'book').'" href="print.php?id='.$cm->id.'" onclick="this.target=\'_blank\'"><img src="'.$OUTPUT->pix_url('bookquiz/print_book', 'mod_game').'" class="bigicon" alt="'.get_string('printbook', 'book').'"/></a>';
$printchapter = '<a title="'.get_string('printchapter', 'book').'" href="print.php?id='.$cm->id.'&amp;chapterid='.$chapter->id.'" onclick="this.target=\'_blank\'"><img src="'.$OUTPUT->pix_url('bookquiz/print_chapter', 'mod_game').'" class="bigicon" alt="'.get_string('printchapter', 'book').'"/></a>';
$printbook = '<a title="'.get_string('printbook', 'book').'" href="print.php?id='.$cm->id.
'" onclick="this.target=\'_blank\'"><img src="'.
$OUTPUT->pix_url('bookquiz/print_book', 'mod_game').
'" class="bigicon" alt="'.get_string('printbook', 'book').'"/></a>';
$printchapter = '<a title="'.get_string('printchapter', 'book').'" href="print.php?id='.
$cm->id.'&amp;chapterid='.$chapter->id.
'" onclick="this.target=\'_blank\'"><img src="'.
$OUTPUT->pix_url('bookquiz/print_chapter', 'mod_game').'" class="bigicon" alt="'.
get_string('printchapter', 'book').'"/></a>';
}
// =====================================================
// Book display HTML code
// =====================================================
/* =====================================================
* Book display HTML code
* =====================================================
*/
echo "OK";
?>
<table border="0" cellspacing="0" width="100%" valign="top" cellpadding="2">
@ -159,44 +186,43 @@ echo "OK";
<!-- toc and chapter row //-->
<tr>
<td width="<?php echo $tocwidth ?>" valign="top" align="left">
<?php
echo $OUTPUT->box_start('generalbox');
echo $toc;
echo $OUTPUT->box_end();
if ($allowedit && $edit) {
echo '<font size="1"><br />';
helpbutton('faq', get_string('faq','book'), 'book', true, true);
echo '</font>';
}
?>
<?php
echo $OUTPUT->box_start('generalbox');
echo $toc;
echo $OUTPUT->box_end();
if ($allowedit && $edit) {
echo '<font size="1"><br />';
helpbutton('faq', get_string('faq', 'book'), 'book', true, true);
echo '</font>';
}
?>
</td>
<td valign="top" align="right">
<?php
echo $OUTPUT->box_start('generalbox');
$content = '';
if (!$book->customtitles) {
if ($currsubtitle == '&nbsp;') {
$content .= '<p class="book_chapter_title">'.$currtitle.'</p>';
} else {
$content .= '<p class="book_chapter_title">'.$currtitle.'<br />'.$currsubtitle.'</p>';
}
}
$content .= $chapter->content;
$nocleanoption = new object();
$nocleanoption->noclean = true;
echo '<div class="book_content">';
echo format_text($content, FORMAT_HTML, $nocleanoption, $course->id);
echo '</div>';
echo $OUTPUT->box_end();
/// lower navigation
echo '<p>'.$chnavigation.'</p>';
?>
<?php
echo $OUTPUT->box_start('generalbox');
$content = '';
if (!$book->customtitles) {
if ($currsubtitle == '&nbsp;') {
$content .= '<p class="book_chapter_title">'.$currtitle.'</p>';
} else {
$content .= '<p class="book_chapter_title">'.$currtitle.'<br />'.$currsubtitle.'</p>';
}
}
$content .= $chapter->content;
$nocleanoption = new object();
$nocleanoption->noclean = true;
echo '<div class="book_content">';
echo format_text($content, FORMAT_HTML, $nocleanoption, $course->id);
echo '</div>';
echo $OUTPUT->box_end();
// Lower navigation.
echo '<p>'.$chnavigation.'</p>';
?>
</td>
</tr>
</table>
<?php
echo $OUTPUT->footer($course);
?>

Loading…
Cancel
Save