Browse Source

Fix:Coding style

MOODLE_20_STABLE
Vasilis Daloukas 9 years ago
parent
commit
0751505215
  1. 23
      backup/moodle2/backup_game_activity_task.class.php
  2. 8
      backup/moodle2/backup_game_settingslib.php
  3. 60
      backup/moodle2/backup_game_stepslib.php
  4. 106
      backup/moodle2/restore_game_activity_task.class.php
  5. 34
      backup/moodle2/restore_game_stepslib.php
  6. 573
      bookquiz/importodt.php
  7. 384
      bookquiz/importppt.php
  8. 230
      bookquiz/play.php
  9. 142
      bookquiz/questions.php
  10. 74
      bookquiz/toc.php
  11. 156
      bookquiz/view.php

23
backup/moodle2/backup_game_activity_task.class.php

@ -1,5 +1,4 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/ // This file is part of Moodle - http://moodle.org/
// //
// Moodle is free software: you can redistribute it and/or modify // Moodle is free software: you can redistribute it and/or modify
@ -24,8 +23,8 @@
* @package game * @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_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_settingslib.php'); // Because it exists (optional).
/** /**
* game backup task that provides all the settings and steps to perform one * game backup task that provides all the settings and steps to perform one
@ -37,14 +36,14 @@ class backup_game_activity_task extends backup_activity_task {
* Define (add) particular settings this activity can have * Define (add) particular settings this activity can have
*/ */
protected function define_my_settings() { 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 * Define (add) particular steps this activity can have
*/ */
protected function define_my_steps() { protected function define_my_steps() {
// Game only has one structure step // Game only has one structure step.
$this->add_step(new backup_game_activity_structure_step('game_structure', 'game.xml')); $this->add_step(new backup_game_activity_structure_step('game_structure', 'game.xml'));
} }
@ -55,15 +54,15 @@ class backup_game_activity_task extends backup_activity_task {
static public function encode_content_links($content) { static public function encode_content_links($content) {
global $CFG; global $CFG;
$base = preg_quote($CFG->wwwroot,"/"); $base = preg_quote($CFG->wwwroot, "/");
// Link to the list of gamess // Link to the list of games.
$search="/(".$base."\/mod\/game\/index.php\?id\=)([0-9]+)/"; $search = "/(".$base."\/mod\/game\/index.php\?id\=)([0-9]+)/";
$content= preg_replace($search, '$@GAMEINDEX*$2@$', $content); $content = preg_replace($search, '$@GAMEINDEX*$2@$', $content);
// Link to game view by moduleid // Link to game view by moduleid.
$search="/(".$base."\/mod\/game\/view.php\?id\=)([0-9]+)/"; $search = "/(".$base."\/mod\/game\/view.php\?id\=)([0-9]+)/";
$content= preg_replace($search, '$@GAMEVIEWBYID*$2@$', $content); $content = preg_replace($search, '$@GAMEVIEWBYID*$2@$', $content);
return $content; return $content;
} }

8
backup/moodle2/backup_game_settingslib.php

@ -1,5 +1,4 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/ // This file is part of Moodle - http://moodle.org/
// //
// Moodle is free software: you can redistribute it and/or modify // Moodle is free software: you can redistribute it and/or modify
@ -22,6 +21,7 @@
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/ */
// This activity has not particular settings but the inherited from the generic /** 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 * backup_activity_task so here there isn't any class definition, like the ones
// existing in /backup/moodle2/backup_settingslib.php (activities section) * existing in /backup/moodle2/backup_settingslib.php (activities section)
*/

60
backup/moodle2/backup_game_stepslib.php

@ -1,5 +1,4 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/ // This file is part of Moodle - http://moodle.org/
// //
// Moodle is free software: you can redistribute it and/or modify // Moodle is free software: you can redistribute it and/or modify
@ -33,10 +32,10 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
protected function define_structure() { protected function define_structure() {
// To know if we are including userinfo // To know if we are including userinfo.
$userinfo = $this->get_setting_value('userinfo'); $userinfo = $this->get_setting_value('userinfo');
// Define each element separated // Define each element separated.
$game = new backup_nested_element('game', array('id'), array( $game = new backup_nested_element('game', array('id'), array(
'name', 'sourcemodule', 'timeopen', 'timeclose', 'quizid', 'name', 'sourcemodule', 'timeopen', 'timeclose', 'quizid',
'glossaryid', 'glossarycategoryid', 'questioncategoryid', 'bookid', 'glossaryid', 'glossarycategoryid', 'questioncategoryid', 'bookid',
@ -54,7 +53,8 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$exportjavames = new backup_nested_element('game_export_javames'); $exportjavames = new backup_nested_element('game_export_javames');
$exportjavame = new backup_nested_element('game_export_javame', array('id'), array( $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'); $grades = new backup_nested_element('game_grades');
$grade = new backup_nested_element('game_grade', array('id'), array( $grade = new backup_nested_element('game_grade', array('id'), array(
@ -66,23 +66,23 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$attempts = new backup_nested_element('game_attempts'); $attempts = new backup_nested_element('game_attempts');
$attempt = new backup_nested_element('game_attempt', array('id'), array( $attempt = new backup_nested_element('game_attempt', array('id'), array(
'userid', 'timestart','timefinish', 'timelastattempt', 'lastip', 'userid', 'timestart', 'timefinish', 'timelastattempt', 'lastip',
'lastremotehost', 'preview', 'attempt','score', 'attempts', 'language')); 'lastremotehost', 'preview', 'attempt', 'score', 'attempts', 'language'));
$querys = new backup_nested_element('game_queries'); $querys = new backup_nested_element('game_queries');
$query = new backup_nested_element('game_query', array('id'), array( $query = new backup_nested_element('game_query', array('id'), array(
'gamekind', 'userid','sourcemodule', 'questionid', 'glossaryentryid', 'gamekind', 'userid', 'sourcemodule', 'questionid', 'glossaryentryid',
'questiontext', 'score', 'timelastattempt','studentanswer', 'col', 'row', 'questiontext', 'score', 'timelastattempt', 'studentanswer', 'col', 'row',
'horizontal', 'answertext', 'correct', 'attachment', 'answerid', 'tries')); '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 = new backup_nested_element('game_bookquiz', array('id'), array('lastchapterid'));
$bookquiz_chapters = new backup_nested_element('game_bookquiz_chapters'); $bookquizchapters = new backup_nested_element('game_bookquiz_chapters');
$bookquiz_chapter = new backup_nested_element('game_bookquiz_chapter', array('id'), array( 'chapterid')); $bookquizchapter = new backup_nested_element('game_bookquiz_chapter', array('id'), array( 'chapterid'));
$bookquiz_questions = new backup_nested_element('game_bookquiz_questions'); $bookquizquestions = new backup_nested_element('game_bookquiz_questions');
$bookquiz_question = new backup_nested_element('game_bookquiz_question', array('id'), array( $bookquizquestion = new backup_nested_element('game_bookquiz_question', array('id'), array(
'chapterid', 'questioncategoryid')); 'chapterid', 'questioncategoryid'));
$crosss = new backup_nested_element('game_crosss'); $crosss = new backup_nested_element('game_crosss');
@ -110,9 +110,9 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$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')); $sudoku = new backup_nested_element('game_sudoku', array('id'), array('level', 'data', 'opened', 'guess'));
// Build the tree // Build the tree.
$game->add_child($bookquiz_questions); $game->add_child( $bookquizquestions);
$bookquiz_questions->add_child($bookquiz_question); $bookquizquestions->add_child( $bookquizquestion);
$game->add_child( $exporthtmls); $game->add_child( $exporthtmls);
$exporthtmls->add_child( $exporthtml); $exporthtmls->add_child( $exporthtml);
@ -126,7 +126,7 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$game->add_child( $repetitions); $game->add_child( $repetitions);
$repetitions->add_child( $repetition); $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) { if ($userinfo) {
$game->add_child( $attempts); $game->add_child( $attempts);
$attempts->add_child( $attempt); $attempts->add_child( $attempt);
@ -137,8 +137,8 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$attempts->add_child( $bookquizs); $attempts->add_child( $bookquizs);
$bookquizs->add_child( $bookquiz); $bookquizs->add_child( $bookquiz);
$game->add_child($bookquiz_chapters); $game->add_child( $bookquizchapters);
$bookquiz_chapters->add_child($bookquiz_chapter); $bookquizchapters->add_child($bookquizchapter);
$attempts->add_child( $crosss); $attempts->add_child( $crosss);
$crosss->add_child( $cross); $crosss->add_child( $cross);
@ -162,13 +162,13 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$sudokus->add_child( $sudoku); $sudokus->add_child( $sudoku);
} }
// Define sources // Define sources.
$game->set_source_table('game', array('id' => backup::VAR_ACTIVITYID)); $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)); $exporthtml->set_source_table('game_export_html', array('id' => backup::VAR_ACTIVITYID));
$exportjavame->set_source_table('game_export_javame', 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) { if ($userinfo) {
$grade->set_source_table('game_grades', array('gameid' => backup::VAR_ACTIVITYID)); $grade->set_source_table('game_grades', array('gameid' => backup::VAR_ACTIVITYID));
$repetition->set_source_table('game_repetitions', array('gameid' => backup::VAR_ACTIVITYID)); $repetition->set_source_table('game_repetitions', array('gameid' => backup::VAR_ACTIVITYID));
@ -177,7 +177,7 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$attempt->set_source_table('game_queries', array( 'attemptid' => backup::VAR_PARENTID)); $attempt->set_source_table('game_queries', array( 'attemptid' => backup::VAR_PARENTID));
$bookquiz->set_source_table('game_bookquiz', array( 'id' => backup::VAR_ACTIVITYID)); $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)); $cross->set_source_table('game_cross', array( 'id' => backup::VAR_PARENTID));
$cryptex->set_source_table('game_cryptex', array( 'id' => backup::VAR_PARENTID)); $cryptex->set_source_table('game_cryptex', 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)); $snake->set_source_table('game_snakes', array( 'id' => backup::VAR_PARENTID));
$sudoku->set_source_table('game_sudoku', 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'); $attempt->annotate_ids('user', 'userid');
$grade->annotate_ids('user', 'userid'); $grade->annotate_ids('user', 'userid');
$repetition->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('glossary_enrty', 'glossaryentryid');
$query->annotate_ids('question_answer', 'answerid'); $query->annotate_ids('question_answer', 'answerid');
$bookquiz_question->annotate_ids('book_chapter', 'chapterid'); $bookquizquestion->annotate_ids('book_chapter', 'chapterid');
$bookquiz_question->annotate_ids('question_category', 'questioncategoryid'); $bookquizquestion->annotate_ids('question_category', 'questioncategoryid');
$bookquiz_chapter->annotate_ids('book_chapter', 'chapterid'); $bookquizchapter->annotate_ids('book_chapter', 'chapterid');
$hangman->annotate_ids('game_query', 'queryid'); $hangman->annotate_ids('game_query', 'queryid');
$millionaire->annotate_ids('game_query', 'queryid'); $millionaire->annotate_ids('game_query', 'queryid');
// Define file annotations // Define file annotations.
$game->annotate_files('mod_game', 'snakes_file', null); // This file area hasn't itemid $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 $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 the root element (game), wrapped into standard activity structure.
return $this->prepare_activity_structure( $game); return $this->prepare_activity_structure( $game);
} }
} }

106
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/ // This file is part of Moodle - http://moodle.org/
// //
// Moodle is free software: you can redistribute it and/or modify // Moodle is free software: you can redistribute it and/or modify
@ -23,7 +22,7 @@
*/ */
defined('MOODLE_INTERNAL') || die(); 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 * 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 * Define (add) particular settings this activity can have
*/ */
protected function define_my_settings() { 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 * Define (add) particular steps this activity can have
*/ */
protected function define_my_steps() { 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')); $this->add_step(new restore_game_activity_structure_step('game_structure', 'game.xml'));
} }
@ -101,7 +100,7 @@ class restore_game_activity_task extends restore_activity_task {
static public function define_restore_log_rules_for_course() { static public function define_restore_log_rules_for_course() {
$rules = array(); $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, $rules[] = new restore_log_rule('game', 'view all', 'index?id={course}', null,
null, null, 'index.php?id={course}'); null, null, 'index.php?id={course}');
$rules[] = new restore_log_rule('game', 'view all', 'index.php?id={course}', null); $rules[] = new restore_log_rule('game', 'view all', 'index.php?id={course}', null);
@ -110,124 +109,139 @@ class restore_game_activity_task extends restore_activity_task {
} }
public function after_restore() { public function after_restore() {
// Do something at end of restore // Do something at end of restore.
global $DB; global $DB;
// Get the blockid // Get the blockid.
$gameid = $this->get_activityid(); $gameid = $this->get_activityid();
// Extract Game configdata and update it to point to the new glossary // Extract Game configdata and update it to point to the new glossary.
$rec = $DB->get_record_select( 'game', 'id='.$gameid, null, $rec = $DB->get_record_select( 'game', 'id='.$gameid,
'id,quizid,glossaryid,glossarycategoryid,questioncategoryid,bookid,glossaryid2,glossarycategoryid2'); null, 'id,quizid,glossaryid,glossarycategoryid,questioncategoryid,bookid,glossaryid2,glossarycategoryid2');
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'quiz', $rec->quizid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'quiz', $rec->quizid);
if( $ret != false) if ($ret != false) {
$rec->quizid = $ret->newitemid; $rec->quizid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid);
if( $ret != false) if ($ret != false) {
$rec->glossaryid = $ret->newitemid; $rec->glossaryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid);
if( $ret != false) if ($ret != false) {
$rec->glossarycategoryid = $ret->newitemid; $rec->glossarycategoryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_categories', $rec->questioncategoryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_categories', $rec->questioncategoryid);
if( $ret != false) if ($ret != false) {
$rec->questioncategoryid = $ret->newitemid; $rec->questioncategoryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book', $rec->bookid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book', $rec->bookid);
if( $ret != false) if ($ret != false) {
$rec->bookid = $ret->newitemid; $rec->bookid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid2); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid2);
if( $ret != false) if ($ret != false) {
$rec->glossaryid2 = $ret->newitemid; $rec->glossaryid2 = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid);
if( $ret != false) if ($ret != false) {
$rec->glossarycategoryid = $ret->newitemid; $rec->glossarycategoryid = $ret->newitemid;
}
$DB->update_record( 'game', $rec); $DB->update_record( 'game', $rec);
//game_repetitions // Read game_repetitions.
$recs = $DB->get_records_select( 'game_repetitions', 'gameid='.$gameid, null, '', $recs = $DB->get_records_select( 'game_repetitions', 'gameid='.$gameid, null, '',
'id,questionid,glossaryentryid'); 'id,questionid,glossaryentryid');
if( $recs != false){ if ($recs != false) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid);
if( $ret != false) if ($ret != false) {
$rec->questionid = $ret->newitemid; $rec->questionid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid);
if( $ret != false) if ($ret != false) {
$rec->glossaryentryid = $ret->newitemid; $rec->glossaryentryid = $ret->newitemid;
}
$DB->update_record( 'game_repetitions', $rec); $DB->update_record( 'game_repetitions', $rec);
} }
} }
//game_queries // Read game_queries.
$recs = $DB->get_records_select( 'game_queries', 'gameid='.$gameid, null, '', $recs = $DB->get_records_select( 'game_queries', 'gameid='.$gameid, null, '',
'id,questionid,glossaryentryid,answerid'); 'id,questionid,glossaryentryid,answerid');
if( $recs != false){ if ($recs != false) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid);
if( $ret != false) if ($ret != false) {
$rec->questionid = $ret->newitemid; $rec->questionid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid);
if( $ret != false) if ($ret != false) {
$rec->glossaryentryid = $ret->newitemid; $rec->glossaryentryid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_answers', $rec->glossaryentryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_answers', $rec->glossaryentryid);
if( $ret != false) if ($ret != false) {
$rec->answerid = $ret->newitemid; $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'); $recs = $DB->get_records_select( 'game_bookquiz', 'id='.$gameid, null, '', 'id,lastchapterid');
if( $recs != false){ if ($recs != false) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->lastchapterid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->lastchapterid);
if( $ret != false) if ($ret != false) {
$rec->lastchapterid = $ret->newitemid; $rec->lastchapterid = $ret->newitemid;
}
$DB->update_record( 'game_bookquiz', $rec); $DB->update_record( 'game_bookquiz', $rec);
} }
} }
//bookquiz_chapters // 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"; $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); $recs = $DB->get_records_sql( $sql);
if( $recs != false){ if ($recs != false) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid);
if( $ret != false) if ($ret != false) {
$rec->chapterid = $ret->newitemid; $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'); $recs = $DB->get_records_select( 'game_bookquiz_questions', 'id='.$gameid, null, '', 'id,chapterid,questioncategoryid');
if( $recs != false){ if ($recs != false) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid);
if( $ret != false) if ($ret != false) {
$rec->chapterid = $ret->newitemid; $rec->chapterid = $ret->newitemid;
}
$ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->questioncategoryid); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->questioncategoryid);
if( $ret != false) if ($ret != false) {
$rec->questioncategoryid = $ret->newitemid; $rec->questioncategoryid = $ret->newitemid;
}
$DB->update_record( 'game_bookquiz_questions', $rec); $DB->update_record( 'game_bookquiz_questions', $rec);
} }
} }
} }
} }

