Browse Source

Fix:Coding style

MOODLE_20_STABLE
Vasilis Daloukas 9 years ago
parent
commit
0751505215
  1. 13
      backup/moodle2/backup_game_activity_task.class.php
  2. 8
      backup/moodle2/backup_game_settingslib.php
  3. 52
      backup/moodle2/backup_game_stepslib.php
  4. 86
      backup/moodle2/restore_game_activity_task.class.php
  5. 34
      backup/moodle2/restore_game_stepslib.php
  6. 439
      bookquiz/importodt.php
  7. 308
      bookquiz/importppt.php
  8. 112
      bookquiz/play.php
  9. 48
      bookquiz/questions.php
  10. 68
      bookquiz/toc.php
  11. 110
      bookquiz/view.php

13
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'));
} }
@ -57,11 +56,11 @@ class backup_game_activity_task extends backup_activity_task {
$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);

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)
*/

52
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(
@ -78,11 +78,11 @@ class backup_game_activity_structure_step extends backup_activity_structure_step
$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);
} }
} }

86
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);
} }

439
bookquiz/importodt.php

@ -1,4 +1,19 @@
<?php // $Id: importodt.php,v 1.5 2012/07/25 11:16:04 bdaloukas Exp $ <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/** /**
* This is a very rough importer for odt * This is a very rough importer for odt
* *
@ -22,35 +37,36 @@
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.
if (empty($_FILES['newfile'])) {
if (empty($_FILES['newfile'])) // File was just uploaded.
{ // 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 } else {
{ // Valid file is found // Valid file is found.
if ( readdata( $course->id, 'game', $dirtemp, $r_levels, $r_titles, $r_texts, $dirfordelete)) if (readdata( $course->id, 'game', $dirtemp, $rlevels, $rtitles, $rtexts, $dirfordelete)) {
{ // first try to reall all of the data in // First try to reall all of the data in.
if ($overwrite) { if ($overwrite) {
game_bookquiz_deletebook( $course->id, $bookid); game_bookquiz_deletebook( $course->id, $bookid);
} }
$pageobjects = extract_data( $course->id, 'book', $bookid, $dirtemp, $subchapter, $r_levels, $r_titles, $r_texts); // parse all the html files into objects // Parse all the html files into objects.
clean_temp( $dirfordelete); // all done with files so dump em $pageobjects = extract_data( $course->id, 'book', $bookid, $dirtemp, $subchapter, $rlevels, $rtitles, $rtexts);
clean_temp( $dirfordelete); // All done with files so dump em.
$objects = game_bookquiz_create_objects( $pageobjects, $bookid); // function to preps the data to be sent to DB // Function to preps the data to be sent to DB.
$objects = game_bookquiz_create_objects( $pageobjects, $bookid);
if( !game_bookquiz_save_objects($objects)) if (!game_bookquiz_save_objects( $objects)) {
{ // sends it to DB // Sends it to DB.
print_error('could not save'); print_error('could not save');
} }
}else } else {
print_error('could not get data'); print_error('could not get data');
}
print_continue("{$CFG->wwwroot}/mod/game/view.php?id=$cm->id"); print_continue("{$CFG->wwwroot}/mod/game/view.php?id=$cm->id");
echo $OUTPUT->footer($course); echo $OUTPUT->footer($course);
@ -58,7 +74,7 @@
} }
} }
/// Print upload form // Print upload form.
print_heading_with_help( get_string( "bookquiz_import_odt", "game"), "importodt", "game"); print_heading_with_help( get_string( "bookquiz_import_odt", "game"), "importodt", "game");
@ -97,90 +113,84 @@
echo $OUTPUT->footer($course); echo $OUTPUT->footer($course);
// START OF FUNCTIONS // START OF FUNCTIONS.
//the r_basedir variable contains the directory where the temp files are // The rbasedir variable contains the directory where the temp files are.
//At the end the directory must be deleted // At the end the directory must be deleted.
function readdata( $courseid, $modname, &$r_basedir, &$r_levels, &$r_titles, &$r_texts, &$dirfordelete) function readdata( $courseid, $modname, &$rbasedir, &$rlevels, &$rtitles, &$rtexts, &$dirfordelete) {
{ // This function expects a odt file to be uploaded. Then it parses the content.xml to determine.
// this function expects a odt file to be uploaded. Then it parses // Then copies the images.
// the content.xml to determine.
// Then copies the image
global $CFG; global $CFG;
// create a random upload directory in temp // Create a random upload directory in temp.
$newdir = $CFG->dataroot."/temp/$modname"; $newdir = $CFG->dataroot."/temp/$modname";
if (!file_exists( $newdir)) if (!file_exists( $newdir)) {
mkdir( $newdir); mkdir( $newdir);
}
$i = 1; $i = 1;
srand((double)microtime() * 1000000); srand((double)microtime() * 1000000);
while(true) while (true) {
{ $rbasedir = "$modname/$i-".rand(0, 10000);
$r_basedir = "$modname/$i-".rand(0,10000); $newdir = $CFG->dataroot.'/temp/'.$rbasedir;
$newdir = $CFG->dataroot.'/temp/'.$r_basedir; if (!file_exists( $newdir)) {
if (!file_exists( $newdir))
{
mkdir( $newdir); mkdir( $newdir);
$newdir .= '/'; $newdir .= '/';
break; break;
} }
$i++; $i++;
} }
$dirfordelete = $r_basedir; $dirfordelete = $rbasedir;
$r_basedir .= '/'; $rbasedir .= '/';
$zipfile = $_FILES["newfile"]["name"]; $zipfile = $_FILES["newfile"]["name"];
$tempzipfile = $_FILES["newfile"]["tmp_name"]; $tempzipfile = $_FILES["newfile"]["tmp_name"];
// create our directory // Creates our directory.
$path_parts = pathinfo($zipfile); $pathparts = pathinfo($zipfile);
$dirname = substr($zipfile, 0, strpos($zipfile, '.'.$path_parts['extension'])); // take off the extension // Takes off the extension.
$dirname = substr($zipfile, 0, strpos($zipfile, '.'.$pathparts['extension']));
if (!file_exists($newdir.$dirname)) { if (!file_exists($newdir.$dirname)) {
mkdir($newdir.$dirname); mkdir($newdir.$dirname);
} }
// move our uploaded file to temp/game // Move our uploaded file to temp/game.
move_uploaded_file( $tempzipfile, $newdir.$zipfile); move_uploaded_file( $tempzipfile, $newdir.$zipfile);
//if the file ends with .lnk then use .odt instead // If the file ends with .lnk then use .odt instead.
if( substr( $zipfile, -4) == ".lnk") if (substr( $zipfile, -4) == ".lnk") {
$zipfile = substr( $zipfile, 0, -4).".odt"; $zipfile = substr( $zipfile, 0, -4).".odt";
}
// unzip it! // Unzip it!
unzip_file ( $newdir.$zipfile, $newdir.$dirname, false); unzip_file ( $newdir.$zipfile, $newdir.$dirname, false);
$r_basedir .= $dirname; // update the base $rbasedir .= $dirname; // Update the base.
$newdir .= $dirname; $newdir .= $dirname;
// 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).
$content = $newdir.'/content.xml'; $content = $newdir.'/content.xml';
$data = file_get_contents( $content); $data = file_get_contents( $content);
$content = $newdir.'/styles.xml'; $content = $newdir.'/styles.xml';
if (file_exists( $content)) { if (file_exists( $content)) {
$datastyle = file_get_contents( $content); $datastyle = file_get_contents( $content);
}else } else {
{
$datastyle = ''; $datastyle = '';
} }
oo_game_convert_ver2( $data, $datastyle, $r_levels, $r_titles, $r_texts); oo_game_convert_ver2( $data, $datastyle, $rlevels, $rtitles, $rtexts);
return true; return true;
} }
function oo_game_convert_ver2( $data, $datastyle, &$rlevels, &$rtitles, &$rtexts) {
$rlevels = array();
$rtitles = array();
$rtexts = array();
//////////////////////// // We have tables, encode it here so all <text:p in them don't get preg_match_all few lines later.
function oo_game_convert_ver2( $data, $datastyle, &$r_levels, &$r_titles, &$r_texts) if (ereg('table:table', $data)) {
{
$r_levels = array();
$r_titles = array();
$r_texts = array();
// we have tables, encode it here so all <text:p in them don't get preg_match_all few lines later
IF(ereg('table:table', $data))
{
$data = str_replace('<table:table', '<text:p text:style-name="RKRK"><table:table', $data); $data = str_replace('<table:table', '<text:p text:style-name="RKRK"><table:table', $data);
$data = str_replace('</table:table>', '</table:table></text:p>', $data); $data = str_replace('</table:table>', '</table:table></text:p>', $data);
$data = preg_replace('#<table:table(.*?)</table:table>#es', "base64_encode('\\1')", $data); $data = preg_replace('#<table:table(.*?)</table:table>#es', "base64_encode('\\1')", $data);
@ -191,65 +201,63 @@ function readdata( $courseid, $modname, &$r_basedir, &$r_levels, &$r_titles, &$r
game_bookquiz_convert_ver2_computestyles( $data, $styles, false); game_bookquiz_convert_ver2_computestyles( $data, $styles, false);
game_bookquiz_splitsections($data, $positions, $inputs, $titles, $titleframes, $texts); game_bookquiz_splitsections($data, $positions, $inputs, $titles, $titleframes, $texts);
for( $i=0; $i < count( $positions); $i++) for ($i = 0; $i < count( $positions); $i++) {
{
preg_match_all( "#text:outline-level=\"([0-9]*)\"#es", $inputs[ $i], $matches); preg_match_all( "#text:outline-level=\"([0-9]*)\"#es", $inputs[ $i], $matches);
$levels = $matches[ 1]; $levels = $matches[ 1];
if (count( $levels) > 0) { if (count( $levels) > 0) {
$level = $levels[ 0]; $level = $levels[ 0];
}else } else {
{
$level = 0; $level = 0;
} }
$r_levels[] = $level; $rlevels[] = $level;
$r_titles[] = strip_tags( $titles[ $i]); $rtitles[] = strip_tags( $titles[ $i]);
$textframe = game_bookquiz_convert($titleframes[ $i], $styles, $images); $textframe = game_bookquiz_convert($titleframes[ $i], $styles, $images);
$text = game_bookquiz_convert($texts[ $i], $styles, $images); $text = game_bookquiz_convert($texts[ $i], $styles, $images);
if ($textframe != '') { if ($textframe != '') {
$text = $textframe.'<BR>'.$text; $text = $textframe.'<br>'.$text;
} }
echo "<hr><b>".$titles[ $i]."</b><br>".$text."\r\n\r\n\r\n\r\n"; echo "<hr><b>".$titles[ $i]."</b><br>".$text."\r\n\r\n\r\n\r\n";
$r_texts[] = $text; $rtexts[] = $text;
} }
} }
function extract_data( $courseid, $modname, $id, $basedir, $subchapter, $levels, $titles, $texts) function extract_data( $courseid, $modname, $id, $basedir, $subchapter, $levels, $titles, $texts) {
{
global $CFG; global $CFG;
global $matches; global $matches;
$dirtemp = $CFG->dataroot.'/temp/'.$basedir; $dirtemp = $CFG->dataroot.'/temp/'.$basedir;
for ($i = 0; $i < count( $levels); $i++) { for ($i = 0; $i < count( $levels); $i++) {
echo $levels[ $i]." ".$titles[ $i]."<BR>"; echo $levels[ $i]." ".$titles[ $i]."<br>";
} }
$extractedpages = array(); $extractedpages = 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); make_upload_directory( $courseid.'/moddata/'.$modname, false);
make_upload_directory( $courseid.'/moddata/'.$modname."/".$id, 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."/".$id, false);
$imagedir = $CFG->dataroot.'/'.$courseid.'/moddata/'.$modname."/".$id; $imagedir = $CFG->dataroot.'/'.$courseid.'/moddata/'.$modname."/".$id;
if ($CFG->slasharguments) if ($CFG->slasharguments) {
$imagelink = $CFG->wwwroot.'/file.php/'.$courseid.'/moddata/'.$modname."/".$id; $imagelink = $CFG->wwwroot.'/file.php/'.$courseid.'/moddata/'.$modname."/".$id;
else } else {
$imagelink = $CFG->wwwroot.'/file.php?file=/'.$courseid.'/moddata/'.$modname."/".$id; $imagelink = $CFG->wwwroot.'/file.php?file=/'.$courseid.'/moddata/'.$modname."/".$id;
}
// try to make a unique subfolder to store the images // Try to make a unique subfolder to store the images.
$i = 1; $i = 1;
while(true) while (true) {
{
$newdir = $imagedir.'/'.$i; $newdir = $imagedir.'/'.$i;
if (!file_exists( $newdir)) if (!file_exists( $newdir)) {
{ // Ok doesnt exist so make the directory and update our paths.
// ok doesnt exist so make the directory and update our paths
mkdir( $newdir); mkdir( $newdir);
$imagedir = $newdir; $imagedir = $newdir;
$imagelink = $imagelink.'/'.$i; $imagelink = $imagelink.'/'.$i;
@ -258,16 +266,14 @@ function extract_data( $courseid, $modname, $id, $basedir, $subchapter, $levels,
$i++; $i++;
} }
for( $i=0; $i < count( $titles); $i++) for ($i = 0; $i < count( $titles); $i++) {
{ // Start building our page.
// start building our page
$page = new stdClass; $page = new stdClass;
$page->title = $titles[ $i]; $page->title = $titles[ $i];
$page->content = $texts[ $i]; $page->content = $texts[ $i];
//$page->source = $path_parts['basename']; // need for book only
$page->subchapter = ( $levels[ $i] >= 2); $page->subchapter = ( $levels[ $i] >= 2);
//check if the nexts are subchapters // Check if the nexts are subchapters.
for ($j = $i + 1; $j < count( $titles); $j++) { for ($j = $i + 1; $j < count( $titles); $j++) {
if ($levels[ $j] > 2) { if ($levels[ $j] > 2) {
$page->content .= '<br><b><u>'.$titles[ $j].'</u></b><br>'.$texts[ $j]; $page->content .= '<br><b><u>'.$titles[ $j].'</u></b><br>'.$texts[ $j];
@ -279,8 +285,7 @@ function extract_data( $courseid, $modname, $id, $basedir, $subchapter, $levels,
preg_match_all('#="Pictures/([a-z .A-Z_0-9]*)"#es', $page->content, $imgs); preg_match_all('#="Pictures/([a-z .A-Z_0-9]*)"#es', $page->content, $imgs);
foreach ($imgs[1] as $img) foreach ($imgs[1] as $img) {
{
$src = $dirtemp.'/Pictures/'.$img; $src = $dirtemp.'/Pictures/'.$img;
$dest = $imagedir.'/'.$img; $dest = $imagedir.'/'.$img;
rename( $src, $dest); rename( $src, $dest);
@ -288,63 +293,56 @@ function extract_data( $courseid, $modname, $id, $basedir, $subchapter, $levels,
$page->content = str_replace( "Pictures/$img", $imagelink."/".$img, $page->content); $page->content = str_replace( "Pictures/$img", $imagelink."/".$img, $page->content);
} }
// add the page to the array; // Add the page to the array.
$extractedpages[] = $page; $extractedpages[] = $page;
} // End $pages foreach loop.
} // end $pages foreach loop
return $extractedpages; return $extractedpages;
} }
/** /*
Clean up the temp directory Clean up the temp directory
*/ */
function clean_temp( $base) function clean_temp( $base) {
{
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.
$dir = $CFG->dataroot.'/temp/'.$base; $dir = $CFG->dataroot.'/temp/'.$base;
remove_dir( $dir); remove_dir( $dir);
//game_full_rmdir( $dir);
} }
/*
/**
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 game_bookquiz_create_objects( $pageobjects, $bookid) {
function game_bookquiz_create_objects( $pageobjects, $bookid)
{
global $DB; global $DB;
$chapters = array(); $chapters = array();
$lastpagenum = $DB->get_field('book_chapters', 'MAX(pagenum) as num', array( 'bookid' => $bookid)); $lastpagenum = $DB->get_field('book_chapters', 'MAX(pagenum) as num', array( 'bookid' => $bookid));
foreach ($pageobjects as $pageobject) foreach ($pageobjects as $pageobject) {
{
$chapter = new stdClass; $chapter = new stdClass;
// same for all chapters // Same for all chapters.
$chapter->bookid = $bookid; $chapter->bookid = $bookid;
$chapter->pagenum = ++$lastpagenum; $chapter->pagenum = ++$lastpagenum;
$chapter->timecreated = time(); $chapter->timecreated = time();
$chapter->timemodified = time(); $chapter->timemodified = time();
$chapter->subchapter = 0; $chapter->subchapter = 0;
if ($pageobject->title == '') if ($pageobject->title == '') {
$chapter->title = "Page $count"; // no title set so make a generic one $chapter->title = "Page $count"; // No title set so make a generic one.
else } else {
$chapter->title = addslashes($pageobject->title); $chapter->title = addslashes($pageobject->title);
}
$chapter->subchapter = $pageobject->subchapter; $chapter->subchapter = $pageobject->subchapter;
$content = str_replace("\n", '', $pageobject->content); $content = str_replace("\n", '', $pageobject->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>';
$chapter->content = addslashes( $content); $chapter->content = addslashes( $content);
@ -355,16 +353,12 @@ function game_bookquiz_create_objects( $pageobjects, $bookid)
return $chapters; return $chapters;
} }
/** // Save the chapter objects to the database.
Save the chapter objects to the database function game_bookquiz_save_objects($chapters) {
*/
function game_bookquiz_save_objects($chapters)
{
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 (!$newid = $DB->insert_record('book_chapters', $chapter)) { if (!$newid = $DB->insert_record('book_chapters', $chapter)) {
print_error('Could not insert to table book_chapters'); print_error('Could not insert to table book_chapters');
} }
@ -373,9 +367,8 @@ function game_bookquiz_save_objects($chapters)
return true; return true;
} }
//splits the data to // Splits the data to.
function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$titleframes, &$texts) function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$titleframes, &$texts) {
{
preg_match_all('#<text:h (.*?)>(.*?)</text:h>#es', $data, $matches, PREG_OFFSET_CAPTURE); preg_match_all('#<text:h (.*?)>(.*?)</text:h>#es', $data, $matches, PREG_OFFSET_CAPTURE);
$in = $matches[ 1]; $in = $matches[ 1];
@ -387,8 +380,7 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
$oldposition = 0; $oldposition = 0;
$oldlen = 0; $oldlen = 0;
for($i=0; $i < count( $in); $i++) for ($i = 0; $i < count( $in); $i++) {
{
$inputs[] = $in[ $i][ 0]; $inputs[] = $in[ $i][ 0];
$newposition = $in[ $i][ 1]; $newposition = $in[ $i][ 1];
@ -397,12 +389,11 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
$titlenet = $title[ $i][ 0]; $titlenet = $title[ $i][ 0];
$titleframe = ''; $titleframe = '';
//frames inside header // Frames inside header.
preg_match_all('#<draw:frame (.*?)>(.*?)</draw:frame>#es', $titlenet, $titlematches, PREG_OFFSET_CAPTURE); preg_match_all('#<draw:frame (.*?)>(.*?)</draw:frame>#es', $titlenet, $titlematches, PREG_OFFSET_CAPTURE);
$frames = $titlematches[ 2]; $frames = $titlematches[ 2];
if (count( $frames) > 0) { if (count( $frames) > 0) {
for($j=0; $j < count( $frames); $j++) for ($j = 0; $j < count( $frames); $j++) {
{
$titleframe .= $frames[ $j][ 0]; $titleframe .= $frames[ $j][ 0];
$titlenet = substr( $titlenet, $frames[ $j][ 1] + strlen( $frames[ $j][ 0]) + 13); $titlenet = substr( $titlenet, $frames[ $j][ 1] + strlen( $frames[ $j][ 0]) + 13);
} }
@ -417,51 +408,45 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
$oldlen = strlen( $title[ $i][ 0]) + strlen( $in[ $i][ 0]) + 10; $oldlen = strlen( $title[ $i][ 0]) + strlen( $in[ $i][ 0]) + 10;
$oldposition = $newposition; $oldposition = $newposition;
} }
$newposition = strlen( $data); $newposition = strlen( $data);
$texts[] = substr( $data, $oldposition + $oldlen, $newposition - $oldposition - $oldlen); $texts[] = substr( $data, $oldposition + $oldlen, $newposition - $oldposition - $oldlen);
} }
function game_bookquiz_convert( $data, $styles, &$images) function game_bookquiz_convert( $data, $styles, &$images) {
{
$images = array(); $images = array();
// get data // Get data.
preg_match_all('#<text:p text:style-name="([a-z A-Z_0-9]*)">(.*?)</text:p>#es', $data, $text); preg_match_all('#<text:p text:style-name="([a-z A-Z_0-9]*)">(.*?)</text:p>#es', $data, $text);
$originals = $text[ 0]; $originals = $text[ 0];
$names = $text[ 1]; $names = $text[ 1];
$texts = $text[ 2]; $texts = $text[ 2];
for( $i=0; $i < count( $texts); $i++) for ($i = 0; $i < count( $texts); $i++) {
{
$name = $names[ $i]; $name = $names[ $i];
$text = $texts[ $i]; $text = $texts[ $i];
//repairs draw:frame // Repairs draw:frame.
$pattern = "#<draw:frame draw:style-name=\"([a-z .A-Z_0-9]*)\" (.*?)<draw:image xlink:href=\"Pictures/([a-z .A-Z_0-9]*)(.*?)</draw:frame>#es"; $pattern = "#<draw:frame draw:style-name=\"([a-z .A-Z_0-9]*)\" (.*?)<draw:image xlink:href=\"Pictures/([a-z .A-Z_0-9]*)(.*?)</draw:frame>#es";
preg_match_all( $pattern, $text, $matches); preg_match_all( $pattern, $text, $matches);
if (count( $matches[ 1]) ) { if (count( $matches[ 1]) ) {
$new = game_bookquiz_convert_image( $matches, $styles, $images); $new = game_bookquiz_convert_image( $matches, $styles, $images);
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
}else IF($name == 'RKRK') } else if ($name == 'RKRK') {
{
$new = game_bookquiz_convert_RKRK( $text); $new = game_bookquiz_convert_RKRK( $text);
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
}else } else {
{
$new = '<P>'.game_bookquiz_convert_text( $text, $styles).'</P>'; $new = '<P>'.game_bookquiz_convert_text( $text, $styles).'</P>';
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
} }
} }
// repairs text:span text:style-name // Repairs text:span text:style-name.
preg_match_all( '#<text:span text:style-name="([a-z .A-Z_0-9]*)">(.*?)</text:span>#es', $data, $text); preg_match_all( '#<text:span text:style-name="([a-z .A-Z_0-9]*)">(.*?)</text:span>#es', $data, $text);
$originals = $text[ 0]; $originals = $text[ 0];
$names = $text[ 1]; $names = $text[ 1];
$texts = $text[ 2]; $texts = $text[ 2];
for( $i=0; $i < count( $texts); $i++) for ($i = 0; $i < count( $texts); $i++) {
{
$name = $names[ $i]; $name = $names[ $i];
$text = $texts[ $i]; $text = $texts[ $i];
@ -470,24 +455,21 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
if (count( $matches[ 1]) ) { if (count( $matches[ 1]) ) {
$new = game_bookquiz_convert_image( $matches, $styles, $images); $new = game_bookquiz_convert_image( $matches, $styles, $images);
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
}else IF($name == 'RKRK') } else if ($name == 'RKRK') {
{
$new = game_bookquiz_convert_RKRK( $text); $new = game_bookquiz_convert_RKRK( $text);
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
}else } else {
{
$new = "<span ".$styles[ $name].'>'.game_bookquiz_convert_text( $text, $styles).'</span>'; $new = "<span ".$styles[ $name].'>'.game_bookquiz_convert_text( $text, $styles).'</span>';
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
} }
} }
// repairs text:a // Repairs text:a.
preg_match_all( '#<text:a (.*?) xlink:href="(.*?)">(.*?)</text:a>#es', $data, $text); preg_match_all( '#<text:a (.*?) xlink:href="(.*?)">(.*?)</text:a>#es', $data, $text);
$originals = $text[ 0]; $originals = $text[ 0];
$hrefs = $text[ 2]; $hrefs = $text[ 2];
$texts = $text[ 3]; $texts = $text[ 3];
for( $i=0; $i < count( $texts); $i++) for ($i = 0; $i < count( $texts); $i++) {
{
$href = $hrefs[ $i]; $href = $hrefs[ $i];
$text = $texts[ $i]; $text = $texts[ $i];
@ -495,37 +477,32 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
} }
//repair text:list // Repair text:list.
preg_match_all( '#<text:list text:style-name="([a-z A-Z_0-9]*)">(.*?)</text:list>#es', $data, $text); preg_match_all( '#<text:list text:style-name="([a-z A-Z_0-9]*)">(.*?)</text:list>#es', $data, $text);
$originals = $text[ 0]; $originals = $text[ 0];
$names = $text[ 1]; $names = $text[ 1];
$texts = $text[ 2]; $texts = $text[ 2];
for( $i=0; $i < count( $texts); $i++) for ($i = 0; $i < count( $texts); $i++) {
{
$new = '<UL>'.$texts[ $i].'</UL>'; $new = '<UL>'.$texts[ $i].'</UL>';
$data = str_replace( $originals[ $i], $new, $data); $data = str_replace( $originals[ $i], $new, $data);
//I have to repair the listitems // I have to repair the listitems.
preg_match_all( '#<text:list-item>(.*?)</text:list-item>#es', $data, $listitems); preg_match_all( '#<text:list-item>(.*?)</text:list-item>#es', $data, $listitems);
$originallistitems = $listitems[ 0]; $originallistitems = $listitems[ 0];
$items = $listitems[ 1]; $items = $listitems[ 1];
for ($j = 0; $j < count( $items); $j++) { for ($j = 0; $j < count( $items); $j++) {
$new = '<LI>'.$items[ $j]; $new = '<LI>'.$items[ $j];
$data = str_replace( $originallistitems[ $j], $new, $data); $data = str_replace( $originallistitems[ $j], $new, $data);
} }
} }
$data = str_replace( '<text:line-break/>', '<br>', $data); $data = str_replace( '<text:line-break/>', '<br>', $data);
return $data; return $data;
} }
function game_bookquiz_convert_text( $text, $styles) function game_bookquiz_convert_text( $text, $styles) {
{
$pattern = "#<text:span text:style-name=\"([a-z .A-Z_0-9]*)\">(.*?)</text:span>#es"; $pattern = "#<text:span text:style-name=\"([a-z .A-Z_0-9]*)\">(.*?)</text:span>#es";
preg_match_all( $pattern, $text, $matches); preg_match_all( $pattern, $text, $matches);
@ -533,8 +510,7 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
$names = $matches[ 1]; $names = $matches[ 1];
$spantexts = $matches[ 2]; $spantexts = $matches[ 2];
for( $i=0; $i < count( $names); $i++) for ($i = 0; $i < count( $names); $i++) {
{
$name = $names[ $i]; $name = $names[ $i];
$style = $styles[ $name]; $style = $styles[ $name];
@ -545,8 +521,7 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
return $text; return $text;
} }
function game_bookquiz_convert_image( $matches, $xmlstyles, &$images) function game_bookquiz_convert_image( $matches, $xmlstyles, &$images) {
{
$ret = ''; $ret = '';
$styles = $matches[ 1]; $styles = $matches[ 1];
@ -562,134 +537,46 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
return $ret; return $ret;
} }
function game_bookquiz_convert_RKRK( $text) function game_bookquiz_convert_rkrk( $text) {
{
$table = base64_decode($text); $table = base64_decode($text);
$table = stripslashes($table); $table = stripslashes($table);
$table = strtr($table, array('</table:table>' => '</table>', '<table:table-row>' => '<tr>', '</table:table-row>' => '</tr>', '</table:table-cell>' => '</td>', '</table:table-header-rows>' => '', '<table:table-header-rows>' => '', '>' => ">\n", '</text:p>' => '')); $table = strtr($table, array('</table:table>' => '</table>', '<table:table-row>' => '<tr>', '</table:table-row>' => '</tr>', '</table:table-cell>' => '</td>', '</table:table-header-rows>' => '', '<table:table-header-rows>' => '', '>' => ">\n", '</text:p>' => ''));
//preg_match_all('#table:name="([a-z A-Z_0-9]*)" table:style-name="([a-z A-Z_0-9]*)">#es', $table, $repl);
preg_match_all('#table:name="(.*?)" table:style-name="(.*?)">#es', $table, $repl); preg_match_all('#table:name="(.*?)" table:style-name="(.*?)">#es', $table, $repl);
foreach($repl[0] as $val) foreach ($repl[0] as $val) {
{
//$table = str_replace($val, '<table border="1"><tr><td>', $table);
$table = str_replace($val, '<table border="1"><tr>', $table); $table = str_replace($val, '<table border="1"><tr>', $table);
} }
//preg_match_all('#<text:p text:style-name="([a-z A-Z_0-9]*)">#es', $table, $repl);
preg_match_all('#<text:p text:style-name="(.*?)">#es', $table, $repl); preg_match_all('#<text:p text:style-name="(.*?)">#es', $table, $repl);
foreach($repl[0] as $key => $val) foreach ($repl[0] as $key => $val) {
{
$table = str_replace($val, '', $table); $table = str_replace($val, '', $table);
} }
preg_match_all('#<table:table-column (.*?)">#es', $table, $repl); preg_match_all('#<table:table-column (.*?)">#es', $table, $repl);
foreach($repl[0] as $val) foreach ($repl[0] as $val) {
{
$table = str_replace($val, '', $table); $table = str_replace($val, '', $table);
} }
//preg_match_all('#<table:table-cell table:style-name="([\.a-z A-Z_0-9]*)" office:value-type="([a-z A-Z_0-9]*)">#es', $table, $repl);
preg_match_all('#<table:table-cell table:style-name="(.*?)" office:value-type=(.*?)">#es', $table, $repl); preg_match_all('#<table:table-cell table:style-name="(.*?)" office:value-type=(.*?)">#es', $table, $repl);
foreach($repl[0] as $val) foreach ($repl[0] as $val) {
{
$table = str_replace($val, '<td>', $table); $table = str_replace($val, '<td>', $table);
} }
//maybe there are a lot of pictures inside a table
// Maybe there are a lot of pictures inside a table.
preg_match_all('#xlink:href="Pictures/([a-z.A-Z_0-9]*)"#es', $table, $repl); preg_match_all('#xlink:href="Pictures/([a-z.A-Z_0-9]*)"#es', $table, $repl);
foreach( $repl[ 1] as $picture) foreach ($repl[ 1] as $picture) {
{
$table = str_replace('<draw:image xlink:href="Pictures/'.$picture.'" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>', '<img src="Pictures/'.$picture.'">', $table); $table = str_replace('<draw:image xlink:href="Pictures/'.$picture.'" xlink:type="simple" xlink:show="embed" xlink:actuate="onLoad"/>', '<img src="Pictures/'.$picture.'">', $table);
} }
if( strpos( $table,"</table>") === false) if (strpos( $table, "</table>") === false) {
$table .= "</table>"; $table .= "</table>";
}
$ret = '<BR>'.$table.'<BR>'; $ret = '<BR>'.$table.'<BR>';
return $ret; return $ret;
} }
/*
function game_bookquiz_oo_unzip($file, $dir)
{
unzip_file ( $file, $dir, false);
$dir .= '/';
if( file_exists( $dir.'content.xml')){
$content = file_get_contents( $dir.'content.xml');
}else
{
$content = '';
}
if( file_exists( $dir.'styles.xml')){
$contentstyles = file_get_contents( $dir.'styles.xml');
}else
{
$contentstyles = '';
}
$img = array();
$handle = opendir($dir.'Pictures');
while (false!==($item = readdir($handle))) {
if($item != '.' && $item != '..') {
if(!is_dir($dir.'/'.$item)) {
$img[ $item] = file_get_contents( $dir.'/'.$item);
}else{
unlink($dir.'/'.$item);
}
}
}
}
*/
function old_game_bookquiz_oo_unzip($file, $save, $dir)
{
IF($zip = game_zip_open($file))
{
while ($zip_entry = game_zip_read($zip))
{
$filename = game_zip_entry_name($zip_entry);
IF($filename == 'content.xml' and game_zip_entry_open($zip, $zip_entry, "r"))
{
$content = game_zip_entry_read($zip_entry, game_zip_entry_filesize($zip_entry));
game_zip_entry_close($zip_entry);
}
IF( $filename == 'styles.xml' and game_zip_entry_open($zip, $zip_entry, "r"))
{
$contentstyles = game_zip_entry_read($zip_entry, game_zip_entry_filesize($zip_entry));
game_zip_entry_close($zip_entry);
}
IF(ereg('Pictures/', $filename) and !ereg('Object', $filename) and game_zip_entry_open($zip, $zip_entry, "r")) function game_bookquiz_deletebook( $courseid, $bookid) {
{
$img[$filename] = game_zip_entry_read($zip_entry, game_zip_entry_filesize($zip_entry));
game_zip_entry_close($zip_entry);
}
}
IF(isset($content))
{
IF($save == false)
return array($content, $img);
else
{
file_put_contents("$dir/content.xml", $content);
IF(isset($contentstyles)){
file_put_contents("$dir/styles.xml", $contentstyles);
}
IF(is_array($img))
{
IF(!is_dir("$dir/Pictures"))
mkdir( "$dir/Pictures");
foreach($img as $key => $val)
file_put_contents("$dir/$key", $val);
}
}
}
}
}
function game_bookquiz_deletebook( $courseid, $bookid)
{
global $CFG; global $CFG;
if (!delete_records( 'book_chapters', 'bookid', $bookid)) { if (!delete_records( 'book_chapters', 'bookid', $bookid)) {
@ -697,11 +584,9 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
} }
game_full_rmdir( "$CFG->dataroot/$courseid/moddata/book/$bookid"); game_full_rmdir( "$CFG->dataroot/$courseid/moddata/book/$bookid");
} }
function game_bookquiz_convert_ver2_computestyles( $data, &$styles, $isstyle) function game_bookquiz_convert_ver2_computestyles( $data, &$styles, $isstyle) {
{
preg_match_all('#<style:style style:name="(.*?)"(.*?)>(.*?)</style:style>#es', $data, $style); preg_match_all('#<style:style style:name="(.*?)"(.*?)>(.*?)</style:style>#es', $data, $style);
$stylenames = $style[ 1]; $stylenames = $style[ 1];
@ -720,15 +605,17 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
if ($pos1 > $pos2) { if ($pos1 > $pos2) {
break; break;
} }
//is a parent style
// Is a parent style.
$s = substr( $styledatas[ $i], 0, $pos2 + 2); $s = substr( $styledatas[ $i], 0, $pos2 + 2);
game_bookquiz_convertstyle_parent( $s, $styles); game_bookquiz_convertstyle_parent( $s, $styles);
$styledatas[ $i] = substr( $styledatas[ $i], $pos2 + 2); $styledatas[ $i] = substr( $styledatas[ $i], $pos2 + 2);
$change = true; $change = true;
} }
if ($change) { if ($change) {
//Must to recompute name, styledatas, styleinfos // Must to recompute name, styledatas, styleinfos.
preg_match_all('#<style:style style:name="(.*?)"(.*?)>(.*?)</style:style>#es', $data, $style); preg_match_all('#<style:style style:name="(.*?)"(.*?)>(.*?)</style:style>#es', $data, $style);
$name = $style[ 1][ 0]; $name = $style[ 1][ 0];
$styleinfos[ $i] = $style[ 2][ 0]; $styleinfos[ $i] = $style[ 2][ 0];
@ -739,8 +626,7 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
} }
} }
function game_bookquiz_convertstyle_parent( $data, &$styles) function game_bookquiz_convertstyle_parent( $data, &$styles) {
{
$styleitems = array(); $styleitems = array();
preg_match_all( '#(.*?)style:name="(.*?)"(.*?)style:parent-style-name="(.*?)"(.*?)#es', $data, $infos); preg_match_all( '#(.*?)style:name="(.*?)"(.*?)style:parent-style-name="(.*?)"(.*?)#es', $data, $infos);
@ -748,7 +634,7 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
$parents = $infos[ 4]; $parents = $infos[ 4];
if (count( $parents)) { if (count( $parents)) {
if (array_key_exists( $parents[ 0], $styles)) { if (array_key_exists( $parents[ 0], $styles)) {
//is a child style. Must to copy the properties of the parent style // Is a child style. Must to copy the properties of the parent style.
$a = explode( ';', $styles[ $parents[ 0]]); $a = explode( ';', $styles[ $parents[ 0]]);
foreach ($a as $s) { foreach ($a as $s) {
$pos = strpos( $s, ':'); $pos = strpos( $s, ':');
@ -767,17 +653,17 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
foreach ($styleitems as $key => $item) { foreach ($styleitems as $key => $item) {
$style .= ';'.$key.':'.$item; $style .= ';'.$key.':'.$item;
} }
$styles[ $name] = substr( $style, 1); $styles[ $name] = substr( $style, 1);
} }
function game_bookquiz_convertstyle( $data, $styleinfo, $styles) function game_bookquiz_convertstyle( $data, $styleinfo, $styles) {
{
$styleitems = array(); $styleitems = array();
preg_match_all( '#<style:paragraph-properties (.*?)/>#es', $data, $infos); preg_match_all( '#<style:paragraph-properties (.*?)/>#es', $data, $infos);
$lines = $infos[ 1]; $lines = $infos[ 1];
if (count( $lines)) { if (count( $lines)) {
$line = $lines[ 0]; //print_object( $lines); $line = $lines[ 0];
if ($line != '') { if ($line != '') {
game_bookquiz_convertstyle_paragraph( $line, $styleitems); game_bookquiz_convertstyle_paragraph( $line, $styleitems);
@ -806,8 +692,7 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
return substr( $style, 1); return substr( $style, 1);
} }
function game_bookquiz_convertstyle_paragraph( $line, &$styleitems) function game_bookquiz_convertstyle_paragraph( $line, &$styleitems) {
{
preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas); preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas);
$data1 = $datas[ 1]; $data1 = $datas[ 1];
$data2 = $datas[ 2]; $data2 = $datas[ 2];
@ -824,7 +709,6 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
switch ($eq1) { switch ($eq1) {
case 'fo:text-align': case 'fo:text-align':
$styleitems[ 'align'] = $eq2; $styleitems[ 'align'] = $eq2;
//print_object( $styleitems);
break; break;
case 'fo:background-color': case 'fo:background-color':
$styleitems[ 'background-color'] = $eq2; $styleitems[ 'background-color'] = $eq2;
@ -833,8 +717,7 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t
} }
} }
function game_bookquiz_convertstyle_textproperties( $line, &$styleitems) function game_bookquiz_convertstyle_textproperties( $line, &$styleitems) {
{
preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas); preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas);
$data1 = $datas[ 1]; $data1 = $datas[ 1];
$data2 = $datas[ 2]; $data2 = $datas[ 2];

308
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
@ -16,8 +31,8 @@
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)) {
@ -28,7 +43,7 @@
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');
} }
@ -44,30 +59,33 @@
$strimportppt = get_string("importppt", "lesson"); $strimportppt = get_string("importppt", "lesson");
$strlessons = get_string("modulenameplural", "lesson"); $strlessons = get_string("modulenameplural", "lesson");
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"); echo $OUTPUT->heading("$strimportppt", " $strimportppt",
"<a href=\"index.php?id=$course->id\">$strlessons</a>".
if ($form = data_submitted()) { /// Filename " -> <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 {
@ -81,8 +99,7 @@
} }
} }
/// Print upload form // Print upload form.
print_heading_with_help($strimportppt, "importppt", "lesson"); print_heading_with_help($strimportppt, "importppt", "lesson");
echo $OUTPUT->box_start('center'); echo $OUTPUT->box_start('center');
@ -105,16 +122,17 @@
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,26 +400,21 @@ 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();
@ -407,13 +423,13 @@ function book_create_objects($pageobjects, $bookid) {
$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');

112
bookquiz/play.php

@ -1,7 +1,20 @@
<?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
// 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) { 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);
} }
@ -22,8 +35,7 @@ function game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $chapterid, $c
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) {
@ -35,8 +47,7 @@ function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $conte
} }
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");
} }
@ -52,12 +63,12 @@ function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $conte
$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) {
@ -71,17 +82,15 @@ function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $conte
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;
@ -110,9 +119,10 @@ if( 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.
'&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="" />';
} }
@ -120,7 +130,9 @@ if ($previd) {
$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";
@ -133,10 +145,10 @@ if ($nextid) {
} 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">
@ -209,7 +223,7 @@ $tocwidth = '10%';
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>
@ -218,17 +232,16 @@ $tocwidth = '10%';
<?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');
} }
@ -238,16 +251,16 @@ function game_bookquiz_play_computelastchapter( $game, &$bookquiz)
$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\" ".
" onclick=\"this.autocomplete='off'\">\n";
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";
} }
// 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,9 +284,9 @@ 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;
@ -281,7 +295,7 @@ function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapter
} }
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";
@ -290,8 +304,7 @@ function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapter
echo "</form>\n"; echo "</form>\n";
} }
function game_bookquiz_selectrandomquestion( $questions) function game_bookquiz_selectrandomquestion( $questions) {
{
global $DB; global $DB;
$categorylist = ''; $categorylist = '';
@ -313,14 +326,12 @@ function game_bookquiz_selectrandomquestion( $questions)
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);
@ -339,7 +350,7 @@ function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $contex
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];
@ -347,17 +358,16 @@ function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $contex
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;