34
backup/moodle2/restore_game_stepslib.php

@ -1,5 +1,4 @@
<?php <?php
// This file is part of Moodle - http://moodle.org/ // This file is part of Moodle - http://moodle.org/
// //
// Moodle is free software: you can redistribute it and/or modify // Moodle is free software: you can redistribute it and/or modify
@ -38,14 +37,16 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$paths[] = new restore_path_element('game', '/activity/game'); $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_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_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) { if ($userinfo) {
$paths[] = new restore_path_element('game_grade', '/activity/game/game_grades/game_grade'); $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_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_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_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', '/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_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_cryptex', '/activity/game/game_cryptexs/game_cryptex');
$paths[] = new restore_path_element('game_hangman', '/activity/game/game_hangmans/game_hangman'); $paths[] = new restore_path_element('game_hangman', '/activity/game/game_hangmans/game_hangman');
@ -55,7 +56,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$paths[] = new restore_path_element('game_sudoku', '/activity/game/game_sudokus/game_sudoku'); $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); return $this->prepare_activity_structure($paths);
} }
@ -67,10 +68,10 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->course = $this->get_courseid(); $data->course = $this->get_courseid();
$data->timemodified = $this->apply_date_offset($data->timemodified); $data->timemodified = $this->apply_date_offset($data->timemodified);
// insert the game record // Insert the game record.
$newitemid = $DB->insert_record('game', $data); $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); $this->apply_activity_instance($newitemid);
} }
@ -80,11 +81,10 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data = (object)$data; $data = (object)$data;
$data->id = $this->get_new_parentid('game'); $data->id = $this->get_new_parentid('game');
if( $data->id == 0) if ($data->id ! 0) {
return;
$DB->insert_record('game_export_html', $data); $DB->insert_record('game_export_html', $data);
} }
}
protected function process_game_export_javame($data) { protected function process_game_export_javame($data) {
global $DB; global $DB;
@ -92,11 +92,10 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data = (object)$data; $data = (object)$data;
$data->id = $this->get_new_parentid('game'); $data->id = $this->get_new_parentid('game');
if( $data->id == 0) if ($data->id != 0) {
return;
$DB->insert_record('game_export_javame', $data); $DB->insert_record('game_export_javame', $data);
} }
}
protected function process_game_grade($data) { protected function process_game_grade($data) {
global $DB; global $DB;
@ -131,12 +130,15 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
$data->gameid = $this->get_new_parentid('game'); $data->gameid = $this->get_new_parentid('game');
$data->userid = $this->get_mappingid('user', $data->userid); $data->userid = $this->get_mappingid('user', $data->userid);
if( !isset( $data->timestart)) if (!isset( $data->timestart)) {
$data->timestart = 0; $data->timestart = 0;
if( !isset( $data->timefinish)) }
if (!isset( $data->timefinish)) {
$data->timefinish = 0; $data->timefinish = 0;
if( !isset( $data->timelastattempt)) }
if (!isset( $data->timelastattempt)) {
$data->timelastattempt = 0; $data->timelastattempt = 0;
}
$data->timestart = $this->apply_date_offset($data->timestart); $data->timestart = $this->apply_date_offset($data->timestart);
$data->timefinish = $this->apply_date_offset($data->timefinish); $data->timefinish = $this->apply_date_offset($data->timefinish);
@ -264,7 +266,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st
} }
protected function after_execute() { 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_file', null);
$this->add_related_files('mod_game', 'snakes_board', null); $this->add_related_files('mod_game', 'snakes_board', null);
} }