48
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
* *
@ -16,16 +31,12 @@
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 // Print upload form.
$OUTPUT->heading( $course->fullname); $OUTPUT->heading( $course->fullname);
$select = "gameid={$game->id}"; $select = "gameid={$game->id}";
@ -70,24 +81,23 @@
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>';
@ -113,13 +123,13 @@
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',
array( 'gameid' => $gameid), '', 'id,chapterid,questioncategoryid')) != false) {
foreach ($recs as $rec) { foreach ($recs as $rec) {
$questions[ $rec->chapterid] = $rec->questioncategoryid; $questions[ $rec->chapterid] = $rec->questioncategoryid;
$recids[ $rec->chapterid] = $rec->id; $recids[ $rec->chapterid] = $rec->id;
@ -131,7 +141,6 @@ function game_bookquiz_save( $gameid, $bookid, $ids, $form)
$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;
} }
@ -142,7 +151,6 @@ function game_bookquiz_save( $gameid, $bookid, $ids, $form)
$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;
@ -158,13 +166,11 @@ function game_bookquiz_save( $gameid, $bookid, $ids, $form)
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");
} }
} }

68
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>';
@ -84,7 +99,8 @@ 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));
@ -115,9 +131,9 @@ if ($print) { ///TOC for printing
} }
} 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.
?>

110
bookquiz/view.php

@ -1,15 +1,30 @@
<?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');
} }
@ -26,12 +41,13 @@ 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') {
// Go to first chapter if no given.
foreach ($chapters as $ch) { foreach ($chapters as $ch) {
if ($allowedit) { if ($allowedit) {
$chapterid = $ch->id; $chapterid = $ch->id;
@ -44,49 +60,45 @@ 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;
@ -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.
// Book display HTML code '" 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
* =====================================================
*/
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">
@ -181,6 +208,7 @@ echo "OK";
$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 = new object();
@ -189,7 +217,7 @@ echo "OK";
echo format_text($content, FORMAT_HTML, $nocleanoption, $course->id); echo format_text($content, FORMAT_HTML, $nocleanoption, $course->id);
echo '</div>'; echo '</div>';
echo $OUTPUT->box_end(); echo $OUTPUT->box_end();
/// lower navigation // Lower navigation.
echo '<p>'.$chnavigation.'</p>'; echo '<p>'.$chnavigation.'</p>';
?> ?>
</td> </td>
@ -198,5 +226,3 @@ echo "OK";
<?php <?php
echo $OUTPUT->footer($course); echo $OUTPUT->footer($course);
?>

Loading…
Cancel
Save