573
bookquiz/importodt.php

File diff suppressed because it is too large

384
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 * This is a very rough importer for powerpoint slides
* Export a powerpoint presentation with powerpoint as html pages * Export a powerpoint presentation with powerpoint as html pages
@ -13,61 +28,64 @@
* @package lesson * @package lesson
**/ **/
require_once("../../config.php"); require_once("../../config.php");
require_once("locallib.php"); require_once("locallib.php");
$id = required_param('id', PARAM_INT); // Course Module ID $id = required_param('id', PARAM_INT); // Course Module ID.
$pageid = optional_param('pageid', '', PARAM_INT); // Page ID $pageid = optional_param('pageid', '', PARAM_INT); // Page ID.
global $matches; global $matches;
if (! $cm = get_coursemodule_from_id('lesson', $id)) { if (! $cm = get_coursemodule_from_id('lesson', $id)) {
print_error('Course Module ID was incorrect'); 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'); print_error('Course is misconfigured');
} }
// allows for adaption for multiple modules // Allows for adaption for multiple modules.
if(! $modname = $DB->get_field('modules', 'name', array( 'id' => $cm->module))) { if (!$modname = $DB->get_field('modules', 'name', array( 'id' => $cm->module))) {
print_error('Could not find module name'); print_error('Could not find module name');
} }
if (! $mod = $DB->get_record($modname, array( "id" => $cm->instance))) { if (! $mod = $DB->get_record($modname, array( "id" => $cm->instance))) {
print_error('Course module is incorrect'); print_error('Course module is incorrect');
} }
require_login($course->id, false);
$context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/lesson:edit', $context);
$strimportppt = get_string("importppt", "lesson"); require_login($course->id, false);
$strlessons = get_string("modulenameplural", "lesson"); $context = get_context_instance(CONTEXT_MODULE, $cm->id);
require_capability('mod/lesson:edit', $context);
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"); $strimportppt = get_string("importppt", "lesson");
$strlessons = get_string("modulenameplural", "lesson");
if ($form = data_submitted()) { /// Filename 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 (empty($_FILES['newfile'])) { // file was just uploaded if ($form = data_submitted()) { // Filename.
if (empty($_FILES['newfile'])) { // File was just uploaded.
notify(get_string("uploadproblem") ); notify(get_string("uploadproblem") );
} }
if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) { if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) {
notify(get_string("uploadnofilefound") ); 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.
} else { // Valid file is found $modcreateobjects = $modname.'_create_objects';
$modsaveobjects = $modname.'_save_objects';
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 // Function to preps the data to be sent to DB.
$objects = $modcreateobjects($pageobjects, $mod->id);
if(! $mod_save_objects($objects, $mod->id, $pageid)) { // sends it to DB if (! $modsaveobjects($objects, $mod->id, $pageid)) {
// Sends it to DB.
print_error( 'could not save'); print_error( 'could not save');
} }
} else { } else {
@ -79,42 +97,42 @@
echo $OUTPUT->footer($course); echo $OUTPUT->footer($course);
exit; exit;
} }
} }
/// Print upload form
print_heading_with_help($strimportppt, "importppt", "lesson"); // Print upload form.
print_heading_with_help($strimportppt, "importppt", "lesson");
echo $OUTPUT->box_start('center'); echo $OUTPUT->box_start('center');
echo "<form id=\"theform\" enctype=\"multipart/form-data\" method=\"post\">"; 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=\"id\" value=\"$cm->id\" />\n";
echo "<input type=\"hidden\" name=\"pageid\" value=\"$pageid\" />\n"; echo "<input type=\"hidden\" name=\"pageid\" value=\"$pageid\" />\n";
echo "<table cellpadding=\"5\">"; echo "<table cellpadding=\"5\">";
echo "<tr><td align=\"right\">"; echo "<tr><td align=\"right\">";
print_string("upload"); print_string("upload");
echo ":</td><td>"; echo ":</td><td>";
echo "<input name=\"newfile\" type=\"file\" size=\"50\" />"; echo "<input name=\"newfile\" type=\"file\" size=\"50\" />";
echo "</td></tr><tr><td>&nbsp;</td><td>"; echo "</td></tr><tr><td>&nbsp;</td><td>";
echo "<input type=\"submit\" name=\"save\" value=\"".get_string("uploadthisfile")."\" />"; echo "<input type=\"submit\" name=\"save\" value=\"".get_string("uploadthisfile")."\" />";
echo "</td></tr>"; echo "</td></tr>";
echo "</table>"; echo "</table>";
echo "</form>"; echo "</form>";
echo $OUTPUT->box_end(); 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) { 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; global $CFG;
// create an upload directory in temp // Create an upload directory in temp.
make_upload_directory('temp/'.$modname); make_upload_directory('temp/'.$modname);
$base = $CFG->dataroot."/temp/$modname/"; $base = $CFG->dataroot."/temp/$modname/";
@ -122,22 +140,23 @@ function readdata($file, $courseid, $modname) {
$zipfile = $_FILES["newfile"]["name"]; $zipfile = $_FILES["newfile"]["name"];
$tempzipfile = $_FILES["newfile"]["tmp_name"]; $tempzipfile = $_FILES["newfile"]["tmp_name"];
// create our directory // Create our directory.
$path_parts = pathinfo($zipfile); $pathparts = pathinfo($zipfile);
$dirname = substr($zipfile, 0, strpos($zipfile, '.'.$path_parts['extension'])); // take off the extension // Take off the extension.
$dirname = substr($zipfile, 0, strpos($zipfile, '.'.$pathparts['extension']));
if (!file_exists($base.$dirname)) { if (!file_exists($base.$dirname)) {
mkdir($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); move_uploaded_file($tempzipfile, $base.$zipfile);
// unzip it! // Unzip it!
unzip_file($base.$zipfile, $base, false); unzip_file($base.$zipfile, $base, false);
$base = $base.$dirname; // update the base $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) // This is the file where we get the names of the files for the slides (in the correct order too).
$outline = $base.'/outline.htm'; $outline = $base.'/outline.htm';
$pages = array(); $pages = array();
@ -145,9 +164,10 @@ function readdata($file, $courseid, $modname) {
if (file_exists($outline) and is_readable($outline)) { if (file_exists($outline) and is_readable($outline)) {
$outlinecontents = file_get_contents($outline); $outlinecontents = file_get_contents($outline);
$filenames = array(); $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) { foreach ($filenames[1] as $file) {
$path = $base.'/'.$file; $path = $base.'/'.$file;
if (is_readable($path)) { if (is_readable($path)) {
@ -157,10 +177,11 @@ function readdata($file, $courseid, $modname) {
} }
} }
} else { } 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); $dh = opendir($base);
while (false !== ($file = readdir($dh))) { // read throug the directory while (false !== ($file = readdir($dh))) { // Read throug the directory.
if ('slide' == substr($file, 0, 5)) { // check for name (may want to check extension later) if ('slide' == substr($file, 0, 5)) {
// Check for name (may want to check extension later).
$path = $base.'/'.$file; $path = $base.'/'.$file;
if (is_readable($path)) { if (is_readable($path)) {
$pages[$path] = file_get_contents($path); $pages[$path] = file_get_contents($path);
@ -170,7 +191,7 @@ function readdata($file, $courseid, $modname) {
} }
} }
ksort($pages); // order them by file name ksort($pages); // Order them by file name.
} }
if (empty($pages)) { if (empty($pages)) {
@ -180,18 +201,20 @@ function readdata($file, $courseid, $modname) {
return $pages; 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) { 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 $CFG;
global $matches; global $matches;
$extratedpages = array(); $extratedpages = array();
// directory for images // Directory for images.
make_mod_upload_directory($courseid); // make sure moddata is made 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 // We store our images in a subfolder in here.
make_upload_directory($courseid.'/moddata/'.$modname, false);
$imagedir = $CFG->dataroot.'/'.$courseid.'/moddata/'.$modname; $imagedir = $CFG->dataroot.'/'.$courseid.'/moddata/'.$modname;
@ -201,12 +224,12 @@ function extract_data($pages, $courseid, $lessonname, $modname) {
$imagelink = $CFG->wwwroot.'/file.php?file=/'.$courseid.'/moddata/'.$modname; $imagelink = $CFG->wwwroot.'/file.php?file=/'.$courseid.'/moddata/'.$modname;
} }
// try to make a unique subfolder to store the images // Try to make a unique subfolder to store the images.
$lessonname = str_replace(' ', '_', $lessonname); // get rid of spaces $lessonname = str_replace(' ', '_', $lessonname); // Get rid of spaces.
$i = 0; $i = 0;
while(true) { while (true) {
if (!file_exists($imagedir.'/'.$lessonname.$i)) { 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); mkdir($imagedir.'/'.$lessonname.$i);
$imagedir = $imagedir.'/'.$lessonname.$i; $imagedir = $imagedir.'/'.$lessonname.$i;
$imagelink = $imagelink.'/'.$lessonname.$i; $imagelink = $imagelink.'/'.$lessonname.$i;
@ -216,66 +239,69 @@ function extract_data($pages, $courseid, $lessonname, $modname) {
} }
foreach ($pages as $file => $content) { foreach ($pages as $file => $content) {
// to make life easier on our preg_match_alls, we strip out all tags except /* 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 * 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 * can identify the content in the div based on the div's class
*/
$tags = '<div><img>'; // should also allow <b><i> $tags = '<div><img>'; // Should also allow <b><i>.
$string = strip_tags($content,$tags); $string = strip_tags($content, $tags);
//echo s($string);
$matches = array(); $matches = array();
// this will look for a non nested tag that is closed /* this will look for a non nested tag that is closed
// want to allow <b><i>(maybe more) tags but when we do that * want to allow <b><i>(maybe more) tags but when we do that
// the preg_match messes up. * the preg_match messes up.
*/
preg_match_all("/(<([\w]+)[^>]*>)([^<\\2>]*)(<\/\\2>)/", $string, $matches); preg_match_all("/(<([\w]+)[^>]*>)([^<\\2>]*)(<\/\\2>)/", $string, $matches);
//(<([\w]+)[^>]*>)([^<\\2>]*)(<\/\\2>) original pattern
//(<(div+)[^>]*>)[^(<div*)](<\/div>) work in progress
$path_parts = pathinfo($file); $pathparts = pathinfo($file);
$file = substr($path_parts['basename'], 0, strpos($path_parts['basename'], '.')); // get rid of the extension // Get rid of the extension.
$file = substr($pathparts['basename'], 0, strpos($pathparts['basename'], '.'));
$imgs = array(); $imgs = array();
// this preg matches all images // This preg matches all images.
preg_match_all("/<img[^>]*(src\=\"(".$file."\_image[^>^\"]*)\"[^>]*)>/i", $string, $imgs); preg_match_all("/<img[^>]*(src\=\"(".$file."\_image[^>^\"]*)\"[^>]*)>/i", $string, $imgs);
// start building our page // Start building our page.
$page = new stdClass; $page = new stdClass;
$page->title = ''; $page->title = '';
$page->contents = array(); $page->contents = array();
$page->images = array(); $page->images = array();
$page->source = $path_parts['basename']; // need for book only $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 keeps the style intact.
// this foreach and uncomment the line with the comment imgstyle in it. Also need to comment out * Found it doesn't help much. But if you want back uncomment
// the $page->images[]... line in the next foreach * this foreach and uncomment the line with the comment imgstyle in it.
/*foreach ($imgs[1] as $img) { * Also need to comment out
$page->images[] = '<img '.str_replace('src="', "src=\"$imagelink/", $img).' />'; * the $page->images[]... line in the next foreach
}*/ */
foreach ($imgs[2] as $img) { foreach ($imgs[2] as $img) {
copy($path_parts['dirname'].'/'.$img, $imagedir.'/'.$img); copy($pathparts['dirname'].'/'.$img, $imagedir.'/'.$img);
$page->images[] = "<img src=\"$imagelink/$img\" title=\"$img\" />"; // comment out this line if you are using the above foreach loop // 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 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.
$class = isolate_class($matches[1][$i]); // first step in isolating the class // Check for any static classes.
// check for any static classes
switch ($class) { switch ($class) {
case 'T': // class T is used for Titles case 'T': // Class T is used for Titles.
$page->title = $matches[3][$i]; $page->title = $matches[3][$i];
break; break;
case 'B': // I would guess that all bullet lists would start with B then go to B1, B2, etc // 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 case 'B':
// B1-B4 are just insurance, should just hit B and all be taken care of.
case 'B1':
case 'B2': case 'B2':
case 'B3': case 'B3':
case 'B4': 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; break;
default: default:
if ($matches[3][$i] != '&#13;') { // odd crap generated... sigh if ($matches[3][$i] != '&#13;') { // Odd crap generated... sigh.
if (substr($matches[3][$i], 0, 1) == ':') { // check for leading : ... hate MS ... if (substr($matches[3][$i], 0, 1) == ':') {// Check for leading : ..hate MS .
$page->contents[] = substr($matches[3][$i], 1); // get rid of : $page->contents[] = substr($matches[3][$i], 1); // Get rid of :.
} else { } else {
$page->contents[] = $matches[3][$i]; $page->contents[] = $matches[3][$i];
} }
@ -284,91 +310,86 @@ function extract_data($pages, $courseid, $lessonname, $modname) {
} }
} }
// add the page to the array; // Add the page to the array.
$extratedpages[] = $page; $extratedpages[] = $page;
} // end $pages foreach loop } // End $pages foreach loop.
return $extratedpages; return $extratedpages;
} }
/** // A recursive function to build a html list.
A recursive function to build a html list
*/
function build_list($list, &$i, $depth) { function build_list($list, &$i, $depth) {
global $matches; // not sure why I global this... global $matches; // Not sure why I global this...
while($i < count($matches[1])) {
while ($i < count($matches[1])) {
$class = isolate_class($matches[1][$i]); $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') { if ($class == 'B') {
$this_depth = 0; // calling class B depth 0 $thisdepth = 0; // Calling class B depth 0.
} else { } else {
// set the depth number. So B1 is depth 1 and B2 is depth 2 and so on // Set the depth number. So B1 is depth 1 and B2 is depth 2 and so on.
$this_depth = substr($class, 1); $thisdepth = substr($class, 1);
if (!is_numeric($this_depth)) { if (!is_numeric($thisdepth)) {
print_error( 'Depth not parsed!'); print_error( 'Depth not parsed!');
} }
} if ($thisdepth < $depth) {
if ($this_depth < $depth) { // We are moving back a level in the nesting.
// we are moving back a level in the nesting
break; break;
} }
if ($this_depth > $depth) { if ($thisdepth > $depth) {
// we are moving in a lvl in nesting // We are moving in a lvl in nesting.
$list .= '<ul>'; $list .= '<ul>';
$list = build_list($list, $i, $this_depth); $list = build_list($list, $i, $thisdepth);
// once we return back, should go to the start of the while // Once we return back, should go to the start of the while.
continue; 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])) { if ($cleanstring = ppt_clean_text($matches[3][$i])) {
$list .= '<li>'.ppt_clean_text($matches[3][$i]).'</li>'; $list .= '<li>'.ppt_clean_text($matches[3][$i]).'</li>';
} }
$i++; $i++;
} else { } else {
// not a B class, so get out of here... // Not a B class, so get out of here...
break; break;
} }
} }
// end the list and return it
// End the list and return it.
$list .= '</ul>'; $list .= '</ul>';
return $list; return $list;
} }
/** // Given an html tag, this function will.
Given an html tag, this function will
*/
function isolate_class($string) { function isolate_class($string) {
if($class = strstr($string, 'class=')) { // first step in isolating the class if ($class = strstr($string, 'class=')) {
$class = substr($class, strpos($class, '=')+1); // this gets rid of <div blawblaw class= there are no "" or '' around the class name ...sigh... // 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, ' ')) { 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, ' ')); return substr($class, 0, strpos($class, ' '));
} else { } 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, '>')); return substr($class, 0, strpos($class, '>'));
} }
} else { } else {
// no class defined in the tag // No class defined in the tag.
return ''; 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) { function ppt_clean_text($string) {
$chop = 1; // default: just a single char infront of the content $chop = 1; // Default: just a single char infront of the content.
// look for any other crazy things that may be 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 if (strstr($string, '&lt;') and strpos($string, '&lt;') == 0) {
$chop = 4; // increase the $chop // 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); $string = substr($string, $chop);
@ -379,41 +400,36 @@ function ppt_clean_text($string) {
} }
} }
/** // Clean up the temp directory.
Clean up the temp directory
*/
function clean_temp() { function clean_temp() {
global $CFG; global $CFG;
// this function is broken, use it to clean up later /* 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 * should only clean up what we made as well because someone else could be importing ppt as well
//delDirContents($CFG->dataroot.'/temp/lesson'); * 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) { function book_create_objects($pageobjects, $bookid) {
$chapters = array(); $chapters = array();
$chapter = new stdClass; $chapter = new stdClass;
// same for all chapters // Same for all chapters.
$chapter->bookid = $bookid; $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->timecreated = time();
$chapter->timemodified = time(); $chapter->timemodified = time();
$chapter->subchapter = 0; $chapter->subchapter = 0;
$i = 1; $i = 1;
foreach ($pageobjects as $pageobject) { foreach ($pageobjects as $pageobject) {
$page = prep_page($pageobject, $i); // get title and contents $page = prep_page($pageobject, $i); // Get title and contents.
$chapter->importsrc = addslashes($pageobject->source); // add the source $chapter->importsrc = addslashes($pageobject->source); // Add the source.
$chapter->title = $page->title; $chapter->title = $page->title;
$chapter->content = $page->contents; $chapter->content = $page->contents;
$chapters[] = $chapter; $chapters[] = $chapter;
// increment our page number and our counter // Increment our page number and our counter.
$chapter->pagenum = $chapter->pagenum + 1; $chapter->pagenum = $chapter->pagenum + 1;
$i++; $i++;
} }
@ -421,44 +437,40 @@ function book_create_objects($pageobjects, $bookid) {
return $chapters; 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) { function prep_page($pageobject, $count) {
if ($pageobject->title == '') { 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 { } else {
$page->title = addslashes($pageobject->title); $page->title = addslashes($pageobject->title);
} }
$page->contents = ''; $page->contents = '';
// nab all the images first // Nab all the images first.
foreach ($pageobject->images as $image) { foreach ($pageobject->images as $image) {
$image = str_replace("\n", '', $image); $image = str_replace("\n", '', $image);
$image = str_replace("\r", '', $image); $image = str_replace("\r", '', $image);
$image = str_replace("'", '"', $image); // imgstyle $image = str_replace("'", '"', $image); // Imgstyle.
$page->contents .= addslashes($image); $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) { foreach ($pageobject->contents as $content) {
$content = str_replace("\n", '', $content); $content = str_replace("\n", '', $content);
$content = str_replace("\r", '', $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>'; $content = '<p>'.$content.'</p>';
$page->contents .= addslashes($content); $page->contents .= addslashes($content);
} }
return $page; return $page;
} }
/** // Save the chapter objects to the database.
Save the chapter objects to the database
*/
function book_save_objects($chapters, $bookid, $pageid='0') { function book_save_objects($chapters, $bookid, $pageid='0') {
global $DB; global $DB;
// nothing fancy, just save them all in order // Nothing fancy, just save them all in order.
foreach ($chapters as $chapter) { foreach ($chapters as $chapter) {
if (!$chapter->id = $DB->insert_record('book_chapters', $chapter)) { if (!$chapter->id = $DB->insert_record('book_chapters', $chapter)) {
print_error('Could not update your book'); print_error('Could not update your book');

230
bookquiz/play.php

@ -1,12 +1,25 @@
<?php // $Id: play.php,v 1.8 2012/07/25 22:46:42 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
function game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $chapterid, $context) //
{ // Moodle is free software: you can redistribute it and/or modify
if( $attempt != false and $bookquiz != false){ // 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); return game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context);
} }
if( $attempt == false){ if ($attempt == false) {
$attempt = game_addattempt( $game); $attempt = game_addattempt( $game);
} }
@ -15,82 +28,78 @@ function game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $chapterid, $c
$bookquiz->id = $attempt->id; $bookquiz->id = $attempt->id;
$bookquiz->bookid = $game->bookid; $bookquiz->bookid = $game->bookid;
if( !game_insert_record( 'game_bookquiz', $bookquiz)){ if ( !game_insert_record( 'game_bookquiz', $bookquiz)) {
print_error( 'game_bookquiz_continue: error inserting in game_bookquiz'); print_error( 'game_bookquiz_continue: error inserting in game_bookquiz');
} }
return game_bookquiz_play( $id, $game, $attempt, $bookquiz, 0, $context); return game_bookquiz_play( $id, $game, $attempt, $bookquiz, 0, $context);
} }
function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context) function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context) {
{
global $DB, $OUTPUT, $cm; global $DB, $OUTPUT, $cm;
if( $bookquiz->lastchapterid == 0){ if ($bookquiz->lastchapterid == 0) {
game_bookquiz_play_computelastchapter( $game, $bookquiz); game_bookquiz_play_computelastchapter( $game, $bookquiz);
if( $bookquiz->lastchapterid == 0){ if ($bookquiz->lastchapterid == 0) {
print_error( get_string( 'bookquiz_empty', 'game')); print_error( get_string( 'bookquiz_empty', 'game'));
} }
} }
if( $chapterid == 0){ if ($chapterid == 0) {
$chapterid = $bookquiz->lastchapterid; $chapterid = $bookquiz->lastchapterid;
}else } else {
{ if (($DB->set_field( 'game_bookquiz', 'lastchapterid', $chapterid, array( 'id' => $bookquiz->id))) == false) {
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"); print_error( "Can't update table game_bookquiz with lastchapterid to $chapterid");
} }
} }
$book = $DB->get_record( 'book', array('id' => $game->bookid)); $book = $DB->get_record( 'book', array('id' => $game->bookid));
if( !$chapter = $DB->get_record( 'book_chapters', array('id' => $chapterid))){ if (!$chapter = $DB->get_record( 'book_chapters', array('id' => $chapterid))) {
print_error('Error reading book chapters.'); print_error('Error reading book chapters.');
} }
$select = "bookid = $game->bookid AND hidden = 0"; $select = "bookid = $game->bookid AND hidden = 0";
$chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden'); $chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden');
$okchapters = array(); $okchapters = array();
if( ($recs = $DB->get_records( 'game_bookquiz_chapters', array( 'attemptid' => $attempt->id))) != false){ if (($recs = $DB->get_records( 'game_bookquiz_chapters', array( 'attemptid' => $attempt->id))) != false) {
foreach( $recs as $rec){ foreach ($recs as $rec) {
//1 means correct answer // The 1 means correct answer.
$okchapters[ $rec->chapterid] = 1; $okchapters[ $rec->chapterid] = 1;
} }
} }
//2 means current
//$okchapters[ $chapterid] = 2; // The 2 means current.
$showquestions = false; $showquestions = false;
$a = array( 'gameid' => $game->id, 'chapterid' => $chapterid); $a = array( 'gameid' => $game->id, 'chapterid' => $chapterid);
if( ($questions = $DB->get_records( 'game_bookquiz_questions', $a)) === false){ if (($questions = $DB->get_records( 'game_bookquiz_questions', $a)) === false) {
if( !array_key_exists( $chapterid, $okchapters)){ if (!array_key_exists( $chapterid, $okchapters)) {
$okchapters[ $chapterid] = 1; $okchapters[ $chapterid] = 1;
$newrec = new stdClass(); $newrec = new stdClass();
$newrec->attemptid = $attempt->id; $newrec->attemptid = $attempt->id;
$newrec->chapterid = $chapterid; $newrec->chapterid = $chapterid;
if( !$DB->insert_record( 'game_bookquiz_chapters', $newrec)){ if (!$DB->insert_record( 'game_bookquiz_chapters', $newrec)) {
print_error( "Can't insert to table game_bookquiz_chapters"); print_error( "Can't insert to table game_bookquiz_chapters");
} }
} }
}else } else {
{ // Have to select random one question.
//Have to select random one question
$questionid = game_bookquiz_selectrandomquestion( $questions); $questionid = game_bookquiz_selectrandomquestion( $questions);
if( $questionid != 0){ if ($questionid != 0) {
$showquestions = true; $showquestions = true;
} }
} }
// Prepare chapter navigation icons.
/// prepare chapter navigation icons $previd = null;
$previd = null; $nextid = null;
$nextid = null; $found = 0;
$found = 0; $scoreattempt = 0;
$scoreattempt = 0; $lastid = 0;
$lastid = 0; foreach ($chapters as $ch) {
foreach ($chapters as $ch) {
$scoreattempt++; $scoreattempt++;
if ($found) { if ($found) {
$nextid= $ch->id; $nextid = $ch->id;
break; break;
} }
if ($ch->id == $chapter->id) { if ($ch->id == $chapter->id) {
@ -100,27 +109,30 @@ foreach ($chapters as $ch) {
$previd = $ch->id; $previd = $ch->id;
} }
$lastid = $ch->id; $lastid = $ch->id;
} }
if ($ch == current($chapters)) { if ($ch == current($chapters)) {
$nextid = $ch->id; $nextid = $ch->id;
} }
if( count( $chapters)){ if (count( $chapters)) {
$scoreattempt = ($scoreattempt-1) / count( $chapters); $scoreattempt = ($scoreattempt - 1) / count( $chapters);
} }
$chnavigation = '';
$chnavigation = '';
if ($previd) { 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>'; $chnavigation .= '<a title="'.get_string('navprev', 'book').'" href="attempt.php?id='.$id.
} else { '&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="" />'; $chnavigation .= '<img src="'.$OUTPUT->pix_url('bookquiz/nav_prev_dis', 'mod_game').'" class="bigicon" alt="" />';
} }
$nextbutton = ''; $nextbutton = '';
if ($nextid) { if ($nextid) {
if( !$showquestions){ 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>'; $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 = '<center>';
$nextbutton .= '<form name="form" method="get" action="attempt.php">'; $nextbutton .= '<form name="form" method="get" action="attempt.php">';
$nextbutton .= '<input type="hidden" name="id" value="'.$id.'" >'."\r\n"; $nextbutton .= '<input type="hidden" name="id" value="'.$id.'" >'."\r\n";
@ -130,13 +142,13 @@ if ($nextid) {
$showquestions = false; $showquestions = false;
game_updateattempts_maxgrade( $game, $attempt, $scoreattempt, 0); game_updateattempts_maxgrade( $game, $attempt, $scoreattempt, 0);
} }
} else { } else {
game_updateattempts_maxgrade( $game, $attempt, 1, 0); game_updateattempts_maxgrade( $game, $attempt, 1, 0);
$sec = ''; $sec = '';
if( !isset( $cm)) if (!isset( $cm)) {
{
$cm = get_coursemodule_from_instance('game', $game->id, $game->course); $cm = get_coursemodule_from_instance('game', $game->id, $game->course);
} }
if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) { if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) {
$sec = $section->section; $sec = $section->section;
} }
@ -144,17 +156,19 @@ if ($nextid) {
if (! $cm = $DB->get_record('course_modules', array( 'id' => $id))) { if (! $cm = $DB->get_record('course_modules', array( 'id' => $id))) {
print_error("Course Module ID was incorrect 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>'; $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'); require( 'toc.php');
$tocwidth = '10%'; $tocwidth = '10%';
if( $showquestions){ if ($showquestions) {
if( $game->param3 == 0) if ($game->param3 == 0) {
game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context); game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context);
} }
}
?> ?>
<table border="0" cellspacing="0" width="100%" valign="top" cellpadding="2"> <table border="0" cellspacing="0" width="100%" valign="top" cellpadding="2">
@ -182,7 +196,7 @@ $tocwidth = '10%';
?> ?>
</td> </td>
<td valign="top" align="left"> <td valign="top" align="left">
<?php <?php
echo $OUTPUT->box_start('generalbox'); echo $OUTPUT->box_start('generalbox');
$content = ''; $content = '';
if (!$book->customtitles) { if (!$book->customtitles) {
@ -199,55 +213,54 @@ $tocwidth = '10%';
$nocleanoption = new object(); $nocleanoption = new object();
$nocleanoption->noclean = true; $nocleanoption->noclean = true;
echo '<div>'; echo '<div>';
if( $nextbutton != ''){ if ($nextbutton != '') {
echo $nextbutton; echo $nextbutton;
} }
echo format_text($content, FORMAT_HTML, $nocleanoption); echo format_text($content, FORMAT_HTML, $nocleanoption);
if( $nextbutton != ''){ if ($nextbutton != '') {
echo $nextbutton; echo $nextbutton;
} }
echo '</div>'; echo '</div>';
echo $OUTPUT->box_end(); echo $OUTPUT->box_end();
/// lower navigation // Lower navigation.
echo '<p align="right">'.$chnavigation.'</p>'; echo '<p align="right">'.$chnavigation.'</p>';
?> ?>
</td> </td>
</tr> </tr>
</table> </table>
<?php <?php
if( $showquestions){ if ($showquestions) {
if( $game->param3 != 0) if ($game->param3 != 0) {
game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context); game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context);
} }
}
} }
function game_bookquiz_play_computelastchapter( $game, &$bookquiz) function game_bookquiz_play_computelastchapter( $game, &$bookquiz) {
{
global $DB; global $DB;
if( $game->bookid == 0) if ($game->bookid == 0) {
{
print_error( 'Not defined a book on this game'); print_error( 'Not defined a book on this game');
} }
$pagenum = $DB->get_field( 'book_chapters', 'min(pagenum) as p', array('bookid' => $game->bookid)); $pagenum = $DB->get_field( 'book_chapters', 'min(pagenum) as p', array('bookid' => $game->bookid));
if( $pagenum){ if ($pagenum) {
$bookquiz->lastchapterid = $DB->get_field( 'book_chapters', 'id', array('bookid' => $game->bookid, 'pagenum' => $pagenum)); $bookquiz->lastchapterid = $DB->get_field( 'book_chapters', 'id', array('bookid' => $game->bookid, 'pagenum' => $pagenum));
if( $bookquiz->lastchapterid){ if ($bookquiz->lastchapterid) {
//update the data in table game_bookquiz // Update the data in table game_bookquiz.
if( ($DB->set_field( 'game_bookquiz', 'lastchapterid', $bookquiz->lastchapterid, array('id' => $bookquiz->id))) == false){ 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"); print_error( "Can't update table game_bookquiz with lastchapterid to $bookquiz->lastchapterid");
} }
} }
} }
} }
function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapterid, $scoreattempt, $game, $context) function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapterid, $scoreattempt, $game, $context) {
{
$onlyshow = false; $onlyshow = false;
$showsolution = false; $showsolution = false;
@ -256,13 +269,14 @@ function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapter
global $CFG; global $CFG;
/// Start the form // Start the form.
echo "<form id=\"responseform\" method=\"post\" action=\"{$CFG->wwwroot}/mod/game/attempt.php\" onclick=\"this.autocomplete='off'\">\n"; echo "<form id=\"responseform\" method=\"post\" action=\"{$CFG->wwwroot}/mod/game/attempt.php\" ".
if( ($onlyshow === false) and ($showsolution === false)){ " 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"; echo "<center><input type=\"submit\" name=\"finishattempt\" value=\"".get_string('sudoku_submit', 'game')."\"></center>\n";
} }
// Add a hidden field with the quiz id // Add a hidden field with the quiz id.
echo '<div>'; echo '<div>';
echo '<input type="hidden" name="id" value="' . s($id) . "\" />\n"; echo '<input type="hidden" name="id" value="' . s($id) . "\" />\n";
echo '<input type="hidden" name="action" value="bookquizcheck" />'; echo '<input type="hidden" name="action" value="bookquizcheck" />';
@ -270,57 +284,54 @@ function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapter
echo '<input type="hidden" name="scoreattempt" value="'.$scoreattempt.'" />'; echo '<input type="hidden" name="scoreattempt" value="'.$scoreattempt.'" />';
echo '<input type="hidden" name="nextchapterid" value="'.$nextchapterid.'" />'; echo '<input type="hidden" name="nextchapterid" value="'.$nextchapterid.'" />';
/// Print all the questions // Print all the questions.
// Add a hidden field with questionids // Add a hidden field with questionids.
echo '<input type="hidden" name="questionids" value="'.$questionlist."\" />\n"; echo '<input type="hidden" name="questionids" value="'.$questionlist."\" />\n";
$number=0; $number = 0;
foreach ($questions as $question) { foreach ($questions as $question) {
game_print_question( $game, $question, $context); game_print_question( $game, $question, $context);
} }
echo "</div>"; echo "</div>";
// Finish the form // Finish the form.
echo '</div>'; echo '</div>';
if( ($onlyshow === false) and ($showsolution === false)){ if (($onlyshow === false) and ($showsolution === false)) {
echo "<center><input type=\"submit\" name=\"finishattempt\" value=\"".get_string('sudoku_submit', 'game')."\"></center>\n"; echo "<center><input type=\"submit\" name=\"finishattempt\" value=\"".get_string('sudoku_submit', 'game')."\"></center>\n";
} }
echo "</form>\n"; echo "</form>\n";
} }
function game_bookquiz_selectrandomquestion( $questions) function game_bookquiz_selectrandomquestion( $questions) {
{
global $DB; global $DB;
$categorylist = ''; $categorylist = '';
if( $questions == false){ if ($questions == false) {
return 0; return 0;
} }
foreach( $questions as $rec){ foreach ($questions as $rec) {
$categorylist .= ',' . $rec->questioncategoryid; $categorylist .= ',' . $rec->questioncategoryid;
} }
$select = 'category in ('.substr( $categorylist, 1). ") AND qtype in ('shortanswer', 'truefalse', 'multichoice')"; $select = 'category in ('.substr( $categorylist, 1). ") AND qtype in ('shortanswer', 'truefalse', 'multichoice')";
if( ($recs = $DB->get_records_select( 'question', $select, null, '', 'id,id')) == false){ if (($recs = $DB->get_records_select( 'question', $select, null, '', 'id,id')) == false) {
return 0; return 0;
} }
$a = array(); $a = array();
foreach( $recs as $rec){ foreach ($recs as $rec) {
$a[ $rec->id] = $rec->id; $a[ $rec->id] = $rec->id;
} }
if( count( $a) == 0){ if (count( $a) == 0) {
return 0; return 0;
}else } else {
{
return array_rand( $a); return array_rand( $a);
} }
} }
function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $context) function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $context) {
{
global $USER, $DB; global $USER, $DB;
$scoreattempt = optional_param('scoreattempt', 0, PARAM_INT); $scoreattempt = optional_param('scoreattempt', 0, PARAM_INT);
@ -337,28 +348,27 @@ function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $contex
$chapterid = required_param('chapterid', PARAM_INT); $chapterid = required_param('chapterid', PARAM_INT);
$nextchapterid = required_param('nextchapterid', PARAM_INT); $nextchapterid = required_param('nextchapterid', PARAM_INT);
foreach($questions as $question) { foreach ($questions as $question) {
if( !array_key_exists( $question->id, $grades)){ if (!array_key_exists( $question->id, $grades)) {
//no answered // No answered.
continue; continue;
} }
$grade = $grades[ $question->id]; $grade = $grades[ $question->id];
if( $grade->grade < 0.99){ if ($grade->grade < 0.99) {
continue; continue;
} }
//found one correct answer // Found one correct answer.
if( !$DB->get_field( 'game_bookquiz_chapters', 'id', array( 'attemptid' => $attempt->id, 'chapterid' => $chapterid))) if (!$DB->get_field( 'game_bookquiz_chapters', 'id', array( 'attemptid' => $attempt->id, 'chapterid' => $chapterid))) {
{
$newrec = new stdClass(); $newrec = new stdClass();
$newrec->attemptid = $attempt->id; $newrec->attemptid = $attempt->id;
$newrec->chapterid = $chapterid; $newrec->chapterid = $chapterid;
if( !$DB->insert_record( 'game_bookquiz_chapters', $newrec, false)){ if (!$DB->insert_record( 'game_bookquiz_chapters', $newrec, false)) {
print_object( $newrec);
print_error( "Can't insert to table game_bookquiz_chapters"); print_error( "Can't insert to table game_bookquiz_chapters");
} }
} }
//Have to go to next page.
// Have to go to next page.
$bookquiz->lastchapterid = $nextchapterid; $bookquiz->lastchapterid = $nextchapterid;
$scorequestion = 1; $scorequestion = 1;
break; break;

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

74
bookquiz/toc.php

@ -1,4 +1,18 @@
<?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.'); defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.');
@ -7,27 +21,28 @@ define('NUM_NUMBERS', '1');
define('NUM_BULLETS', '2'); define('NUM_BULLETS', '2');
define('NUM_INDENTED', '3'); 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
/* 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)
*/
/// fills: $currtitle = ''; // Active chapter title (plain text).
/// $toc $currsubtitle = ''; // Active subchapter if any.
/// $title (not for print)
$currtitle = ''; //active chapter title (plain text)
$currsubtitle = ''; //active subchapter if any
$prevtitle = '&nbsp;'; $prevtitle = '&nbsp;';
$toc = ''; //representation of toc (HTML) $toc = ''; // Representation of toc (HTML).
$nch = 0; //chapter number $nch = 0; // Chapter number.
$ns = 0; //subchapter number $ns = 0; // Subchapter number.
$title = ''; $title = '';
$first = 1; $first = 1;
@ -50,8 +65,8 @@ switch ($book->numbering) {
break; break;
} }
if ($print) {
if ($print) { ///TOC for printing // TOC for printing.
$toc .= '<a name="toc"></a>'; $toc .= '<a name="toc"></a>';
if ($book->customtitles) { if ($book->customtitles) {
$toc .= '<h1>'.get_string('toc', 'book').'</h1>'; $toc .= '<h1>'.get_string('toc', 'book').'</h1>';
@ -60,7 +75,7 @@ if ($print) { ///TOC for printing
} }
$titles = array(); $titles = array();
$toc .= '<ul>'; $toc .= '<ul>';
foreach($chapters as $ch) { foreach ($chapters as $ch) {
$title = trim(strip_tags($ch->title)); $title = trim(strip_tags($ch->title));
if (!$ch->hidden) { if (!$ch->hidden) {
if (!$ch->subchapter) { if (!$ch->subchapter) {
@ -84,9 +99,10 @@ if ($print) { ///TOC for printing
} }
} }
$toc .= '</ul></li></ul>'; $toc .= '</ul></li></ul>';
} else { //normal students view } else {
// Normal students view.
$toc .= '<font size="-1"><ul>'; $toc .= '<font size="-1"><ul>';
foreach($chapters as $ch) { foreach ($chapters as $ch) {
$title = trim(strip_tags($ch->title)); $title = trim(strip_tags($ch->title));
if (!$ch->hidden) { if (!$ch->hidden) {
if (!$ch->subchapter) { if (!$ch->subchapter) {
@ -114,10 +130,10 @@ if ($print) { ///TOC for printing
$currsubtitle = '&nbsp;'; $currsubtitle = '&nbsp;';
} }
} else { } else {
if( array_key_exists( $ch->id, $okchapters)){ if (array_key_exists( $ch->id, $okchapters)) {
$toc .= '<a title="'.htmlspecialchars($title).'" href="attempt.php?id='.$id.'&chapterid='.$ch->id.'">'.$title.'</a>'; $toc .= '<a title="'.htmlspecialchars($title).'" href="attempt.php?id='
}else $id.'&chapterid='.$ch->id.'">'.$title.'</a>';
{ } else {
$toc .= htmlspecialchars($title); $toc .= htmlspecialchars($title);
} }
} }
@ -130,6 +146,4 @@ if ($print) { ///TOC for printing
$toc .= '</div>'; $toc .= '</div>';
$toc = str_replace('<ul></ul>', '', $toc); //cleanup of invalid structures $toc = str_replace('<ul></ul>', '', $toc); // Cleanup of invalid structures.
?>

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

Loading…
Cancel
Save