diff --git a/backup/moodle2/backup_game_activity_task.class.php b/backup/moodle2/backup_game_activity_task.class.php index 05e8729..3e095ab 100755 --- a/backup/moodle2/backup_game_activity_task.class.php +++ b/backup/moodle2/backup_game_activity_task.class.php @@ -1,5 +1,4 @@ dirroot . '/mod/game/backup/moodle2/backup_game_stepslib.php'); // Because it exists (must) -require_once($CFG->dirroot . '/mod/game/backup/moodle2/backup_game_settingslib.php'); // Because it exists (optional) - + +require_once($CFG->dirroot . '/mod/game/backup/moodle2/backup_game_stepslib.php'); // Because it exists (must). +require_once($CFG->dirroot . '/mod/game/backup/moodle2/backup_game_settingslib.php'); // Because it exists (optional). + /** * game backup task that provides all the settings and steps to perform one * complete backup of the activity @@ -37,34 +36,34 @@ class backup_game_activity_task extends backup_activity_task { * Define (add) particular settings this activity can have */ protected function define_my_settings() { - // No particular settings for this activity + // No particular settings for this activity. } /** * Define (add) particular steps this activity can have */ protected function define_my_steps() { - // Game only has one structure step - $this->add_step(new backup_game_activity_structure_step('game_structure', 'game.xml')); + // Game only has one structure step. + $this->add_step(new backup_game_activity_structure_step('game_structure', 'game.xml')); } - + /** * Code the transformations to perform in the activity in * order to get transportable (encoded) links */ static public function encode_content_links($content) { global $CFG; - - $base = preg_quote($CFG->wwwroot,"/"); - - // Link to the list of gamess - $search="/(".$base."\/mod\/game\/index.php\?id\=)([0-9]+)/"; - $content= preg_replace($search, '$@GAMEINDEX*$2@$', $content); - - // Link to game view by moduleid - $search="/(".$base."\/mod\/game\/view.php\?id\=)([0-9]+)/"; - $content= preg_replace($search, '$@GAMEVIEWBYID*$2@$', $content); - + + $base = preg_quote($CFG->wwwroot, "/"); + + // Link to the list of games. + $search = "/(".$base."\/mod\/game\/index.php\?id\=)([0-9]+)/"; + $content = preg_replace($search, '$@GAMEINDEX*$2@$', $content); + + // Link to game view by moduleid. + $search = "/(".$base."\/mod\/game\/view.php\?id\=)([0-9]+)/"; + $content = preg_replace($search, '$@GAMEVIEWBYID*$2@$', $content); + return $content; } } diff --git a/backup/moodle2/backup_game_settingslib.php b/backup/moodle2/backup_game_settingslib.php index ab78ff4..998e8ae 100755 --- a/backup/moodle2/backup_game_settingslib.php +++ b/backup/moodle2/backup_game_settingslib.php @@ -1,5 +1,4 @@ . - + /** * @package moodlecore * @subpackage backup-moodle2 * @copyright 2010 onwards YOUR_NAME_GOES_HERE {@link YOUR_URL_GOES_HERE} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ - - // This activity has not particular settings but the inherited from the generic - // backup_activity_task so here there isn't any class definition, like the ones - // existing in /backup/moodle2/backup_settingslib.php (activities section) + +/** This activity has not particular settings but the inherited from the generic + * backup_activity_task so here there isn't any class definition, like the ones + * existing in /backup/moodle2/backup_settingslib.php (activities section) + */ diff --git a/backup/moodle2/backup_game_stepslib.php b/backup/moodle2/backup_game_stepslib.php index 032ab7d..5ea4205 100755 --- a/backup/moodle2/backup_game_stepslib.php +++ b/backup/moodle2/backup_game_stepslib.php @@ -1,5 +1,4 @@ get_setting_value('userinfo'); - // Define each element separated + // Define each element separated. $game = new backup_nested_element('game', array('id'), array( 'name', 'sourcemodule', 'timeopen', 'timeclose', 'quizid', 'glossaryid', 'glossarycategoryid', 'questioncategoryid', 'bookid', @@ -45,16 +44,17 @@ class backup_game_activity_structure_step extends backup_activity_structure_step 'shuffle', 'timemodified', 'toptext', 'bottomtext', 'grademethod', 'grade', 'decimalpoints', 'popup', 'review', 'attempts', 'glossaryid2', 'glossarycategoryid2', - 'language', 'subcategories', 'maxattempts' + 'language', 'subcategories', 'maxattempts' )); - + $exporthtmls = new backup_nested_element('game_export_htmls'); $exporthtml = new backup_nested_element('game_export_html', array('id'), array( - 'filename', 'title', 'checkbutton', 'printbutton', 'inputsize', 'maxpicturewidth', 'maxpictureheight')); + 'filename', 'title', 'checkbutton', 'printbutton', 'inputsize', 'maxpicturewidth', 'maxpictureheight')); $exportjavames = new backup_nested_element('game_export_javames'); $exportjavame = new backup_nested_element('game_export_javame', array('id'), array( - 'filename', 'icon', 'createdby', 'vendor', 'name', 'description', 'version', 'maxpicturewidth', 'maxpictureheight')); + 'filename', 'icon', 'createdby', 'vendor', 'name', 'description', 'version', + 'maxpicturewidth', 'maxpictureheight')); $grades = new backup_nested_element('game_grades'); $grade = new backup_nested_element('game_grade', array('id'), array( @@ -63,122 +63,122 @@ class backup_game_activity_structure_step extends backup_activity_structure_step $repetitions = new backup_nested_element('game_repetitions'); $repetition = new backup_nested_element('game_repetition', array('id'), array( 'userid', 'questionid', 'glossaryentryid', 'repetitions')); - - $attempts = new backup_nested_element('game_attempts'); + + $attempts = new backup_nested_element('game_attempts'); $attempt = new backup_nested_element('game_attempt', array('id'), array( - 'userid', 'timestart','timefinish', 'timelastattempt', 'lastip', - 'lastremotehost', 'preview', 'attempt','score', 'attempts', 'language')); + 'userid', 'timestart', 'timefinish', 'timelastattempt', 'lastip', + 'lastremotehost', 'preview', 'attempt', 'score', 'attempts', 'language')); $querys = new backup_nested_element('game_queries'); $query = new backup_nested_element('game_query', array('id'), array( - 'gamekind', 'userid','sourcemodule', 'questionid', 'glossaryentryid', - 'questiontext', 'score', 'timelastattempt','studentanswer', 'col', 'row', + 'gamekind', 'userid', 'sourcemodule', 'questionid', 'glossaryentryid', + 'questiontext', 'score', 'timelastattempt', 'studentanswer', 'col', 'row', 'horizontal', 'answertext', 'correct', 'attachment', 'answerid', 'tries')); - $bookquizs = new backup_nested_element('game_bookquizs'); + $bookquizs = new backup_nested_element('game_bookquizs'); $bookquiz = new backup_nested_element('game_bookquiz', array('id'), array('lastchapterid')); - $bookquiz_chapters = new backup_nested_element('game_bookquiz_chapters'); - $bookquiz_chapter = new backup_nested_element('game_bookquiz_chapter', array('id'), array( 'chapterid')); - - $bookquiz_questions = new backup_nested_element('game_bookquiz_questions'); - $bookquiz_question = new backup_nested_element('game_bookquiz_question', array('id'), array( + $bookquizchapters = new backup_nested_element('game_bookquiz_chapters'); + $bookquizchapter = new backup_nested_element('game_bookquiz_chapter', array('id'), array( 'chapterid')); + + $bookquizquestions = new backup_nested_element('game_bookquiz_questions'); + $bookquizquestion = new backup_nested_element('game_bookquiz_question', array('id'), array( 'chapterid', 'questioncategoryid')); - $crosss = new backup_nested_element('game_crosss'); + $crosss = new backup_nested_element('game_crosss'); $cross = new backup_nested_element('game_cross', array('id'), array( - 'cols', 'rows', 'words', 'wordsall', 'createscore', 'createtries', + 'cols', 'rows', 'words', 'wordsall', 'createscore', 'createtries', 'createtimelimit', 'createconnectors', 'createfilleds', 'createspaces', 'triesplay')); - $cryptexs = new backup_nested_element('game_cryptexs'); + $cryptexs = new backup_nested_element('game_cryptexs'); $cryptex = new backup_nested_element('game_cryptex', array('id'), array('letters')); - - $hangmans = new backup_nested_element('game_hangmans'); + + $hangmans = new backup_nested_element('game_hangmans'); $hangman = new backup_nested_element('game_hangman', array('id'), array( - 'queryid', 'letters', 'allletters', 'try', 'maxtries', 'finishedword', + 'queryid', 'letters', 'allletters', 'try', 'maxtries', 'finishedword', 'corrects', 'iscorrect')); - $hiddenpictures = new backup_nested_element('game_hiddenpictures'); + $hiddenpictures = new backup_nested_element('game_hiddenpictures'); $hiddenpicture = new backup_nested_element('game_hiddenpicture', array('id'), array('correct', 'wrong', 'found')); - - $millionaires = new backup_nested_element('game_millionaires'); + + $millionaires = new backup_nested_element('game_millionaires'); $millionaire = new backup_nested_element('game_millionaire', array('id'), array('queryid', 'state', 'level')); - $snakes = new backup_nested_element('game_snakes'); + $snakes = new backup_nested_element('game_snakes'); $snake = new backup_nested_element('game_snake', array('id'), array('snakesdatabaseid', 'position', 'queryid', 'dice')); - $sudokus = new backup_nested_element('game_sudokus'); + $sudokus = new backup_nested_element('game_sudokus'); $sudoku = new backup_nested_element('game_sudoku', array('id'), array('level', 'data', 'opened', 'guess')); - // Build the tree - $game->add_child($bookquiz_questions); - $bookquiz_questions->add_child($bookquiz_question); - + // Build the tree. + $game->add_child( $bookquizquestions); + $bookquizquestions->add_child( $bookquizquestion); + $game->add_child( $exporthtmls); $exporthtmls->add_child( $exporthtml); $game->add_child( $exportjavames); $exportjavames->add_child( $exportjavame); - + $game->add_child( $grades); $grades->add_child( $grade); - + $game->add_child( $repetitions); $repetitions->add_child( $repetition); - - // All these source definitions only happen if we are including user info + + // All these source definitions only happen if we are including user info. if ($userinfo) { - $game->add_child( $attempts); - $attempts->add_child( $attempt); + $game->add_child( $attempts); + $attempts->add_child( $attempt); + + $attempts->add_child( $querys); + $querys->add_child( $query); - $attempts->add_child( $querys); - $querys->add_child( $query); + $attempts->add_child( $bookquizs); + $bookquizs->add_child( $bookquiz); - $attempts->add_child( $bookquizs); - $bookquizs->add_child( $bookquiz); + $game->add_child( $bookquizchapters); + $bookquizchapters->add_child($bookquizchapter); - $game->add_child($bookquiz_chapters); - $bookquiz_chapters->add_child($bookquiz_chapter); + $attempts->add_child( $crosss); + $crosss->add_child( $cross); - $attempts->add_child( $crosss); - $crosss->add_child( $cross); + $attempts->add_child( $cryptexs); + $cryptexs->add_child( $cryptex); - $attempts->add_child( $cryptexs); - $cryptexs->add_child( $cryptex); + $attempts->add_child( $hangmans); + $hangmans->add_child( $hangman); - $attempts->add_child( $hangmans); - $hangmans->add_child( $hangman); + $attempts->add_child( $hiddenpictures); + $hiddenpictures->add_child( $hiddenpicture); - $attempts->add_child( $hiddenpictures); - $hiddenpictures->add_child( $hiddenpicture); + $attempts->add_child( $millionaires); + $millionaires->add_child( $millionaire); - $attempts->add_child( $millionaires); - $millionaires->add_child( $millionaire); + $attempts->add_child( $snakes); + $snakes->add_child( $snake); - $attempts->add_child( $snakes); - $snakes->add_child( $snake); - - $attempts->add_child( $sudokus); - $sudokus->add_child( $sudoku); - } - - // Define sources + $attempts->add_child( $sudokus); + $sudokus->add_child( $sudoku); + } + + // Define sources. $game->set_source_table('game', array('id' => backup::VAR_ACTIVITYID)); - $bookquiz_question->set_source_table('game_bookquiz_questions', array('gameid' => backup::VAR_ACTIVITYID)); + $bookquizquestion->set_source_table('game_bookquiz_questions', array('gameid' => backup::VAR_ACTIVITYID)); $exporthtml->set_source_table('game_export_html', array('id' => backup::VAR_ACTIVITYID)); $exportjavame->set_source_table('game_export_javame', array('id' => backup::VAR_ACTIVITYID)); - - // All the rest of elements only happen if we are including user info + + // All the rest of elements only happen if we are including user info. if ($userinfo) { $grade->set_source_table('game_grades', array('gameid' => backup::VAR_ACTIVITYID)); $repetition->set_source_table('game_repetitions', array('gameid' => backup::VAR_ACTIVITYID)); - + $attempt->set_source_table('game_attempts', array( 'gameid' => backup::VAR_ACTIVITYID)); $attempt->set_source_table('game_queries', array( 'attemptid' => backup::VAR_PARENTID)); - + $bookquiz->set_source_table('game_bookquiz', array( 'id' => backup::VAR_ACTIVITYID)); - $bookquiz_chapter->set_source_table('game_bookquiz_chapters', array( 'id' => backup::VAR_PARENTID)); - + $bookquizchapter->set_source_table('game_bookquiz_chapters', array( 'id' => backup::VAR_PARENTID)); + $cross->set_source_table('game_cross', array( 'id' => backup::VAR_PARENTID)); $cryptex->set_source_table('game_cryptex', array( 'id' => backup::VAR_PARENTID)); $hangman->set_source_table('game_hangman', array( 'id' => backup::VAR_PARENTID)); @@ -187,7 +187,7 @@ class backup_game_activity_structure_step extends backup_activity_structure_step $snake->set_source_table('game_snakes', array( 'id' => backup::VAR_PARENTID)); $sudoku->set_source_table('game_sudoku', array( 'id' => backup::VAR_PARENTID)); } - // Define id annotations + // Define id annotations. $attempt->annotate_ids('user', 'userid'); $grade->annotate_ids('user', 'userid'); $repetition->annotate_ids('user', 'userid'); @@ -198,17 +198,17 @@ class backup_game_activity_structure_step extends backup_activity_structure_step $query->annotate_ids('glossary_enrty', 'glossaryentryid'); $query->annotate_ids('question_answer', 'answerid'); - $bookquiz_question->annotate_ids('book_chapter', 'chapterid'); - $bookquiz_question->annotate_ids('question_category', 'questioncategoryid'); - $bookquiz_chapter->annotate_ids('book_chapter', 'chapterid'); + $bookquizquestion->annotate_ids('book_chapter', 'chapterid'); + $bookquizquestion->annotate_ids('question_category', 'questioncategoryid'); + $bookquizchapter->annotate_ids('book_chapter', 'chapterid'); $hangman->annotate_ids('game_query', 'queryid'); $millionaire->annotate_ids('game_query', 'queryid'); - - // Define file annotations - $game->annotate_files('mod_game', 'snakes_file', null); // This file area hasn't itemid - $game->annotate_files('mod_game', 'snakes_board', null); // This file area hasn't itemid - - // Return the root element (game), wrapped into standard activity structure + + // Define file annotations. + $game->annotate_files('mod_game', 'snakes_file', null); // This file area hasn't itemid. + $game->annotate_files('mod_game', 'snakes_board', null); // This file area hasn't itemid. + + // Return the root element (game), wrapped into standard activity structure. return $this->prepare_activity_structure( $game); } } diff --git a/backup/moodle2/restore_game_activity_task.class.php b/backup/moodle2/restore_game_activity_task.class.php index 81b9134..e6b7d84 100755 --- a/backup/moodle2/restore_game_activity_task.class.php +++ b/backup/moodle2/restore_game_activity_task.class.php @@ -1,5 +1,4 @@ -dirroot . '/mod/game/backup/moodle2/restore_game_stepslib.php'); // Because it exists (must) +require_once($CFG->dirroot . '/mod/game/backup/moodle2/restore_game_stepslib.php'); // Because it exists (must). /** * game restore task that provides all the settings and steps to perform one @@ -35,14 +34,14 @@ class restore_game_activity_task extends restore_activity_task { * Define (add) particular settings this activity can have */ protected function define_my_settings() { - // No particular settings for this activity + // No particular settings for this activity. } /** * Define (add) particular steps this activity can have */ protected function define_my_steps() { - // Game only has one structure step + // Game only has one structure step. $this->add_step(new restore_game_activity_structure_step('game_structure', 'game.xml')); } @@ -77,7 +76,7 @@ class restore_game_activity_task extends restore_activity_task { */ static public function define_restore_log_rules() { $rules = array(); - + $rules[] = new restore_log_rule('game', 'add', 'view.php?id={course_module}', '{game}'); $rules[] = new restore_log_rule('game', 'update', 'view.php?id={course_module}', '{game}'); $rules[] = new restore_log_rule('game', 'view', 'view.php?id={course_module}', '{game}'); @@ -87,7 +86,7 @@ class restore_game_activity_task extends restore_activity_task { return $rules; } - + /** * Define the restore log rules that will be applied * by the {@link restore_logs_processor} when restoring @@ -100,134 +99,149 @@ class restore_game_activity_task extends restore_activity_task { */ static public function define_restore_log_rules_for_course() { $rules = array(); - - // Fix old wrong uses (missing extension) + + // Fix old wrong uses (missing extension). $rules[] = new restore_log_rule('game', 'view all', 'index?id={course}', null, null, null, 'index.php?id={course}'); $rules[] = new restore_log_rule('game', 'view all', 'index.php?id={course}', null); - + return $rules; } - + public function after_restore() { - // Do something at end of restore + // Do something at end of restore. global $DB; - // Get the blockid + // Get the blockid. $gameid = $this->get_activityid(); - - // Extract Game configdata and update it to point to the new glossary - $rec = $DB->get_record_select( 'game', 'id='.$gameid, null, - 'id,quizid,glossaryid,glossarycategoryid,questioncategoryid,bookid,glossaryid2,glossarycategoryid2'); + + // Extract Game configdata and update it to point to the new glossary. + $rec = $DB->get_record_select( 'game', 'id='.$gameid, + null, 'id,quizid,glossaryid,glossarycategoryid,questioncategoryid,bookid,glossaryid2,glossarycategoryid2'); $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'quiz', $rec->quizid); - if( $ret != false) + if ($ret != false) { $rec->quizid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid); - if( $ret != false) + if ($ret != false) { $rec->glossaryid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid); - if( $ret != false) + if ($ret != false) { $rec->glossarycategoryid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_categories', $rec->questioncategoryid); - if( $ret != false) + if ($ret != false) { $rec->questioncategoryid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book', $rec->bookid); - if( $ret != false) + if ($ret != false) { $rec->bookid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary', $rec->glossaryid2); - if( $ret != false) + if ($ret != false) { $rec->glossaryid2 = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_categories', $rec->glossarycategoryid); - if( $ret != false) + if ($ret != false) { $rec->glossarycategoryid = $ret->newitemid; - + } + $DB->update_record( 'game', $rec); - //game_repetitions + // Read game_repetitions. $recs = $DB->get_records_select( 'game_repetitions', 'gameid='.$gameid, null, '', 'id,questionid,glossaryentryid'); - if( $recs != false){ - foreach( $recs as $rec){ + if ($recs != false) { + foreach ($recs as $rec) { $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid); - if( $ret != false) + if ($ret != false) { $rec->questionid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid); - if( $ret != false) + if ($ret != false) { $rec->glossaryentryid = $ret->newitemid; - + } + $DB->update_record( 'game_repetitions', $rec); - } + } } - - //game_queries + + // Read game_queries. $recs = $DB->get_records_select( 'game_queries', 'gameid='.$gameid, null, '', 'id,questionid,glossaryentryid,answerid'); - if( $recs != false){ - foreach( $recs as $rec){ + if ($recs != false) { + foreach ($recs as $rec) { $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question', $rec->questionid); - if( $ret != false) + if ($ret != false) { $rec->questionid = $ret->newitemid; - + } $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'glossary_entry', $rec->glossaryentryid); - if( $ret != false) + if ($ret != false) { $rec->glossaryentryid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'question_answers', $rec->glossaryentryid); - if( $ret != false) + if ($ret != false) { $rec->answerid = $ret->newitemid; - - $DB->update_record( 'game_queries', $rec); - } + } + + $DB->update_record( 'game_queries', $rec); + } } - //bookquiz + // Read bookquiz. $recs = $DB->get_records_select( 'game_bookquiz', 'id='.$gameid, null, '', 'id,lastchapterid'); - if( $recs != false){ - foreach( $recs as $rec){ + if ($recs != false) { + foreach ($recs as $rec) { $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->lastchapterid); - if( $ret != false) + if ($ret != false) { $rec->lastchapterid = $ret->newitemid; - - $DB->update_record( 'game_bookquiz', $rec); - } + } + + $DB->update_record( 'game_bookquiz', $rec); + } } - - //bookquiz_chapters - $sql = "SELECT gbc.* FROM {game_bookquiz_chapters} gbc LEFT JOIN {game_attempts} a ON gbc.attemptid = a.id WHERE a.gameid=$gameid"; + + // Read bookquiz_chapters. + $sql = "SELECT gbc.* ". + "FROM {game_bookquiz_chapters} gbc LEFT JOIN {game_attempts} a ON gbc.attemptid = a.id". + " WHERE a.gameid=$gameid"; $recs = $DB->get_records_sql( $sql); - if( $recs != false){ - foreach( $recs as $rec){ + if ($recs != false) { + foreach ($recs as $rec) { $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid); - if( $ret != false) + if ($ret != false) { $rec->chapterid = $ret->newitemid; - - $DB->update_record( 'game_bookquiz_chapter', $rec); - } - } + } + $DB->update_record( 'game_bookquiz_chapter', $rec); + } + } - //bookquiz_questions + // Read bookquiz_questions. $recs = $DB->get_records_select( 'game_bookquiz_questions', 'id='.$gameid, null, '', 'id,chapterid,questioncategoryid'); - if( $recs != false){ - foreach( $recs as $rec){ + if ($recs != false) { + foreach ($recs as $rec) { $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->chapterid); - if( $ret != false) + if ($ret != false) { $rec->chapterid = $ret->newitemid; - + } + $ret = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'book_chapters', $rec->questioncategoryid); - if( $ret != false) + if ($ret != false) { $rec->questioncategoryid = $ret->newitemid; - - $DB->update_record( 'game_bookquiz_questions', $rec); - } + } + + $DB->update_record( 'game_bookquiz_questions', $rec); + } } - } } diff --git a/backup/moodle2/restore_game_stepslib.php b/backup/moodle2/restore_game_stepslib.php index fa976cb..ab9e20b 100755 --- a/backup/moodle2/restore_game_stepslib.php +++ b/backup/moodle2/restore_game_stepslib.php @@ -1,5 +1,4 @@ get_setting_value('userinfo'); - + $paths[] = new restore_path_element('game', '/activity/game'); $paths[] = new restore_path_element('game_export_html', '/activity/game/game_export_htmls/game_export_html'); $paths[] = new restore_path_element('game_export_javame', '/activity/game/game_export_htmls/game_export_javame'); - $paths[] = new restore_path_element('game_bookquiz_question', '/activity/game/game_bookquiz_questions/game_bookquiz_question'); + $paths[] = new restore_path_element( + 'game_bookquiz_question', '/activity/game/game_bookquiz_questions/game_bookquiz_question'); if ($userinfo) { $paths[] = new restore_path_element('game_grade', '/activity/game/game_grades/game_grade'); $paths[] = new restore_path_element('game_repetition', '/activity/game/game_repetiotions/game_repetition'); $paths[] = new restore_path_element('game_attempt', '/activity/game/game_attempts/game_attempt'); $paths[] = new restore_path_element('game_query', '/activity/game/game_querys/game_query'); $paths[] = new restore_path_element('game_bookquiz', '/activity/game/game_bookquizs/game_bookquiz'); - $paths[] = new restore_path_element('game_bookquiz_chapter', '/activity/game/game_bookquiz_chapters/game_bookquiz_chapter'); + $paths[] = new restore_path_element('game_bookquiz_chapter', + '/activity/game/game_bookquiz_chapters/game_bookquiz_chapter'); $paths[] = new restore_path_element('game_cross', '/activity/game/game_crosss/game_cross'); $paths[] = new restore_path_element('game_cryptex', '/activity/game/game_cryptexs/game_cryptex'); $paths[] = new restore_path_element('game_hangman', '/activity/game/game_hangmans/game_hangman'); @@ -54,50 +55,48 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $paths[] = new restore_path_element('game_snake', '/activity/game/game_snakes/game_snake'); $paths[] = new restore_path_element('game_sudoku', '/activity/game/game_sudokus/game_sudoku'); } - - // Return the paths wrapped into standard activity structure + + // Return the paths wrapped into standard activity structure. return $this->prepare_activity_structure($paths); } - + protected function process_game($data) { global $DB; - + $data = (object)$data; $oldid = $data->id; - $data->course = $this->get_courseid(); + $data->course = $this->get_courseid(); $data->timemodified = $this->apply_date_offset($data->timemodified); - - // insert the game record + + // Insert the game record. $newitemid = $DB->insert_record('game', $data); - - // immediately after inserting "activity" record, call this + + // Immediately after inserting "activity" record, call this. $this->apply_activity_instance($newitemid); } - + protected function process_game_export_html($data) { global $DB; - + $data = (object)$data; - + $data->id = $this->get_new_parentid('game'); - if( $data->id == 0) - return; - - $DB->insert_record('game_export_html', $data); + if ($data->id ! 0) { + $DB->insert_record('game_export_html', $data); + } } - + protected function process_game_export_javame($data) { global $DB; - + $data = (object)$data; - + $data->id = $this->get_new_parentid('game'); - if( $data->id == 0) - return; - - $DB->insert_record('game_export_javame', $data); - } - + if ($data->id != 0) { + $DB->insert_record('game_export_javame', $data); + } + } + protected function process_game_grade($data) { global $DB; @@ -109,7 +108,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $DB->insert_record('game_grades', $data); } - + protected function process_game_repetition($data) { global $DB; @@ -118,10 +117,10 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->gameid = $this->get_new_parentid('game'); $data->userid = $this->get_mappingid('user', $data->userid); - + $DB->insert_record('game_repetitions', $data); } - + protected function process_game_attempt($data) { global $DB; @@ -131,13 +130,16 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->gameid = $this->get_new_parentid('game'); $data->userid = $this->get_mappingid('user', $data->userid); - if( !isset( $data->timestart)) + if (!isset( $data->timestart)) { $data->timestart = 0; - if( !isset( $data->timefinish)) + } + if (!isset( $data->timefinish)) { $data->timefinish = 0; - if( !isset( $data->timelastattempt)) - $data->timelastattempt = 0; - + } + if (!isset( $data->timelastattempt)) { + $data->timelastattempt = 0; + } + $data->timestart = $this->apply_date_offset($data->timestart); $data->timefinish = $this->apply_date_offset($data->timefinish); $data->timelastattempt = $this->apply_date_offset($data->timelastattempt); @@ -145,7 +147,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $newitemid = $DB->insert_record('game_attempts', $data); $this->set_mapping('game_attempt', $oldid, $newitemid); } - + protected function process_game_query($data) { global $DB; @@ -158,8 +160,8 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $newitemid = $DB->insert_record('game_queries', $data); $this->set_mapping('game_query', $oldid, $newitemid); - } - + } + protected function process_game_bookquiz($data) { global $DB; @@ -168,7 +170,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->id = $this->get_new_parentid('game'); $DB->insert_record('game_bookquiz', $data); - } + } protected function process_game_bookquiz_chapter($data) { global $DB; @@ -178,17 +180,17 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->gameid = $this->get_new_parentid('game'); $DB->insert_record('game_bookquiz_chapters', $data); - } + } protected function process_game_bookquiz_question($data) { global $DB; $data = (object)$data; - + $data->gameid = $this->get_new_parentid('game'); $DB->insert_record('game_bookquiz_questions', $data); - } + } protected function process_game_cross($data) { global $DB; @@ -198,7 +200,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->id = $this->get_new_parentid('game'); $DB->insert_record('game_cross', $data); - } + } protected function process_game_cryptex($data) { global $DB; @@ -208,7 +210,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->id = $this->get_new_parentid('game'); $DB->insert_record('game_cryptex', $data); - } + } protected function process_game_hangman($data) { global $DB; @@ -219,7 +221,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->queryid = $this->get_mappingid('game_query', $data->queryid); $DB->insert_record('game_hangman', $data); - } + } protected function process_game_hiddenpicture($data) { global $DB; @@ -229,7 +231,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->id = $this->get_new_parentid('game'); $DB->insert_record('game_hiddenpicture', $data); - } + } protected function process_game_millionaire($data) { global $DB; @@ -240,9 +242,9 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $data->queryid = $this->get_mappingid('game_query', $data->queryid); $DB->insert_record('game_millionaire', $data); - } - - protected function process_game_snake($data) { + } + + protected function process_game_snake($data) { global $DB; $data = (object)$data; @@ -252,7 +254,7 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $DB->insert_record('game_snakes', $data); } - + protected function process_game_sudoku($data) { global $DB; @@ -262,9 +264,9 @@ class restore_game_activity_structure_step extends restore_activity_structure_st $DB->insert_record('game_sudoku', $data); } - + protected function after_execute() { - // Add Game related files, no need to match by itemname (just internally handled context) + // Add Game related files, no need to match by itemname (just internally handled context). $this->add_related_files('mod_game', 'snakes_file', null); $this->add_related_files('mod_game', 'snakes_board', null); } diff --git a/bookquiz/importodt.php b/bookquiz/importodt.php index e2907fa..28f3e72 100755 --- a/bookquiz/importodt.php +++ b/bookquiz/importodt.php @@ -1,4 +1,19 @@ -. + /** * This is a very rough importer for odt * @@ -10,60 +25,61 @@ * @package game **/ - require_once("../../../config.php"); - require_once( "../header.php"); - require_once("../locallib.php"); +require_once("../../../config.php"); +require_once( "../header.php"); +require_once("../locallib.php"); - $subchapter = optional_param('subchapter', '', PARAM_ALPHA); - $overwrite = optional_param('overwrite', 0, PARAM_INT); - $attempt = game_getattempt( $game, $detail); - $bookid = $game->bookid; - if( $bookid == 0){ - print_error( get_string( 'bookquiz_not_select_book', 'game')); - } +$subchapter = optional_param('subchapter', '', PARAM_ALPHA); +$overwrite = optional_param('overwrite', 0, PARAM_INT); +$attempt = game_getattempt( $game, $detail); +$bookid = $game->bookid; +if ($bookid == 0) { + print_error( get_string( 'bookquiz_not_select_book', 'game')); +} - if ($form = data_submitted()) - { /// Filename +if ($form = data_submitted()) { + // Filename. + if (empty($_FILES['newfile'])) { + // File was just uploaded. + notify(get_string("uploadproblem") ); + } - if (empty($_FILES['newfile'])) - { // file was just uploaded - notify(get_string("uploadproblem") ); - } + if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) { + notify(get_string("uploadnofilefound") ); + } else { + // Valid file is found. + if (readdata( $course->id, 'game', $dirtemp, $rlevels, $rtitles, $rtexts, $dirfordelete)) { + // First try to reall all of the data in. + if ($overwrite) { + game_bookquiz_deletebook( $course->id, $bookid); + } + // Parse all the html files into objects. + $pageobjects = extract_data( $course->id, 'book', $bookid, $dirtemp, $subchapter, $rlevels, $rtitles, $rtexts); + clean_temp( $dirfordelete); // All done with files so dump em. - if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) - { - notify(get_string("uploadnofilefound") ); - } else - { // Valid file is found - if ( readdata( $course->id, 'game', $dirtemp, $r_levels, $r_titles, $r_texts, $dirfordelete)) - { // first try to reall all of the data in - if( $overwrite){ - 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 - 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 - - if( !game_bookquiz_save_objects($objects)) - { // sends it to DB - print_error('could not save'); - } - }else - print_error('could not get data'); + // Function to preps the data to be sent to DB. + $objects = game_bookquiz_create_objects( $pageobjects, $bookid); - print_continue("{$CFG->wwwroot}/mod/game/view.php?id=$cm->id"); - echo $OUTPUT->footer($course); - exit; + if (!game_bookquiz_save_objects( $objects)) { + // Sends it to DB. + print_error('could not save'); + } + } else { + print_error('could not get data'); } + + print_continue("{$CFG->wwwroot}/mod/game/view.php?id=$cm->id"); + echo $OUTPUT->footer($course); + exit; } +} - /// Print upload form +// Print upload form. print_heading_with_help( get_string( "bookquiz_import_odt", "game"), "importodt", "game"); echo $OUTPUT->box_start('center'); - ?> +?>
@@ -96,160 +112,152 @@ echo $OUTPUT->box_end(); echo $OUTPUT->footer($course); - -// START OF FUNCTIONS - -//the r_basedir variable contains the directory where the temp files are -//At the end the directory must be deleted -function readdata( $courseid, $modname, &$r_basedir, &$r_levels, &$r_titles, &$r_texts, &$dirfordelete) -{ -// this function expects a odt file to be uploaded. Then it parses -// the content.xml to determine. -// Then copies the image + +// START OF FUNCTIONS. + +// The rbasedir variable contains the directory where the temp files are. +// At the end the directory must be deleted. +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. + // Then copies the images. global $CFG; - - // create a random upload directory in temp - $newdir = $CFG->dataroot."/temp/$modname"; - if (!file_exists( $newdir)) - mkdir( $newdir); - - $i = 1; - srand((double)microtime()*1000000); - while(true) - { - $r_basedir = "$modname/$i-".rand(0,10000); - $newdir = $CFG->dataroot.'/temp/'.$r_basedir; - if (!file_exists( $newdir)) - { - mkdir( $newdir); - $newdir .= '/'; + + // Create a random upload directory in temp. + $newdir = $CFG->dataroot."/temp/$modname"; + if (!file_exists( $newdir)) { + mkdir( $newdir); + } + + $i = 1; + srand((double)microtime() * 1000000); + while (true) { + $rbasedir = "$modname/$i-".rand(0, 10000); + $newdir = $CFG->dataroot.'/temp/'.$rbasedir; + if (!file_exists( $newdir)) { + mkdir( $newdir); + $newdir .= '/'; break; } $i++; } - $dirfordelete = $r_basedir; - $r_basedir .= '/'; + $dirfordelete = $rbasedir; + $rbasedir .= '/'; $zipfile = $_FILES["newfile"]["name"]; $tempzipfile = $_FILES["newfile"]["tmp_name"]; - - // create our directory - $path_parts = pathinfo($zipfile); - $dirname = substr($zipfile, 0, strpos($zipfile, '.'.$path_parts['extension'])); // take off the extension - if (!file_exists($newdir.$dirname)){ + + // Creates our directory. + $pathparts = pathinfo($zipfile); + // Takes off the extension. + $dirname = substr($zipfile, 0, strpos($zipfile, '.'.$pathparts['extension'])); + if (!file_exists($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); - - //if the file ends with .lnk then use .odt instead - if( substr( $zipfile, -4) == ".lnk") - $zipfile = substr( $zipfile, 0, -4).".odt"; - // unzip it! - unzip_file ( $newdir.$zipfile, $newdir.$dirname, false); + // If the file ends with .lnk then use .odt instead. + if (substr( $zipfile, -4) == ".lnk") { + $zipfile = substr( $zipfile, 0, -4).".odt"; + } + + // Unzip it! + unzip_file ( $newdir.$zipfile, $newdir.$dirname, false); - $r_basedir .= $dirname; // update the base - $newdir .= $dirname; - - // this is the file where we get the names of the files for the slides (in the correct order too) + $rbasedir .= $dirname; // Update the base. + $newdir .= $dirname; + + // This is the file where we get the names of the files for the slides (in the correct order too). $content = $newdir.'/content.xml'; - $data = file_get_contents( $content); + $data = file_get_contents( $content); $content = $newdir.'/styles.xml'; - if (file_exists( $content)){ - $datastyle = file_get_contents( $content); - }else - { - $datastyle = ''; - } - - oo_game_convert_ver2( $data, $datastyle, $r_levels, $r_titles, $r_texts); - - return true; + if (file_exists( $content)) { + $datastyle = file_get_contents( $content); + } else { + $datastyle = ''; + } + + oo_game_convert_ver2( $data, $datastyle, $rlevels, $rtitles, $rtexts); + + return true; } +function oo_game_convert_ver2( $data, $datastyle, &$rlevels, &$rtitles, &$rtexts) { + $rlevels = array(); + $rtitles = array(); + $rtexts = array(); - //////////////////////// - function oo_game_convert_ver2( $data, $datastyle, &$r_levels, &$r_titles, &$r_texts) - { - $r_levels = array(); - $r_titles = array(); - $r_texts = array(); - - // we have tables, encode it here so all ', '', $data); - $data = preg_replace('##es', "base64_encode('\\1')", $data); - } - - $styles = array(); - game_bookquiz_convert_ver2_computestyles( $datastyle, $styles, true); - game_bookquiz_convert_ver2_computestyles( $data, $styles, false); - - game_bookquiz_splitsections($data, $positions, $inputs, $titles, $titleframes, $texts); - for( $i=0; $i < count( $positions); $i++) - { - preg_match_all( "#text:outline-level=\"([0-9]*)\"#es", $inputs[ $i], $matches); - $levels = $matches[ 1]; - if( count( $levels) > 0){ - $level = $levels[ 0]; - }else - { - $level = 0; - } - - $r_levels[] = $level; - $r_titles[] = strip_tags( $titles[ $i]); - - $textframe = game_bookquiz_convert($titleframes[ $i], $styles, $images); - $text = game_bookquiz_convert($texts[ $i], $styles, $images); - if( $textframe != ''){ - $text = $textframe.'
'.$text; - } + // We have tables, encode it here so all ', '', $data); + $data = preg_replace('##es', "base64_encode('\\1')", $data); + } + + $styles = array(); + game_bookquiz_convert_ver2_computestyles( $datastyle, $styles, true); + game_bookquiz_convert_ver2_computestyles( $data, $styles, false); + + game_bookquiz_splitsections($data, $positions, $inputs, $titles, $titleframes, $texts); + for ($i = 0; $i < count( $positions); $i++) { + preg_match_all( "#text:outline-level=\"([0-9]*)\"#es", $inputs[ $i], $matches); + $levels = $matches[ 1]; + if (count( $levels) > 0) { + $level = $levels[ 0]; + } else { + $level = 0; + } - echo "
".$titles[ $i]."
".$text."\r\n\r\n\r\n\r\n"; + $rlevels[] = $level; + $rtitles[] = strip_tags( $titles[ $i]); - $r_texts[] = $text; - } - } + $textframe = game_bookquiz_convert($titleframes[ $i], $styles, $images); + $text = game_bookquiz_convert($texts[ $i], $styles, $images); + + if ($textframe != '') { + $text = $textframe.'
'.$text; + } + + echo "
".$titles[ $i]."
".$text."\r\n\r\n\r\n\r\n"; + + $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 $matches; - - $dirtemp = $CFG->dataroot.'/temp/'.$basedir; - - for($i=0; $i < count( $levels); $i++){ - echo $levels[ $i]." ".$titles[ $i]."
"; - } + + $dirtemp = $CFG->dataroot.'/temp/'.$basedir; + + for ($i = 0; $i < count( $levels); $i++) { + echo $levels[ $i]." ".$titles[ $i]."
"; + } $extractedpages = array(); - - // directory for images - make_mod_upload_directory( $courseid); // make sure moddata is made - make_upload_directory( $courseid.'/moddata/'.$modname, false); - make_upload_directory( $courseid.'/moddata/'.$modname."/".$id, false); // we store our images in a subfolder in here - + + // Directory for images. + make_mod_upload_directory( $courseid); // Make sure moddata is made. + make_upload_directory( $courseid.'/moddata/'.$modname, false); + // We store our images in a subfolder in here. + make_upload_directory( $courseid.'/moddata/'.$modname."/".$id, false); + $imagedir = $CFG->dataroot.'/'.$courseid.'/moddata/'.$modname."/".$id; - if ($CFG->slasharguments) + if ($CFG->slasharguments) { $imagelink = $CFG->wwwroot.'/file.php/'.$courseid.'/moddata/'.$modname."/".$id; - else + } else { $imagelink = $CFG->wwwroot.'/file.php?file=/'.$courseid.'/moddata/'.$modname."/".$id; - - // try to make a unique subfolder to store the images - $i = 1; - while(true) - { + } + + // Try to make a unique subfolder to store the images. + $i = 1; + while (true) { $newdir = $imagedir.'/'.$i; - if (!file_exists( $newdir)) - { - // ok doesnt exist so make the directory and update our paths + if (!file_exists( $newdir)) { + // Ok doesnt exist so make the directory and update our paths. mkdir( $newdir); $imagedir = $newdir; $imagelink = $imagelink.'/'.$i; @@ -258,597 +266,472 @@ function extract_data( $courseid, $modname, $id, $basedir, $subchapter, $levels, $i++; } - for( $i=0; $i < count( $titles); $i++) - { - // start building our page + for ($i = 0; $i < count( $titles); $i++) { + // Start building our page. $page = new stdClass; $page->title = $titles[ $i]; - $page->content = $texts[ $i]; - //$page->source = $path_parts['basename']; // need for book only - $page->subchapter = ( $levels[ $i] >= 2); - - //check if the nexts are subchapters - for( $j=$i+1; $j < count( $titles); $j++){ - if( $levels[ $j] > 2){ - $page->content .= '
'.$titles[ $j].'
'.$texts[ $j]; - $i = $j; - continue; - } - break; - } - - preg_match_all('#="Pictures/([a-z .A-Z_0-9]*)"#es', $page->content, $imgs); - - foreach ($imgs[1] as $img) - { + $page->content = $texts[ $i]; + $page->subchapter = ( $levels[ $i] >= 2); + + // Check if the nexts are subchapters. + for ($j = $i + 1; $j < count( $titles); $j++) { + if ($levels[ $j] > 2) { + $page->content .= '
'.$titles[ $j].'
'.$texts[ $j]; + $i = $j; + continue; + } + break; + } + + preg_match_all('#="Pictures/([a-z .A-Z_0-9]*)"#es', $page->content, $imgs); + + foreach ($imgs[1] as $img) { $src = $dirtemp.'/Pictures/'.$img; - $dest = $imagedir.'/'.$img; - rename( $src, $dest); - - $page->content = str_replace( "Pictures/$img", $imagelink."/".$img, $page->content); + $dest = $imagedir.'/'.$img; + rename( $src, $dest); + + $page->content = str_replace( "Pictures/$img", $imagelink."/".$img, $page->content); } - // add the page to the array; + // Add the page to the array. $extractedpages[] = $page; - - } // end $pages foreach loop + } // End $pages foreach loop. return $extractedpages; } -/** +/* Clean up the temp directory -*/ -function clean_temp( $base) -{ + */ +function clean_temp( $base) { global $CFG; - // this function is broken, use it to clean up later - // should only clean up what we made as well because someone else could be importing ppt as well - $dir = $CFG->dataroot.'/temp/'.$base; + // 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. + $dir = $CFG->dataroot.'/temp/'.$base; - remove_dir( $dir); - //game_full_rmdir( $dir); + remove_dir( $dir); } - -/** +/* 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; $chapters = array(); $lastpagenum = $DB->get_field('book_chapters', 'MAX(pagenum) as num', array( 'bookid' => $bookid)); - foreach ($pageobjects as $pageobject) - { + foreach ($pageobjects as $pageobject) { $chapter = new stdClass; - - // same for all chapters + + // Same for all chapters. $chapter->bookid = $bookid; $chapter->pagenum = ++$lastpagenum; $chapter->timecreated = time(); $chapter->timemodified = time(); $chapter->subchapter = 0; - if ($pageobject->title == '') - $chapter->title = "Page $count"; // no title set so make a generic one - else - $chapter->title = addslashes($pageobject->title); - - $chapter->subchapter = $pageobject->subchapter; - - $content = str_replace("\n", '', $pageobject->content); - $content = str_replace("\r", '', $content); - $content = str_replace(' ', '', $content); // puts in returns? - $content = '

'.$content.'

'; - - $chapter->content = addslashes( $content); + if ($pageobject->title == '') { + $chapter->title = "Page $count"; // No title set so make a generic one. + } else { + $chapter->title = addslashes($pageobject->title); + } + $chapter->subchapter = $pageobject->subchapter; - $chapters[] = $chapter; + $content = str_replace("\n", '', $pageobject->content); + $content = str_replace("\r", '', $content); + $content = str_replace(' ', '', $content); // Puts in returns? + $content = '

'.$content.'

'; + + $chapter->content = addslashes( $content); + + $chapters[] = $chapter; } return $chapters; } -/** - Save the chapter objects to the database -*/ -function game_bookquiz_save_objects($chapters) -{ +// Save the chapter objects to the database. +function game_bookquiz_save_objects($chapters) { global $DB; - // nothing fancy, just save them all in order - foreach ($chapters as $chapter) - { - if (!$newid=$DB->insert_record('book_chapters', $chapter)) { + // Nothing fancy, just save them all in order. + foreach ($chapters as $chapter) { + if (!$newid = $DB->insert_record('book_chapters', $chapter)) { print_error('Could not insert to table book_chapters'); } } - + return true; } -//splits the data to -function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$titleframes, &$texts) -{ - preg_match_all('#(.*?)#es', $data, $matches, PREG_OFFSET_CAPTURE); - - $in = $matches[ 1] ; - $title = $matches[ 2]; - - $positions = array(); - $inputs = array(); - $titles = array(); - - $oldposition = 0; - $oldlen = 0; - for($i=0; $i < count( $in); $i++) - { - $inputs[] = $in[ $i][ 0]; - - $newposition = $in[ $i][ 1]; - $positions[] = $newposition; - - $titlenet = $title[ $i][ 0]; - $titleframe = ''; - - //frames inside header - preg_match_all('#(.*?)#es', $titlenet, $titlematches, PREG_OFFSET_CAPTURE); - $frames = $titlematches[ 2]; - if( count( $frames) > 0){ - for($j=0; $j < count( $frames); $j++) - { - $titleframe .= $frames[ $j][ 0]; - $titlenet = substr( $titlenet, $frames[ $j][ 1] + strlen( $frames[ $j][ 0]) + 13); - } - } - - $titles[] = $titlenet; - $titleframes[] = $titleframe; - - if( $i > 0){ - $texts[] = substr( $data, $oldposition+$oldlen, $newposition - $oldposition - $oldlen); - } - - $oldlen = strlen( $title[ $i][ 0]) + strlen( $in[ $i][ 0]) + 10; - $oldposition = $newposition; - - } - $newposition = strlen( $data); - $texts[] = substr( $data, $oldposition+$oldlen, $newposition - $oldposition - $oldlen); +// Splits the data to. +function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$titleframes, &$texts) { + preg_match_all('#(.*?)#es', $data, $matches, PREG_OFFSET_CAPTURE); + + $in = $matches[ 1]; + $title = $matches[ 2]; + + $positions = array(); + $inputs = array(); + $titles = array(); + + $oldposition = 0; + $oldlen = 0; + for ($i = 0; $i < count( $in); $i++) { + $inputs[] = $in[ $i][ 0]; + + $newposition = $in[ $i][ 1]; + $positions[] = $newposition; + + $titlenet = $title[ $i][ 0]; + $titleframe = ''; + + // Frames inside header. + preg_match_all('#(.*?)#es', $titlenet, $titlematches, PREG_OFFSET_CAPTURE); + $frames = $titlematches[ 2]; + if (count( $frames) > 0) { + for ($j = 0; $j < count( $frames); $j++) { + $titleframe .= $frames[ $j][ 0]; + $titlenet = substr( $titlenet, $frames[ $j][ 1] + strlen( $frames[ $j][ 0]) + 13); + } + } + + $titles[] = $titlenet; + $titleframes[] = $titleframe; + + if ($i > 0) { + $texts[] = substr( $data, $oldposition + $oldlen, $newposition - $oldposition - $oldlen); + } + + $oldlen = strlen( $title[ $i][ 0]) + strlen( $in[ $i][ 0]) + 10; + $oldposition = $newposition; + } + $newposition = strlen( $data); + $texts[] = substr( $data, $oldposition + $oldlen, $newposition - $oldposition - $oldlen); } - - function game_bookquiz_convert( $data, $styles, &$images) - { - $images = array(); - - // get data - preg_match_all('#(.*?)#es', $data, $text); - $originals = $text[ 0]; - $names = $text[ 1]; - $texts = $text[ 2]; - - for( $i=0; $i < count( $texts); $i++) - { - $name = $names[ $i]; - $text = $texts[ $i]; - - //repairs draw:frame - $pattern = "##es"; - preg_match_all( $pattern, $text, $matches); - if( count( $matches[ 1]) ){ - $new = game_bookquiz_convert_image( $matches, $styles, $images); - $data = str_replace( $originals[ $i], $new, $data); - }else IF($name == 'RKRK') - { - $new = game_bookquiz_convert_RKRK( $text); - $data = str_replace( $originals[ $i], $new, $data); - }else - { - $new = '

'.game_bookquiz_convert_text( $text, $styles).'

'; - $data = str_replace( $originals[ $i], $new, $data); - } - } - - // repairs text:span text:style-name - preg_match_all( '#(.*?)#es', $data, $text); - $originals = $text[ 0]; - $names = $text[ 1]; - $texts = $text[ 2]; - for( $i=0; $i < count( $texts); $i++) - { - $name = $names[ $i]; - $text = $texts[ $i]; - - $pattern = "##es"; - preg_match_all( $pattern, $text, $matches); - if( count( $matches[ 1]) ){ - $new = game_bookquiz_convert_image( $matches, $styles, $images); - $data = str_replace( $originals[ $i], $new, $data); - }else IF($name == 'RKRK') - { - $new = game_bookquiz_convert_RKRK( $text); - $data = str_replace( $originals[ $i], $new, $data); - }else - { - $new = "'.game_bookquiz_convert_text( $text, $styles).''; - $data = str_replace( $originals[ $i], $new, $data); - } - } - - // repairs text:a - preg_match_all( '#(.*?)#es', $data, $text); - $originals = $text[ 0]; - $hrefs = $text[ 2]; - $texts = $text[ 3]; - for( $i=0; $i < count( $texts); $i++) - { - $href = $hrefs[ $i]; - $text = $texts[ $i]; - - $new = "$text"; - $data = str_replace( $originals[ $i], $new, $data); - } - - //repair text:list - preg_match_all( '#(.*?)#es', $data, $text); - $originals = $text[ 0]; - $names = $text[ 1]; - $texts = $text[ 2]; - - for( $i=0; $i < count( $texts); $i++) - { - $new = '
    '.$texts[ $i].'
'; + +function game_bookquiz_convert( $data, $styles, &$images) { + $images = array(); + + // Get data. + preg_match_all('#(.*?)#es', $data, $text); + $originals = $text[ 0]; + $names = $text[ 1]; + $texts = $text[ 2]; + + for ($i = 0; $i < count( $texts); $i++) { + $name = $names[ $i]; + $text = $texts[ $i]; + + // Repairs draw:frame. + $pattern = "##es"; + preg_match_all( $pattern, $text, $matches); + if (count( $matches[ 1]) ) { + $new = game_bookquiz_convert_image( $matches, $styles, $images); $data = str_replace( $originals[ $i], $new, $data); + } else if ($name == 'RKRK') { + $new = game_bookquiz_convert_RKRK( $text); + $data = str_replace( $originals[ $i], $new, $data); + } else { + $new = '

'.game_bookquiz_convert_text( $text, $styles).'

'; + $data = str_replace( $originals[ $i], $new, $data); + } + } - //I have to repair the listitems - preg_match_all( '#(.*?)#es', $data, $listitems); - $originallistitems = $listitems[ 0]; - $items = $listitems[ 1]; - for( $j=0; $j < count( $items); $j++){ - $new = '
  • '.$items[ $j]; - $data = str_replace( $originallistitems[ $j], $new, $data); - + // Repairs text:span text:style-name. + preg_match_all( '#(.*?)#es', $data, $text); + $originals = $text[ 0]; + $names = $text[ 1]; + $texts = $text[ 2]; + for ($i = 0; $i < count( $texts); $i++) { + $name = $names[ $i]; + $text = $texts[ $i]; + + $pattern = "##es"; + preg_match_all( $pattern, $text, $matches); + if (count( $matches[ 1]) ) { + $new = game_bookquiz_convert_image( $matches, $styles, $images); + $data = str_replace( $originals[ $i], $new, $data); + } else if ($name == 'RKRK') { + $new = game_bookquiz_convert_RKRK( $text); + $data = str_replace( $originals[ $i], $new, $data); + } else { + $new = "'.game_bookquiz_convert_text( $text, $styles).''; + $data = str_replace( $originals[ $i], $new, $data); + } + } + + // Repairs text:a. + preg_match_all( '#(.*?)#es', $data, $text); + $originals = $text[ 0]; + $hrefs = $text[ 2]; + $texts = $text[ 3]; + for ($i = 0; $i < count( $texts); $i++) { + $href = $hrefs[ $i]; + $text = $texts[ $i]; + + $new = "$text"; + $data = str_replace( $originals[ $i], $new, $data); + } + + // Repair text:list. + preg_match_all( '#(.*?)#es', $data, $text); + $originals = $text[ 0]; + $names = $text[ 1]; + $texts = $text[ 2]; + + for ($i = 0; $i < count( $texts); $i++) { + $new = '
      '.$texts[ $i].'
    '; + $data = str_replace( $originals[ $i], $new, $data); + + // I have to repair the listitems. + preg_match_all( '#(.*?)#es', $data, $listitems); + $originallistitems = $listitems[ 0]; + $items = $listitems[ 1]; + for ($j = 0; $j < count( $items); $j++) { + $new = '
  • '.$items[ $j]; + $data = str_replace( $originallistitems[ $j], $new, $data); + } + } + + $data = str_replace( '', '
    ', $data); + + return $data; +} + +function game_bookquiz_convert_text( $text, $styles) { + $pattern = "#(.*?)#es"; + preg_match_all( $pattern, $text, $matches); + + $originals = $matches[ 0]; + $names = $matches[ 1]; + $spantexts = $matches[ 2]; + + for ($i = 0; $i < count( $names); $i++) { + $name = $names[ $i]; + $style = $styles[ $name]; + + $new = "".$spantexts[ $i].""; + $text = str_replace( $originals[ $i], $new, $text); + } + + return $text; +} + +function game_bookquiz_convert_image( $matches, $xmlstyles, &$images) { + $ret = ''; + + $styles = $matches[ 1]; + $pictures = $matches[ 3]; + + for ($j = 0; $j < count( $pictures); $j++) { + $style = $styles[ $j]; + + $ret .= '
    '; + $images[] = $pictures[$j]; + } + + return $ret; +} + +function game_bookquiz_convert_rkrk( $text) { + $table = base64_decode($text); + $table = stripslashes($table); + $table = strtr($table, array('' => '
  • ', '' => '', '' => '', '' => '', '' => '', '' => '', '>' => ">\n", '' => '')); + + preg_match_all('#table:name="(.*?)" table:style-name="(.*?)">#es', $table, $repl); + foreach ($repl[0] as $val) { + $table = str_replace($val, '', $table); + } + + preg_match_all('##es', $table, $repl); + foreach ($repl[0] as $key => $val) { + $table = str_replace($val, '', $table); + } + + preg_match_all('##es', $table, $repl); + foreach ($repl[0] as $val) { + $table = str_replace($val, '', $table); + } + + preg_match_all('##es', $table, $repl); + foreach ($repl[0] as $val) { + $table = str_replace($val, '
    ', $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); + foreach ($repl[ 1] as $picture) { + $table = str_replace('', '', $table); + } + if (strpos( $table, "
    ") === false) { + $table .= ""; + } + + $ret = '
    '.$table.'
    '; + + return $ret; +} + +function game_bookquiz_deletebook( $courseid, $bookid) { + global $CFG; + + if (!delete_records( 'book_chapters', 'bookid', $bookid)) { + print_error( "Can't delete records from book_chapters bookid=$bookid"); + } + + game_full_rmdir( "$CFG->dataroot/$courseid/moddata/book/$bookid"); +} + +function game_bookquiz_convert_ver2_computestyles( $data, &$styles, $isstyle) { + preg_match_all('#(.*?)#es', $data, $style); + + $stylenames = $style[ 1]; + $styleinfos = $style[ 2]; + $styledatas = $style[ 3]; + for ($i = 0; $i < count( $stylenames); $i++) { + $name = $stylenames[ $i]; + + $change = false; + for (;;) { + $pos1 = strpos( $styledatas[ $i], 'style:parent-style-name'); + $pos2 = strpos( $styledatas[ $i], '/>'); + if (($pos1 === false) or ($pos2 === false)) { + break; + } + if ($pos1 > $pos2) { + break; } + + // Is a parent style. + $s = substr( $styledatas[ $i], 0, $pos2 + 2); + game_bookquiz_convertstyle_parent( $s, $styles); + + $styledatas[ $i] = substr( $styledatas[ $i], $pos2 + 2); + $change = true; } - $data = str_replace( '', '
    ', $data); + if ($change) { + // Must to recompute name, styledatas, styleinfos. + preg_match_all('#(.*?)#es', $data, $style); + $name = $style[ 1][ 0]; + $styleinfos[ $i] = $style[ 2][ 0]; + $styledatas[ $i] = $style[ 3][ 0]; + } - - - return $data; - } + $styles[ $name] = game_bookquiz_convertstyle( $styledatas[ $i], $styleinfos[ $i], $styles); + } +} - function game_bookquiz_convert_text( $text, $styles) - { - $pattern = "#(.*?)#es"; - preg_match_all( $pattern, $text, $matches); - - $originals = $matches[ 0]; - $names = $matches[ 1]; - $spantexts = $matches[ 2]; - - for( $i=0; $i < count( $names); $i++) - { - $name = $names[ $i]; - $style = $styles[ $name]; - - $new = "".$spantexts[ $i].""; - $text = str_replace( $originals[ $i], $new, $text); - } - - return $text; - } - - function game_bookquiz_convert_image( $matches, $xmlstyles, &$images) - { - $ret = ''; - - $styles = $matches[ 1]; - $pictures = $matches[ 3]; - - for( $j=0; $j < count( $pictures); $j++){ - $style = $styles[ $j]; - - $ret .= '
    '; - $images[] = $pictures[$j]; - } - - return $ret; - } - - function game_bookquiz_convert_RKRK( $text) - { - $table = base64_decode($text); - $table = stripslashes($table); - $table = strtr($table, array('' => '', '' => '', '' => '', '' => '', '
    ' => '', '' => '', '>' => ">\n", '' => '')); - - //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); - foreach($repl[0] as $val) - { - //$table = str_replace($val, '
    ', $table); - $table = str_replace($val, '', $table); - } - //preg_match_all('##es', $table, $repl); - preg_match_all('##es', $table, $repl); - foreach($repl[0] as $key => $val) - { - $table = str_replace($val, '', $table); - } - preg_match_all('##es', $table, $repl); - foreach($repl[0] as $val) - { - $table = str_replace($val, '', $table); - } - //preg_match_all('##es', $table, $repl); - preg_match_all('##es', $table, $repl); - foreach($repl[0] as $val) - { - $table = str_replace($val, '
    ', $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); - foreach( $repl[ 1] as $picture) - { - $table = str_replace('', '', $table); - } - if( strpos( $table,"
    ") === false) - $table .= "
    "; - - $ret = '
    '.$table.'
    '; - - 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")) - { - $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; - - if( !delete_records( 'book_chapters', 'bookid', $bookid)){ - print_error( "Can't delete records from book_chapters bookid=$bookid"); - } - - game_full_rmdir( "$CFG->dataroot/$courseid/moddata/book/$bookid"); - - } - - function game_bookquiz_convert_ver2_computestyles( $data, &$styles, $isstyle) - { - preg_match_all('#(.*?)#es', $data, $style); - - $stylenames = $style[ 1]; - $styleinfos = $style[ 2]; - $styledatas = $style[ 3]; - for($i=0; $i < count( $stylenames); $i++){ - $name = $stylenames[ $i]; - - $change = false; - for(;;){ - $pos1 = strpos( $styledatas[ $i], 'style:parent-style-name'); - $pos2 = strpos( $styledatas[ $i], '/>'); - if( ($pos1 === false) or ($pos2 === false)){ - break; - } - if( $pos1 > $pos2){ - break; - } - //is a parent style - $s = substr( $styledatas[ $i], 0, $pos2+2); - game_bookquiz_convertstyle_parent( $s, $styles); - - $styledatas[ $i] = substr( $styledatas[ $i], $pos2 + 2); - $change = true; - } - if( $change){ - //Must to recompute name, styledatas, styleinfos - preg_match_all('#(.*?)#es', $data, $style); - $name = $style[ 1][ 0]; - $styleinfos[ $i] = $style[ 2][ 0]; - $styledatas[ $i] = $style[ 3][ 0]; - } - - $styles[ $name] = game_bookquiz_convertstyle( $styledatas[ $i], $styleinfos[ $i], $styles); - } - } - - function game_bookquiz_convertstyle_parent( $data, &$styles) - { - $styleitems = array(); - - preg_match_all( '#(.*?)style:name="(.*?)"(.*?)style:parent-style-name="(.*?)"(.*?)#es', $data, $infos); - $names = $infos[ 2]; - $parents = $infos[ 4]; - if( count( $parents)){ - if( array_key_exists( $parents[ 0], $styles)){ - //is a child style. Must to copy the properties of the parent style - $a = explode( ';', $styles[ $parents[ 0]]); - foreach( $a as $s){ - $pos = strpos( $s, ':'); - $key = substr( $s, 0, $pos); - $item = substr( $s, $pos + 1); - if( $item == ''){ - continue; - } - $styleitems[ $key] = $item; - } - } - $name = $names[ 0]; - } - - $style = ''; - foreach( $styleitems as $key => $item){ - $style .= ';'.$key.':'.$item; - } - $styles[ $name] = substr( $style, 1); - } - - function game_bookquiz_convertstyle( $data, $styleinfo, $styles) - { - $styleitems = array(); - - preg_match_all( '##es', $data, $infos); - $lines = $infos[ 1]; - if( count( $lines)){ - $line = $lines[ 0]; //print_object( $lines); - - if( $line != ''){ - game_bookquiz_convertstyle_paragraph( $line, $styleitems); - } - } - - preg_match_all( '##es', $data, $infos); - $lines = $infos[ 1]; - if( count( $lines)){ - $line = $lines[ 0]; - - if( $line != ''){ - game_bookquiz_convertstyle_textproperties( $line, $styleitems); - } - } - - if( count( $styleitems) == 0){ - return ''; - } - - $style = ''; - foreach( $styleitems as $key => $item){ - $style .= ';'.$key.':'.$item; - } - - return substr( $style, 1); - } - - function game_bookquiz_convertstyle_paragraph( $line, &$styleitems) - { - preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas); - $data1 = $datas[ 1]; - $data2 = $datas[ 2]; - - $ret = ''; - for( $i=0; $i < count( $data1); $i++){ - $eq1 = $data1[ $i]; - $eq2 = $data2[ $i]; - - if( (substr( $eq2, 0, 1) == '"') and (substr( $eq2, -1, 1) == '"')){ - $eq2 = substr( $eq2, 1, -1); +function game_bookquiz_convertstyle_parent( $data, &$styles) { + $styleitems = array(); + + preg_match_all( '#(.*?)style:name="(.*?)"(.*?)style:parent-style-name="(.*?)"(.*?)#es', $data, $infos); + $names = $infos[ 2]; + $parents = $infos[ 4]; + if (count( $parents)) { + if (array_key_exists( $parents[ 0], $styles)) { + // Is a child style. Must to copy the properties of the parent style. + $a = explode( ';', $styles[ $parents[ 0]]); + foreach ($a as $s) { + $pos = strpos( $s, ':'); + $key = substr( $s, 0, $pos); + $item = substr( $s, $pos + 1); + if ($item == '') { + continue; + } + $styleitems[ $key] = $item; } + } + $name = $names[ 0]; + } + + $style = ''; + foreach ($styleitems as $key => $item) { + $style .= ';'.$key.':'.$item; + } + + $styles[ $name] = substr( $style, 1); +} + +function game_bookquiz_convertstyle( $data, $styleinfo, $styles) { + $styleitems = array(); + + preg_match_all( '##es', $data, $infos); + $lines = $infos[ 1]; + if (count( $lines)) { + $line = $lines[ 0]; - switch( $eq1){ + if ($line != '') { + game_bookquiz_convertstyle_paragraph( $line, $styleitems); + } + } + + preg_match_all( '##es', $data, $infos); + $lines = $infos[ 1]; + if (count( $lines)) { + $line = $lines[ 0]; + + if ($line != '') { + game_bookquiz_convertstyle_textproperties( $line, $styleitems); + } + } + + if (count( $styleitems) == 0) { + return ''; + } + + $style = ''; + foreach ($styleitems as $key => $item) { + $style .= ';'.$key.':'.$item; + } + + return substr( $style, 1); +} + +function game_bookquiz_convertstyle_paragraph( $line, &$styleitems) { + preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas); + $data1 = $datas[ 1]; + $data2 = $datas[ 2]; + + $ret = ''; + for ($i = 0; $i < count( $data1); $i++) { + $eq1 = $data1[ $i]; + $eq2 = $data2[ $i]; + + if ((substr( $eq2, 0, 1) == '"') and (substr( $eq2, -1, 1) == '"')) { + $eq2 = substr( $eq2, 1, -1); + } + + switch ($eq1) { case 'fo:text-align': $styleitems[ 'align'] = $eq2; - //print_object( $styleitems); break; case 'fo:background-color': $styleitems[ 'background-color'] = $eq2; break; - } } - } + } +} - function game_bookquiz_convertstyle_textproperties( $line, &$styleitems) - { - preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas); - $data1 = $datas[ 1]; - $data2 = $datas[ 2]; +function game_bookquiz_convertstyle_textproperties( $line, &$styleitems) { + preg_match_all( '#(.*?)=(.*?) #es', $line.' ', $datas); + $data1 = $datas[ 1]; + $data2 = $datas[ 2]; - $ret = ''; - for( $i=0; $i < count( $data1); $i++){ - $eq1 = $data1[ $i]; - $eq2 = $data2[ $i]; + $ret = ''; + for ($i = 0; $i < count( $data1); $i++) { + $eq1 = $data1[ $i]; + $eq2 = $data2[ $i]; - if( (substr( $eq2, 0, 1) == '"') and (substr( $eq2, -1, 1) == '"')){ - $eq2 = substr( $eq2, 1, -1); - } + if ((substr( $eq2, 0, 1) == '"') and (substr( $eq2, -1, 1) == '"')) { + $eq2 = substr( $eq2, 1, -1); + } - switch( $eq1){ + switch( $eq1) { case 'fo:font-size': case 'fo:color': case 'fo:background-color': @@ -857,10 +740,10 @@ function game_bookquiz_splitsections($data, &$positions, &$inputs, &$titles, &$t $styleitems[ substr( $eq1, 3)] = $eq2; break; case 'style_text_underline_style': - if( $eq2 == 'solid'){ + if ($eq2 == 'solid') { $styleitems[ 'text-decoration'] = 'underline'; } break; - } } - } + } +} diff --git a/bookquiz/importppt.php b/bookquiz/importppt.php index 9d63925..b8bf33b 100755 --- a/bookquiz/importppt.php +++ b/bookquiz/importppt.php @@ -1,4 +1,19 @@ -. + /** * This is a very rough importer for powerpoint slides * Export a powerpoint presentation with powerpoint as html pages @@ -13,141 +28,146 @@ * @package lesson **/ - require_once("../../config.php"); - require_once("locallib.php"); +require_once("../../config.php"); +require_once("locallib.php"); - $id = required_param('id', PARAM_INT); // Course Module ID - $pageid = optional_param('pageid', '', PARAM_INT); // Page ID - global $matches; - - if (! $cm = get_coursemodule_from_id('lesson', $id)) { - print_error('Course Module ID was incorrect'); - } +$id = required_param('id', PARAM_INT); // Course Module ID. +$pageid = optional_param('pageid', '', PARAM_INT); // Page ID. +global $matches; - if (! $course = $DB->get_record('course', array( 'id' => $cm->course))) { - print_error('Course is misconfigured'); - } - - // allows for adaption for multiple modules - if(! $modname = $DB->get_field('modules', 'name', array( 'id' => $cm->module))) { - print_error('Could not find module name'); - } +if (! $cm = get_coursemodule_from_id('lesson', $id)) { + print_error('Course Module ID was incorrect'); +} - if (! $mod = $DB->get_record($modname, array( "id" => $cm->instance))) { - print_error('Course module is incorrect'); - } +if (! $course = $DB->get_record('course', array( 'id' => $cm->course))) { + print_error('Course is misconfigured'); +} - require_login($course->id, false); - $context = get_context_instance(CONTEXT_MODULE, $cm->id); - require_capability('mod/lesson:edit', $context); +// Allows for adaption for multiple modules. +if (!$modname = $DB->get_field('modules', 'name', array( 'id' => $cm->module))) { + print_error('Could not find module name'); +} - $strimportppt = get_string("importppt", "lesson"); - $strlessons = get_string("modulenameplural", "lesson"); +if (! $mod = $DB->get_record($modname, array( "id" => $cm->instance))) { + print_error('Course module is incorrect'); +} - echo $OUTPUT->heading("$strimportppt", " $strimportppt", "id\">$strlessons -> wwwroot}/mod/$modname/view.php?id=$cm->id\">".format_string($mod->name,true)."-> $strimportppt"); +require_login($course->id, false); +$context = get_context_instance(CONTEXT_MODULE, $cm->id); +require_capability('mod/lesson:edit', $context); - if ($form = data_submitted()) { /// Filename +$strimportppt = get_string("importppt", "lesson"); +$strlessons = get_string("modulenameplural", "lesson"); - if (empty($_FILES['newfile'])) { // file was just uploaded - notify(get_string("uploadproblem") ); - } +echo $OUTPUT->heading("$strimportppt", " $strimportppt", + "id\">$strlessons". + " -> wwwroot}/mod/$modname/view.php?id=$cm->id\">".format_string($mod->name, true)."-> $strimportppt"); - if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) { - notify(get_string("uploadnofilefound") ); - - } else { // Valid file is found - - if ($rawpages = readdata($_FILES, $course->id, $modname)) - { // first try to reall all of the data in - $pageobjects = extract_data($rawpages, $course->id, $mod->name, $modname); // parse all the html files into objects - clean_temp(); // all done with files so dump em - - $mod_create_objects = $modname.'_create_objects'; - $mod_save_objects = $modname.'_save_objects'; - - $objects = $mod_create_objects($pageobjects, $mod->id); // function to preps the data to be sent to DB - - if(! $mod_save_objects($objects, $mod->id, $pageid)) { // sends it to DB - print_error( 'could not save'); - } - } else { - print_error('could not get data'); - } +if ($form = data_submitted()) { // Filename. + if (empty($_FILES['newfile'])) { // File was just uploaded. + notify(get_string("uploadproblem") ); + } - echo "
    "; - print_continue("{$CFG->wwwroot}/mod/$modname/view.php?id=$cm->id"); - echo $OUTPUT->footer($course); - exit; + if ((!is_uploaded_file($_FILES['newfile']['tmp_name']) or $_FILES['newfile']['size'] == 0)) { + notify(get_string("uploadnofilefound") ); + } else { + // Valid file is found. + if ($rawpages = readdata($_FILES, $course->id, $modname)) { + // First try to reall all of the data in. + // parse all the html files into objects. + $pageobjects = extract_data($rawpages, $course->id, $mod->name, $modname); + clean_temp(); // All done with files so dump em. + + $modcreateobjects = $modname.'_create_objects'; + $modsaveobjects = $modname.'_save_objects'; + + // Function to preps the data to be sent to DB. + $objects = $modcreateobjects($pageobjects, $mod->id); + + if (! $modsaveobjects($objects, $mod->id, $pageid)) { + // Sends it to DB. + print_error( 'could not save'); + } + } else { + print_error('could not get data'); } + + echo "
    "; + print_continue("{$CFG->wwwroot}/mod/$modname/view.php?id=$cm->id"); + echo $OUTPUT->footer($course); + exit; } +} - /// Print upload form +// Print upload form. +print_heading_with_help($strimportppt, "importppt", "lesson"); - print_heading_with_help($strimportppt, "importppt", "lesson"); +echo $OUTPUT->box_start('center'); +echo ""; +echo "id\" />\n"; +echo "\n"; +echo ""; - echo $OUTPUT->box_start('center'); - echo ""; - echo "id\" />\n"; - echo "\n"; - echo "
    "; +echo ""; - echo ""; +echo "
    "; +print_string("upload"); +echo ":"; +echo ""; +echo "
     "; +echo ""; +echo "
    "; - print_string("upload"); - echo ":"; - echo ""; - echo "
     "; - echo ""; - echo "
    "; +echo ""; +echo $OUTPUT->box_end(); - echo ""; - echo ""; - echo $OUTPUT->box_end(); +echo $OUTPUT->footer($course); - echo $OUTPUT->footer($course); - -// START OF FUNCTIONS +// START OF FUNCTIONS. +/* this function expects a zip file to be uploaded. Then it parses + * outline.htm to determine the slide path. Then parses each + * slide to get data for the content + */ function readdata($file, $courseid, $modname) { -// this function expects a zip file to be uploaded. Then it parses -// outline.htm to determine the slide path. Then parses each -// slide to get data for the content global $CFG; - // create an upload directory in temp - make_upload_directory('temp/'.$modname); + // Create an upload directory in temp. + make_upload_directory('temp/'.$modname); $base = $CFG->dataroot."/temp/$modname/"; $zipfile = $_FILES["newfile"]["name"]; $tempzipfile = $_FILES["newfile"]["tmp_name"]; - - // create our directory - $path_parts = pathinfo($zipfile); - $dirname = substr($zipfile, 0, strpos($zipfile, '.'.$path_parts['extension'])); // take off the extension + + // Create our directory. + $pathparts = pathinfo($zipfile); + // Take off the extension. + $dirname = substr($zipfile, 0, strpos($zipfile, '.'.$pathparts['extension'])); if (!file_exists($base.$dirname)) { mkdir($base.$dirname); } - // move our uploaded file to temp/lesson + // Move our uploaded file to temp/lesson. move_uploaded_file($tempzipfile, $base.$zipfile); - // unzip it! + // Unzip it! unzip_file($base.$zipfile, $base, false); - - $base = $base.$dirname; // update the base - - // this is the file where we get the names of the files for the slides (in the correct order too) + + $base = $base.$dirname; // Update the base. + + // This is the file where we get the names of the files for the slides (in the correct order too). $outline = $base.'/outline.htm'; - + $pages = array(); - + if (file_exists($outline) and is_readable($outline)) { $outlinecontents = file_get_contents($outline); $filenames = array(); - preg_match_all("/javascript:GoToSld\('(.*)'\)/", $outlinecontents, $filenames); // this gets all of our files names + // This gets all of our files names. + preg_match_all("/javascript:GoToSld\('(.*)'\)/", $outlinecontents, $filenames); - // file $pages with the contents of all of the slides + // File $pages with the contents of all of the slides. foreach ($filenames[1] as $file) { $path = $base.'/'.$file; if (is_readable($path)) { @@ -155,12 +175,13 @@ function readdata($file, $courseid, $modname) { } else { return false; } - } + } } else { - // cannot find the outline, so grab all files that start with slide + // Cannot find the outline, so grab all files that start with slide. $dh = opendir($base); - while (false !== ($file = readdir($dh))) { // read throug the directory - if ('slide' == substr($file, 0, 5)) { // check for name (may want to check extension later) + while (false !== ($file = readdir($dh))) { // Read throug the directory. + if ('slide' == substr($file, 0, 5)) { + // Check for name (may want to check extension later). $path = $base.'/'.$file; if (is_readable($path)) { $pages[$path] = file_get_contents($path); @@ -170,43 +191,45 @@ function readdata($file, $courseid, $modname) { } } - ksort($pages); // order them by file name + ksort($pages); // Order them by file name. } - + if (empty($pages)) { return false; } - + return $pages; } +/* This function attempts to extract the content out of the slides + * the slides are ugly broken xml. and the xml is broken... yeah... + */ function extract_data($pages, $courseid, $lessonname, $modname) { - // this function attempts to extract the content out of the slides - // the slides are ugly broken xml. and the xml is broken... yeah... - + global $CFG; global $matches; $extratedpages = array(); - - // directory for images - make_mod_upload_directory($courseid); // make sure moddata is made - make_upload_directory($courseid.'/moddata/'.$modname, false); // we store our images in a subfolder in here - + + // Directory for images. + make_mod_upload_directory($courseid); // Make sure moddata is made. + // We store our images in a subfolder in here. + make_upload_directory($courseid.'/moddata/'.$modname, false); + $imagedir = $CFG->dataroot.'/'.$courseid.'/moddata/'.$modname; - + if ($CFG->slasharguments) { $imagelink = $CFG->wwwroot.'/file.php/'.$courseid.'/moddata/'.$modname; } else { $imagelink = $CFG->wwwroot.'/file.php?file=/'.$courseid.'/moddata/'.$modname; } - - // try to make a unique subfolder to store the images - $lessonname = str_replace(' ', '_', $lessonname); // get rid of spaces + + // Try to make a unique subfolder to store the images. + $lessonname = str_replace(' ', '_', $lessonname); // Get rid of spaces. $i = 0; - while(true) { + while (true) { if (!file_exists($imagedir.'/'.$lessonname.$i)) { - // ok doesnt exist so make the directory and update our paths + // Ok doesnt exist so make the directory and update our paths. mkdir($imagedir.'/'.$lessonname.$i); $imagedir = $imagedir.'/'.$lessonname.$i; $imagelink = $imagelink.'/'.$lessonname.$i; @@ -214,68 +237,71 @@ function extract_data($pages, $courseid, $lessonname, $modname) { } $i++; } - + foreach ($pages as $file => $content) { - // to make life easier on our preg_match_alls, we strip out all tags except - // for div and img (where our content is). We want div because sometimes we - // can identify the content in the div based on the div's class - - $tags = '
    '; // should also allow - $string = strip_tags($content,$tags); - //echo s($string); + /* to make life easier on our preg_match_alls, we strip out all tags except + * for div and img (where our content is). We want div because sometimes we + * can identify the content in the div based on the div's class + */ + + $tags = '
    '; // Should also allow . + $string = strip_tags($content, $tags); $matches = array(); - // this will look for a non nested tag that is closed - // want to allow (maybe more) tags but when we do that - // the preg_match messes up. + /* this will look for a non nested tag that is closed + * want to allow (maybe more) tags but when we do that + * the preg_match messes up. + */ preg_match_all("/(<([\w]+)[^>]*>)([^<\\2>]*)(<\/\\2>)/", $string, $matches); - //(<([\w]+)[^>]*>)([^<\\2>]*)(<\/\\2>) original pattern - //(<(div+)[^>]*>)[^() work in progress - $path_parts = pathinfo($file); - $file = substr($path_parts['basename'], 0, strpos($path_parts['basename'], '.')); // get rid of the extension + $pathparts = pathinfo($file); + // Get rid of the extension. + $file = substr($pathparts['basename'], 0, strpos($pathparts['basename'], '.')); $imgs = array(); - // this preg matches all images + // This preg matches all images. preg_match_all("/]*(src\=\"(".$file."\_image[^>^\"]*)\"[^>]*)>/i", $string, $imgs); - // start building our page + // Start building our page. $page = new stdClass; $page->title = ''; $page->contents = array(); $page->images = array(); - $page->source = $path_parts['basename']; // need for book only - - // this foreach keeps the style intact. Found it doesn't help much. But if you want back uncomment - // this foreach and uncomment the line with the comment imgstyle in it. Also need to comment out - // the $page->images[]... line in the next foreach - /*foreach ($imgs[1] as $img) { - $page->images[] = ''; - }*/ + $page->source = $pathparts['basename']; // Need for book only. + + /* This foreach keeps the style intact. + * Found it doesn't help much. But if you want back uncomment + * this foreach and uncomment the line with the comment imgstyle in it. + * Also need to comment out + * the $page->images[]... line in the next foreach + */ foreach ($imgs[2] as $img) { - copy($path_parts['dirname'].'/'.$img, $imagedir.'/'.$img); - $page->images[] = ""; // comment out this line if you are using the above foreach loop + copy($pathparts['dirname'].'/'.$img, $imagedir.'/'.$img); + // Comment out this line if you are using the above foreach loop. + $page->images[] = ""; } - for($i = 0; $i < count($matches[1]); $i++) { // go through all of our div matches - - $class = isolate_class($matches[1][$i]); // first step in isolating the class - - // check for any static classes + for ($i = 0; $i < count($matches[1]); $i++) { // Go through all of our div matches. + $class = isolate_class($matches[1][$i]); // First step in isolating the class. + + // Check for any static classes. switch ($class) { - case 'T': // class T is used for Titles + case 'T': // Class T is used for Titles. $page->title = $matches[3][$i]; break; - case 'B': // I would guess that all bullet lists would start with B then go to B1, B2, etc - case 'B1': // B1-B4 are just insurance, should just hit B and all be taken care of + // I would guess that all bullet lists would start with B then go to B1, B2, etc. + case 'B': + // B1-B4 are just insurance, should just hit B and all be taken care of. + case 'B1': case 'B2': case 'B3': case 'B4': - $page->contents[] = build_list('
      ', $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('
        ', $i, 0); break; default: - if ($matches[3][$i] != ' ') { // odd crap generated... sigh - if (substr($matches[3][$i], 0, 1) == ':') { // check for leading : ... hate MS ... - $page->contents[] = substr($matches[3][$i], 1); // get rid of : + if ($matches[3][$i] != ' ') { // Odd crap generated... sigh. + if (substr($matches[3][$i], 0, 1) == ':') {// Check for leading : ..hate MS . + $page->contents[] = substr($matches[3][$i], 1); // Get rid of :. } else { $page->contents[] = $matches[3][$i]; } @@ -284,94 +310,89 @@ function extract_data($pages, $courseid, $lessonname, $modname) { } } - // add the page to the array; + // Add the page to the array. $extratedpages[] = $page; - - } // end $pages foreach loop - + + } // End $pages foreach loop. + return $extratedpages; } -/** -A recursive function to build a html list -*/ +// A recursive function to build a html list. function build_list($list, &$i, $depth) { - global $matches; // not sure why I global this... - - while($i < count($matches[1])) { - + global $matches; // Not sure why I global this... + + while ($i < count($matches[1])) { $class = isolate_class($matches[1][$i]); - if (strstr($class, 'B')) { // make sure we are still working with bullet classes + if (strstr($class, 'B')) { // Make sure we are still working with bullet classes. if ($class == 'B') { - $this_depth = 0; // calling class B depth 0 + $thisdepth = 0; // Calling class B depth 0. } else { - // set the depth number. So B1 is depth 1 and B2 is depth 2 and so on - $this_depth = substr($class, 1); - if (!is_numeric($this_depth)) { - print_error( 'Depth not parsed!'); - } - } - if ($this_depth < $depth) { - // we are moving back a level in the nesting + // Set the depth number. So B1 is depth 1 and B2 is depth 2 and so on. + $thisdepth = substr($class, 1); + if (!is_numeric($thisdepth)) { + print_error( 'Depth not parsed!'); + } + if ($thisdepth < $depth) { + // We are moving back a level in the nesting. break; } - if ($this_depth > $depth) { - // we are moving in a lvl in nesting + if ($thisdepth > $depth) { + // We are moving in a lvl in nesting. $list .= '
          '; - $list = build_list($list, $i, $this_depth); - // once we return back, should go to the start of the while + $list = build_list($list, $i, $thisdepth); + // Once we return back, should go to the start of the while. continue; } - // no depth changes, so add the match to our list + // No depth changes, so add the match to our list. if ($cleanstring = ppt_clean_text($matches[3][$i])) { $list .= '
        • '.ppt_clean_text($matches[3][$i]).'
        • '; } $i++; } else { - // not a B class, so get out of here... + // Not a B class, so get out of here... break; } } - // end the list and return it + + // End the list and return it. $list .= '
        '; return $list; - } -/** -Given an html tag, this function will -*/ +// Given an html tag, this function will. function isolate_class($string) { - if($class = strstr($string, 'class=')) { // first step in isolating the class - $class = substr($class, strpos($class, '=')+1); // this gets rid of
        + // No spaces so nothing else in the div tag, cut off the >. return substr($class, 0, strpos($class, '>')); } } else { - // no class defined in the tag + // No class defined in the tag. return ''; } } -/** -This function strips off the random chars that ppt puts infront of bullet lists -*/ +// This function strips off the random chars that ppt puts infront of bullet lists. function ppt_clean_text($string) { - $chop = 1; // default: just a single char infront of the content - - // look for any other crazy things that may be infront of the content - if (strstr($string, '<') and strpos($string, '<') == 0) { // look for the < in the sting and make sure it is in the front - $chop = 4; // increase the $chop + $chop = 1; // Default: just a single char infront of the content. + + // Look for any other crazy things that may be infront of the content. + if (strstr($string, '<') and strpos($string, '<') == 0) { + // Look for the < in the sting and make sure it is in the front. + $chop = 4; // Increase the $chop. } - // may need to add more later.... - + // May need to add more later.... + $string = substr($string, $chop); - + if ($string != ' ') { return $string; } else { @@ -379,41 +400,36 @@ function ppt_clean_text($string) { } } -/** - Clean up the temp directory -*/ +// Clean up the temp directory. function clean_temp() { global $CFG; - // this function is broken, use it to clean up later - // should only clean up what we made as well because someone else could be importing ppt as well - //delDirContents($CFG->dataroot.'/temp/lesson'); + /* this function is broken, use it to clean up later + * should only clean up what we made as well because someone else could be importing ppt as well + * delDirContents($CFG->dataroot.'/temp/lesson'); + */ } - -/** - Creates objects an chapter object that is to be inserted into the database -*/ +// Creates objects an chapter object that is to be inserted into the database. function book_create_objects($pageobjects, $bookid) { - $chapters = array(); $chapter = new stdClass; - - // same for all chapters + + // Same for all chapters. $chapter->bookid = $bookid; - $chapter->pagenum = $DB->count_records('book_chapters', array( 'bookid' => $bookid))+1; + $chapter->pagenum = $DB->count_records('book_chapters', array( 'bookid' => $bookid)) + 1; $chapter->timecreated = time(); $chapter->timemodified = time(); $chapter->subchapter = 0; - $i = 1; + $i = 1; foreach ($pageobjects as $pageobject) { - $page = prep_page($pageobject, $i); // get title and contents - $chapter->importsrc = addslashes($pageobject->source); // add the source + $page = prep_page($pageobject, $i); // Get title and contents. + $chapter->importsrc = addslashes($pageobject->source); // Add the source. $chapter->title = $page->title; $chapter->content = $page->contents; - $chapters[] = $chapter; - - // increment our page number and our counter + $chapters[] = $chapter; + + // Increment our page number and our counter. $chapter->pagenum = $chapter->pagenum + 1; $i++; } @@ -421,44 +437,40 @@ function book_create_objects($pageobjects, $bookid) { return $chapters; } -/** - Builds the title and content strings from an object -*/ +// Builds the title and content strings from an object. function prep_page($pageobject, $count) { if ($pageobject->title == '') { - $page->title = "Page $count"; // no title set so make a generic one + $page->title = "Page $count"; // No title set so make a generic one. } else { - $page->title = addslashes($pageobject->title); + $page->title = addslashes($pageobject->title); } - + $page->contents = ''; - - // nab all the images first + + // Nab all the images first. foreach ($pageobject->images as $image) { $image = str_replace("\n", '', $image); $image = str_replace("\r", '', $image); - $image = str_replace("'", '"', $image); // imgstyle - + $image = str_replace("'", '"', $image); // Imgstyle. + $page->contents .= addslashes($image); } - // go through the contents array and put

        tags around each element and strip out \n which I have found to be uneccessary + // Go through the contents array and put

        tags around each element and strip out \n which I have found to be uneccessary. foreach ($pageobject->contents as $content) { $content = str_replace("\n", '', $content); $content = str_replace("\r", '', $content); - $content = str_replace(' ', '', $content); // puts in returns? + $content = str_replace(' ', '', $content); // Puts in returns? $content = '

        '.$content.'

        '; $page->contents .= addslashes($content); } return $page; } -/** - Save the chapter objects to the database -*/ +// Save the chapter objects to the database. function book_save_objects($chapters, $bookid, $pageid='0') { global $DB; - // nothing fancy, just save them all in order + // Nothing fancy, just save them all in order. foreach ($chapters as $chapter) { if (!$chapter->id = $DB->insert_record('book_chapters', $chapter)) { print_error('Could not update your book'); diff --git a/bookquiz/play.php b/bookquiz/play.php index b5e138b..d80c265 100755 --- a/bookquiz/play.php +++ b/bookquiz/play.php @@ -1,382 +1,392 @@ -lastchapterid = 0; - $bookquiz->id = $attempt->id; - $bookquiz->bookid = $game->bookid; - - if( !game_insert_record( 'game_bookquiz', $bookquiz)){ - print_error( 'game_bookquiz_continue: error inserting in game_bookquiz'); - } - - return game_bookquiz_play( $id, $game, $attempt, $bookquiz, 0, $context); -} - -function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context) -{ - global $DB, $OUTPUT, $cm; - - if( $bookquiz->lastchapterid == 0){ - game_bookquiz_play_computelastchapter( $game, $bookquiz); - - if( $bookquiz->lastchapterid == 0){ - print_error( get_string( 'bookquiz_empty', 'game')); - } - } - if( $chapterid == 0){ - $chapterid = $bookquiz->lastchapterid; - }else - { - if( ($DB->set_field( 'game_bookquiz', 'lastchapterid', $chapterid, array( 'id' => $bookquiz->id))) == false){ - print_error( "Can't update table game_bookquiz with lastchapterid to $chapterid"); - } - } - - $book = $DB->get_record( 'book', array('id' => $game->bookid)); - if( !$chapter = $DB->get_record( 'book_chapters', array('id' => $chapterid))){ - print_error('Error reading book chapters.'); - } - $select = "bookid = $game->bookid AND hidden = 0"; - $chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden'); - - $okchapters = array(); - if( ($recs = $DB->get_records( 'game_bookquiz_chapters', array( 'attemptid' => $attempt->id))) != false){ - foreach( $recs as $rec){ - //1 means correct answer - $okchapters[ $rec->chapterid] = 1; - } - } - //2 means current - //$okchapters[ $chapterid] = 2; - $showquestions = false; - $a = array( 'gameid' => $game->id, 'chapterid' => $chapterid); - if( ($questions = $DB->get_records( 'game_bookquiz_questions', $a)) === false){ - if( !array_key_exists( $chapterid, $okchapters)){ - $okchapters[ $chapterid] = 1; - $newrec = new stdClass(); - $newrec->attemptid = $attempt->id; - $newrec->chapterid = $chapterid; - - if( !$DB->insert_record( 'game_bookquiz_chapters', $newrec)){ - print_error( "Can't insert to table game_bookquiz_chapters"); - } - } - }else - { - //Have to select random one question - $questionid = game_bookquiz_selectrandomquestion( $questions); - if( $questionid != 0){ - $showquestions = true; - } - } - - -/// prepare chapter navigation icons -$previd = null; -$nextid = null; -$found = 0; -$scoreattempt = 0; -$lastid = 0; -foreach ($chapters as $ch) { - $scoreattempt++; - if ($found) { - $nextid= $ch->id; - break; - } - if ($ch->id == $chapter->id) { - $found = 1; - } - if (!$found) { - $previd = $ch->id; - } - $lastid = $ch->id; -} -if ($ch == current($chapters)) { - $nextid = $ch->id; -} -if( count( $chapters)){ - $scoreattempt = ($scoreattempt-1) / count( $chapters); -} - -$chnavigation = ''; - - -if ($previd) { - $chnavigation .= ''.get_string('navprev', 'book').''; -} else { - $chnavigation .= ''; -} - -$nextbutton = ''; -if ($nextid) { - if( !$showquestions){ - $chnavigation .= ''.get_string('navnext', 'book').''; - $nextbutton = '
        '; - $nextbutton .= '
        '; - $nextbutton .= ''."\r\n"; - $nextbutton .= ''."\r\n"; - $nextbutton .= ''; - $nextbutton .= '
        '; - $showquestions = false; - game_updateattempts_maxgrade( $game, $attempt, $scoreattempt, 0); - } -} else { - game_updateattempts_maxgrade( $game, $attempt, 1, 0); - $sec = ''; - if( !isset( $cm)) - { - $cm = get_coursemodule_from_instance('game', $game->id, $game->course); - } - if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) { - $sec = $section->section; - } - - if (! $cm = $DB->get_record('course_modules', array( 'id' => $id))) { - print_error("Course Module ID was incorrect id=$id"); - } - $chnavigation .= 'pix_url('bookquiz/nav_exit', 'mod_game').'" class="bigicon" alt="'.get_string('navexit', 'book').'" />'; -} - -require( 'toc.php'); -$tocwidth = '10%'; - - if( $showquestions){ - if( $game->param3 == 0) - game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context); - } - - -?> - - - - - - - - - - - - - -
        - - - - - -
        -
        - box_start('generalbox'); - echo $toc; - echo $OUTPUT->box_end(); - ?> - - box_start('generalbox'); - $content = ''; - if (!$book->customtitles) { - if ($currsubtitle == ' ') { - $content .= '

        '.$currtitle.'

        '; - } else { - $content .= '

        '.$currtitle.'
        '.$currsubtitle.'

        '; - } - } - $cmbook = get_coursemodule_from_instance( 'book', $game->bookid, $game->course); - $modcontext = game_get_context_module_instance( $cmbook->id); - $content .= game_filterbook( $chapter->content, $chapter->id, $modcontext->id, $game->course); - - $nocleanoption = new object(); - $nocleanoption->noclean = true; - echo '
        '; - if( $nextbutton != ''){ - echo $nextbutton; - } - echo format_text($content, FORMAT_HTML, $nocleanoption); - if( $nextbutton != ''){ - echo $nextbutton; - } - - echo '
        '; - echo $OUTPUT->box_end(); - /// lower navigation - echo '

        '.$chnavigation.'

        '; - ?> -
        - -param3 != 0) - game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context); - } -} - -function game_bookquiz_play_computelastchapter( $game, &$bookquiz) -{ - global $DB; - - if( $game->bookid == 0) - { - print_error( 'Not defined a book on this game'); - } - - $pagenum = $DB->get_field( 'book_chapters', 'min(pagenum) as p', array('bookid' => $game->bookid)); - - if( $pagenum){ - $bookquiz->lastchapterid = $DB->get_field( 'book_chapters', 'id', array('bookid' => $game->bookid, 'pagenum' => $pagenum)); - - if( $bookquiz->lastchapterid){ - //update the data in table game_bookquiz - if( ($DB->set_field( 'game_bookquiz', 'lastchapterid', $bookquiz->lastchapterid, array('id' => $bookquiz->id))) == false){ - print_error( "Can't update table game_bookquiz with lastchapterid to $bookquiz->lastchapterid"); - } - } - } -} - -function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapterid, $scoreattempt, $game, $context) -{ - $onlyshow = false; - $showsolution = false; - - $questionlist = $questionid; - $questions = game_sudoku_getquestions( $questionlist); - - global $CFG; - - /// Start the form - echo "wwwroot}/mod/game/attempt.php\" onclick=\"this.autocomplete='off'\">\n"; - if( ($onlyshow === false) and ($showsolution === false)){ - echo "
        \n"; - } - - // Add a hidden field with the quiz id - echo '
        '; - echo '\n"; - echo ''; - echo ''; - echo ''; - echo ''; - - /// Print all the questions - - // Add a hidden field with questionids - echo '\n"; - - $number=0; - foreach ($questions as $question) { - game_print_question( $game, $question, $context); - } - echo "
        "; - - // Finish the form - echo '
        '; - if( ($onlyshow === false) and ($showsolution === false)){ - echo "
        \n"; - } - - echo "\n"; -} - -function game_bookquiz_selectrandomquestion( $questions) -{ - global $DB; - - $categorylist = ''; - if( $questions == false){ - return 0; - } - - foreach( $questions as $rec){ - $categorylist .= ',' . $rec->questioncategoryid; - } - $select = 'category in ('.substr( $categorylist, 1). ") AND qtype in ('shortanswer', 'truefalse', 'multichoice')"; - if( ($recs = $DB->get_records_select( 'question', $select, null, '', 'id,id')) == false){ - return 0; - } - $a = array(); - foreach( $recs as $rec){ - $a[ $rec->id] = $rec->id; - } - - if( count( $a) == 0){ - return 0; - }else - { - return array_rand( $a); - } -} - -function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $context) -{ - global $USER, $DB; - - $scoreattempt = optional_param('scoreattempt', 0, PARAM_INT); - $responses = data_submitted(); - - $questionlist = $responses->questionids; - - $questions = game_sudoku_getquestions( $questionlist); - $grades = game_grade_questions( $questions); - - $scorequestion = 0; - $scoreattempt = 0; - - $chapterid = required_param('chapterid', PARAM_INT); - $nextchapterid = required_param('nextchapterid', PARAM_INT); - - foreach($questions as $question) { - if( !array_key_exists( $question->id, $grades)){ - //no answered - continue; - } - $grade = $grades[ $question->id]; - if( $grade->grade < 0.99){ - continue; - } - - //found one correct answer - if( !$DB->get_field( 'game_bookquiz_chapters', 'id', array( 'attemptid' => $attempt->id, 'chapterid' => $chapterid))) - { - $newrec = new stdClass(); - $newrec->attemptid = $attempt->id; - $newrec->chapterid = $chapterid; - if( !$DB->insert_record( 'game_bookquiz_chapters', $newrec, false)){ - print_object( $newrec); - print_error( "Can't insert to table game_bookquiz_chapters"); - } - } - //Have to go to next page. - $bookquiz->lastchapterid = $nextchapterid; - $scorequestion = 1; - break; - } - - $query = new stdClass(); - $query->id = 0; - $query->attemptid = $attempt->id; - $query->gameid = $game->id; - $query->userid = $USER->id; - $query->sourcemodule = 'question'; - $query->questionid = $question->id; - $query->glossaryentryid = 0; - $query->questiontext = $question->questiontext; - $query->timelastattempt = time(); - game_update_queries( $game, $attempt, $query, $scorequestion, ''); - - game_updateattempts( $game, $attempt, $scoreattempt, 0); - - game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $bookquiz->lastchapterid, $context); -} +. + +function game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $chapterid, $context) { + if ($attempt != false and $bookquiz != false) { + return game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context); + } + + if ($attempt == false) { + $attempt = game_addattempt( $game); + } + + $bookquiz = new stdClass(); + $bookquiz->lastchapterid = 0; + $bookquiz->id = $attempt->id; + $bookquiz->bookid = $game->bookid; + + if ( !game_insert_record( 'game_bookquiz', $bookquiz)) { + print_error( 'game_bookquiz_continue: error inserting in game_bookquiz'); + } + + return game_bookquiz_play( $id, $game, $attempt, $bookquiz, 0, $context); +} + +function game_bookquiz_play( $id, $game, $attempt, $bookquiz, $chapterid, $context) { + global $DB, $OUTPUT, $cm; + + if ($bookquiz->lastchapterid == 0) { + game_bookquiz_play_computelastchapter( $game, $bookquiz); + + if ($bookquiz->lastchapterid == 0) { + print_error( get_string( 'bookquiz_empty', 'game')); + } + } + if ($chapterid == 0) { + $chapterid = $bookquiz->lastchapterid; + } else { + if (($DB->set_field( 'game_bookquiz', 'lastchapterid', $chapterid, array( 'id' => $bookquiz->id))) == false) { + print_error( "Can't update table game_bookquiz with lastchapterid to $chapterid"); + } + } + + $book = $DB->get_record( 'book', array('id' => $game->bookid)); + if (!$chapter = $DB->get_record( 'book_chapters', array('id' => $chapterid))) { + print_error('Error reading book chapters.'); + } + $select = "bookid = $game->bookid AND hidden = 0"; + $chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden'); + + $okchapters = array(); + if (($recs = $DB->get_records( 'game_bookquiz_chapters', array( 'attemptid' => $attempt->id))) != false) { + foreach ($recs as $rec) { + // The 1 means correct answer. + $okchapters[ $rec->chapterid] = 1; + } + } + + // The 2 means current. + $showquestions = false; + $a = array( 'gameid' => $game->id, 'chapterid' => $chapterid); + if (($questions = $DB->get_records( 'game_bookquiz_questions', $a)) === false) { + if (!array_key_exists( $chapterid, $okchapters)) { + $okchapters[ $chapterid] = 1; + $newrec = new stdClass(); + $newrec->attemptid = $attempt->id; + $newrec->chapterid = $chapterid; + + if (!$DB->insert_record( 'game_bookquiz_chapters', $newrec)) { + print_error( "Can't insert to table game_bookquiz_chapters"); + } + } + } else { + // Have to select random one question. + $questionid = game_bookquiz_selectrandomquestion( $questions); + if ($questionid != 0) { + $showquestions = true; + } + } + + // Prepare chapter navigation icons. + $previd = null; + $nextid = null; + $found = 0; + $scoreattempt = 0; + $lastid = 0; + foreach ($chapters as $ch) { + $scoreattempt++; + if ($found) { + $nextid = $ch->id; + break; + } + if ($ch->id == $chapter->id) { + $found = 1; + } + if (!$found) { + $previd = $ch->id; + } + $lastid = $ch->id; + } + if ($ch == current($chapters)) { + $nextid = $ch->id; + } + if (count( $chapters)) { + $scoreattempt = ($scoreattempt - 1) / count( $chapters); + } + + $chnavigation = ''; + + if ($previd) { + $chnavigation .= ''.get_string('navprev', 'book').''; + } else { + $chnavigation .= ''; + } + + $nextbutton = ''; + if ($nextid) { + if (!$showquestions) { + $chnavigation .= ''.get_string('navnext', 'book').''; + $nextbutton = '
        '; + $nextbutton .= '
        '; + $nextbutton .= ''."\r\n"; + $nextbutton .= ''."\r\n"; + $nextbutton .= ''; + $nextbutton .= '
        '; + $showquestions = false; + game_updateattempts_maxgrade( $game, $attempt, $scoreattempt, 0); + } + } else { + game_updateattempts_maxgrade( $game, $attempt, 1, 0); + $sec = ''; + if (!isset( $cm)) { + $cm = get_coursemodule_from_instance('game', $game->id, $game->course); + } + + if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) { + $sec = $section->section; + } + + if (! $cm = $DB->get_record('course_modules', array( 'id' => $id))) { + print_error("Course Module ID was incorrect id=$id"); + } + $chnavigation .= 'pix_url('bookquiz/nav_exit', 'mod_game'). + '" class="bigicon" alt="'.get_string('navexit', 'book').'" />'; + } + + require( 'toc.php'); + $tocwidth = '10%'; + + if ($showquestions) { + if ($game->param3 == 0) { + game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context); + } + } + +?> + + + + + + + + + + + + + +
        + + + + + +
        +
        + box_start('generalbox'); + echo $toc; + echo $OUTPUT->box_end(); + ?> + +box_start('generalbox'); + $content = ''; + if (!$book->customtitles) { + if ($currsubtitle == ' ') { + $content .= '

        '.$currtitle.'

        '; + } else { + $content .= '

        '.$currtitle.'
        '.$currsubtitle.'

        '; + } + } + $cmbook = get_coursemodule_from_instance( 'book', $game->bookid, $game->course); + $modcontext = game_get_context_module_instance( $cmbook->id); + $content .= game_filterbook( $chapter->content, $chapter->id, $modcontext->id, $game->course); + + $nocleanoption = new object(); + $nocleanoption->noclean = true; + echo '
        '; + if ($nextbutton != '') { + echo $nextbutton; + } + echo format_text($content, FORMAT_HTML, $nocleanoption); + if ($nextbutton != '') { + echo $nextbutton; + } + + echo '
        '; + echo $OUTPUT->box_end(); + // Lower navigation. + echo '

        '.$chnavigation.'

        '; +?> +
        + +param3 != 0) { + game_bookquiz_showquestions( $id, $questionid, $chapter->id, $nextid, $scoreattempt, $game, $context); + } + } +} + +function game_bookquiz_play_computelastchapter( $game, &$bookquiz) { + global $DB; + + if ($game->bookid == 0) { + print_error( 'Not defined a book on this game'); + } + + $pagenum = $DB->get_field( 'book_chapters', 'min(pagenum) as p', array('bookid' => $game->bookid)); + + if ($pagenum) { + $bookquiz->lastchapterid = $DB->get_field( 'book_chapters', 'id', array('bookid' => $game->bookid, 'pagenum' => $pagenum)); + + if ($bookquiz->lastchapterid) { + // Update the data in table game_bookquiz. + if (($DB->set_field( 'game_bookquiz', 'lastchapterid', $bookquiz->lastchapterid, + array('id' => $bookquiz->id))) == false) { + print_error( "Can't update table game_bookquiz with lastchapterid to $bookquiz->lastchapterid"); + } + } + } +} + +function game_bookquiz_showquestions( $id, $questionid, $chapterid, $nextchapterid, $scoreattempt, $game, $context) { + $onlyshow = false; + $showsolution = false; + + $questionlist = $questionid; + $questions = game_sudoku_getquestions( $questionlist); + + global $CFG; + + // Start the form. + echo "wwwroot}/mod/game/attempt.php\" ". + " onclick=\"this.autocomplete='off'\">\n"; + if (($onlyshow === false) and ($showsolution === false)) { + echo "
        \n"; + } + + // Add a hidden field with the quiz id. + echo '
        '; + echo '\n"; + echo ''; + echo ''; + echo ''; + echo ''; + + // Print all the questions. + + // Add a hidden field with questionids. + echo '\n"; + + $number = 0; + foreach ($questions as $question) { + game_print_question( $game, $question, $context); + } + echo "
        "; + + // Finish the form. + echo '
    '; + if (($onlyshow === false) and ($showsolution === false)) { + echo "
    \n"; + } + + echo "\n"; +} + +function game_bookquiz_selectrandomquestion( $questions) { + global $DB; + + $categorylist = ''; + if ($questions == false) { + return 0; + } + + foreach ($questions as $rec) { + $categorylist .= ',' . $rec->questioncategoryid; + } + $select = 'category in ('.substr( $categorylist, 1). ") AND qtype in ('shortanswer', 'truefalse', 'multichoice')"; + if (($recs = $DB->get_records_select( 'question', $select, null, '', 'id,id')) == false) { + return 0; + } + $a = array(); + foreach ($recs as $rec) { + $a[ $rec->id] = $rec->id; + } + + if (count( $a) == 0) { + return 0; + } else { + return array_rand( $a); + } +} + +function game_bookquiz_check_questions( $id, $game, $attempt, $bookquiz, $context) { + global $USER, $DB; + + $scoreattempt = optional_param('scoreattempt', 0, PARAM_INT); + $responses = data_submitted(); + + $questionlist = $responses->questionids; + + $questions = game_sudoku_getquestions( $questionlist); + $grades = game_grade_questions( $questions); + + $scorequestion = 0; + $scoreattempt = 0; + + $chapterid = required_param('chapterid', PARAM_INT); + $nextchapterid = required_param('nextchapterid', PARAM_INT); + + foreach ($questions as $question) { + if (!array_key_exists( $question->id, $grades)) { + // No answered. + continue; + } + $grade = $grades[ $question->id]; + if ($grade->grade < 0.99) { + continue; + } + + // Found one correct answer. + if (!$DB->get_field( 'game_bookquiz_chapters', 'id', array( 'attemptid' => $attempt->id, 'chapterid' => $chapterid))) { + $newrec = new stdClass(); + $newrec->attemptid = $attempt->id; + $newrec->chapterid = $chapterid; + if (!$DB->insert_record( 'game_bookquiz_chapters', $newrec, false)) { + print_error( "Can't insert to table game_bookquiz_chapters"); + } + } + + // Have to go to next page. + $bookquiz->lastchapterid = $nextchapterid; + $scorequestion = 1; + break; + } + + $query = new stdClass(); + $query->id = 0; + $query->attemptid = $attempt->id; + $query->gameid = $game->id; + $query->userid = $USER->id; + $query->sourcemodule = 'question'; + $query->questionid = $question->id; + $query->glossaryentryid = 0; + $query->questiontext = $question->questiontext; + $query->timelastattempt = time(); + game_update_queries( $game, $attempt, $query, $scorequestion, ''); + + game_updateattempts( $game, $attempt, $scoreattempt, 0); + + game_bookquiz_continue( $id, $game, $attempt, $bookquiz, $bookquiz->lastchapterid, $context); +} diff --git a/bookquiz/questions.php b/bookquiz/questions.php index dc65371..5a83c0f 100755 --- a/bookquiz/questions.php +++ b/bookquiz/questions.php @@ -1,4 +1,19 @@ -. + /** * The script supports book * @@ -7,96 +22,91 @@ * @package game **/ - require_once("../../../config.php"); - require_once( "../headergame.php"); - require_once("../locallib.php"); +require_once("../../../config.php"); +require_once( "../headergame.php"); +require_once("../locallib.php"); + +$attempt = game_getattempt( $game, $detail); +if ($game->bookid == 0) { + print_error( get_string( 'bookquiz_not_select_book', 'game')); +} + +if ($form = data_submitted()) { // Filename. + $ids = explode( ',', $form->ids); + game_bookquiz_save( $game->id, $game->bookid, $ids, $form); +} - $attempt = game_getattempt( $game, $detail); - if( $game->bookid == 0){ - print_error( get_string( 'bookquiz_not_select_book', 'game')); +// Print upload form. +$OUTPUT->heading( $course->fullname); + +$select = "gameid={$game->id}"; +$categories = array(); +if (($recs = $DB->get_records_select( 'game_bookquiz_questions', $select, null, '', 'chapterid,questioncategoryid')) != false) { + foreach ($recs as $rec) { + $categories[ $rec->chapterid] = $rec->questioncategoryid; } +} + +$context = game_get_context_course_instance( $COURSE->id); +$select = " contextid in ($context->id)"; - if ($form = data_submitted()) - { /// Filename - $ids = explode( ',', $form->ids); - game_bookquiz_save( $game->id, $game->bookid, $ids, $form); - - //redirect("{$CFG->wwwroot}/mod/game/bookquiz/questions.php?id=$cm->id", '', 0); +$a = array(); +if ($recs = $DB->get_records_select( 'question_categories', $select, null, 'id,name')) { + foreach ($recs as $rec) { + $s = $rec->name; + if (($count = $DB->count_records( 'question', array( 'category' => $rec->id))) != 0) { + $s .= " ($count)"; + } + $a[ $rec->id] = $s; } +} - /// Print upload form - - $OUTPUT->heading( $course->fullname); - - $select = "gameid={$game->id}"; - $categories = array(); - if( ($recs = $DB->get_records_select( 'game_bookquiz_questions', $select, null, '', 'chapterid,questioncategoryid')) != false){ - foreach( $recs as $rec){ - $categories[ $rec->chapterid] = $rec->questioncategoryid; - } - } - - $context = game_get_context_course_instance( $COURSE->id); - $select = " contextid in ($context->id)"; - - $a = array(); - if( $recs = $DB->get_records_select( 'question_categories', $select, null, 'id,name')){ - foreach( $recs as $rec){ - $s = $rec->name; - if( ($count = $DB->count_records( 'question', array( 'category' => $rec->id))) != 0){ - $s .= " ($count)"; - } - $a[ $rec->id] = $s; - } +$sql = "SELECT chapterid, COUNT(*) as c ". + "FROM {game_bookquiz_questions} gbq,{question} q ". + "WHERE gbq.questioncategoryid=q.category ". + "AND gameid=$game->id ". + "GROUP BY chapterid"; +$numbers = array(); +if (($recs = $DB->get_records_sql( $sql)) != false) { + foreach ($recs as $rec) { + $numbers[ $rec->chapterid] = $rec->c; + } +} + +echo '
    '; +echo ''; +echo ''; +echo ''; +echo ''; +echo ''; +echo "\r\n"; +$ids = ''; +if (($recs = $DB->get_records( 'book_chapters', array('bookid' => $game->bookid), 'pagenum', 'id,title')) != false) { + foreach ($recs as $rec) { + echo ''; + echo ''; + echo ''; + + echo '
    '.get_string( 'bookquiz_chapters', 'game').'
    '.get_string( 'bookquiz_categories', 'game').'
    '.get_string( 'bookquiz_numquestions', 'game').'
    '.$rec->title.''; + if (array_key_exists( $rec->id, $categories)) { + $categoryid = $categories[ $rec->id]; + } else { + $categoryid = 0; + } + echo game_showselectcontrol( 'categoryid_'.$rec->id, $a, $categoryid, ''); + echo ''; + if (array_key_exists( $rec->id, $numbers)) { + echo '
    '.$numbers[ $rec->id].'
    '; + } else { + echo ' '; } - - $sql = "SELECT chapterid, COUNT(*) as c ". - "FROM {game_bookquiz_questions} gbq,{question} q ". - "WHERE gbq.questioncategoryid=q.category ". - "AND gameid=$game->id ". - "GROUP BY chapterid"; - $numbers = array(); - if( ($recs = $DB->get_records_sql( $sql)) != false){ - foreach( $recs as $rec){ - $numbers[ $rec->chapterid] = $rec->c; - } - } - - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo ''; - echo "\r\n"; - $ids = ''; - if( ($recs =$DB->get_records( 'book_chapters', array('bookid' => $game->bookid), 'pagenum', 'id,title')) != false) - { - foreach( $recs as $rec){ - echo ''; - echo ''; - echo ''; - - echo ''; - - echo "\r\n"; - - $ids .= ','.$rec->id; - } - } + echo ''; + + echo "\r\n"; + + $ids .= ','.$rec->id; + } +} ?>
    '.get_string( 'bookquiz_chapters', 'game').'
    '.get_string( 'bookquiz_categories', 'game').'
    '.get_string( 'bookquiz_numquestions', 'game').'
    '.$rec->title.''; - if( array_key_exists( $rec->id, $categories)) - $categoryid = $categories[ $rec->id]; - else - $categoryid = 0; - echo game_showselectcontrol( 'categoryid_'.$rec->id, $a, $categoryid, ''); - echo ''; - if( array_key_exists( $rec->id, $numbers)){ - echo '
    '.$numbers[ $rec->id].'
    '; - }else - { - echo ' '; - } - echo '

    @@ -111,70 +121,66 @@ footer($course); +echo $OUTPUT->footer($course); -function game_bookquiz_save( $gameid, $bookid, $ids, $form) -{ +function game_bookquiz_save( $gameid, $bookid, $ids, $form) { global $DB; - $questions = array(); - $recids = array(); - if( ($recs = $DB->get_records( 'game_bookquiz_questions', array( 'gameid' => $gameid), '', 'id,chapterid,questioncategoryid')) != false){ - foreach( $recs as $rec){ - $questions[ $rec->chapterid] = $rec->questioncategoryid; - $recids[ $rec->chapterid] = $rec->id; - } - } - - foreach( $ids as $chapterid){ - $name = 'categoryid_'.$chapterid; - $categoryid = $form->$name; - - if( !array_key_exists( $chapterid, $questions)){ - - if( $categoryid == 0){ - continue; - } - - $rec = new stdClass(); - $rec->gameid = $gameid; - $rec->chapterid = $chapterid; - $rec->questioncategoryid = $categoryid; - - if (($newid=$DB->insert_record('game_bookquiz_questions', $rec)) == false) { - print_object( $rec); - print_error( "Can't insert to game_bookquiz_questions"); - } - continue; - } - - $cat = $questions[ $chapterid]; - if( $cat == $categoryid){ - $recids[ $chapterid] = 0; - continue; - } - - if( $categoryid == 0){ - if( !delete_records( 'game_bookquiz_questions', 'id', $recids[ $chapterid])){ - print_error( "Can't delete game_bookquiz_questions"); - } - }else - { - $updrec = new StdClass; - $updrec->id = $recids[ $chapterid]; - $updrec->questioncategoryid = $categoryid; - if (($DB->update_record( 'game_bookquiz_questions', $updrec)) == false) { - print_object( $rec); - print_error( "Can't update game_bookquiz_questions"); - } - } - - $recids[ $chapterid] = 0; - } - - foreach( $recids as $chapterid => $id){ - if( $id == 0){ - continue; - } - } + $questions = array(); + $recids = array(); + if (($recs = $DB->get_records( 'game_bookquiz_questions', + array( 'gameid' => $gameid), '', 'id,chapterid,questioncategoryid')) != false) { + foreach ($recs as $rec) { + $questions[ $rec->chapterid] = $rec->questioncategoryid; + $recids[ $rec->chapterid] = $rec->id; + } + } + + foreach ($ids as $chapterid) { + $name = 'categoryid_'.$chapterid; + $categoryid = $form->$name; + + if (!array_key_exists( $chapterid, $questions)) { + if ($categoryid == 0) { + continue; + } + + $rec = new stdClass(); + $rec->gameid = $gameid; + $rec->chapterid = $chapterid; + $rec->questioncategoryid = $categoryid; + + if (($newid = $DB->insert_record('game_bookquiz_questions', $rec)) == false) { + print_error( "Can't insert to game_bookquiz_questions"); + } + continue; + } + + $cat = $questions[ $chapterid]; + if ($cat == $categoryid) { + $recids[ $chapterid] = 0; + continue; + } + + if ($categoryid == 0) { + if (!delete_records( 'game_bookquiz_questions', 'id', $recids[ $chapterid])) { + print_error( "Can't delete game_bookquiz_questions"); + } + } else { + $updrec = new StdClass; + $updrec->id = $recids[ $chapterid]; + $updrec->questioncategoryid = $categoryid; + if (($DB->update_record( 'game_bookquiz_questions', $updrec)) == false) { + print_error( "Can't update game_bookquiz_questions"); + } + } + + $recids[ $chapterid] = 0; + } + + foreach ($recids as $chapterid => $id) { + if ($id == 0) { + continue; + } + } } diff --git a/bookquiz/toc.php b/bookquiz/toc.php index 9b72832..9f146df 100755 --- a/bookquiz/toc.php +++ b/bookquiz/toc.php @@ -1,33 +1,48 @@ -. defined('MOODLE_INTERNAL') or die('Direct access to this script is forbidden.'); - + define('NUM_NONE', '0'); define('NUM_NUMBERS', '1'); define('NUM_BULLETS', '2'); define('NUM_INDENTED', '3'); -/// included from mod/book/view.php and print.php -/// -/// uses: -/// $chapters - all book chapters -/// $chapter - may be false -/// $cm - course module -/// $book - book -/// $edit - force editing view - -/// fills: -/// $toc -/// $title (not for print) +/* Included from mod/book/view.php and print.php. + * + * uses: + * $chapters - all book chapters + * $chapter - may be false + * $cm - course module + * $book - book + * $edit - force editing view + * + * fills: + * $toc + * $title (not for print) + */ -$currtitle = ''; //active chapter title (plain text) -$currsubtitle = ''; //active subchapter if any +$currtitle = ''; // Active chapter title (plain text). +$currsubtitle = ''; // Active subchapter if any. $prevtitle = ' '; -$toc = ''; //representation of toc (HTML) +$toc = ''; // Representation of toc (HTML). -$nch = 0; //chapter number -$ns = 0; //subchapter number +$nch = 0; // Chapter number. +$ns = 0; // Subchapter number. $title = ''; $first = 1; @@ -36,22 +51,22 @@ if (!isset($print)) { } switch ($book->numbering) { - case NUM_NONE: - $toc .= '
    '; - break; - case NUM_NUMBERS: - $toc .= '
    '; - break; - case NUM_BULLETS: - $toc .= '
    '; - break; - case NUM_INDENTED: - $toc .= '
    '; - break; + case NUM_NONE: + $toc .= '
    '; + break; + case NUM_NUMBERS: + $toc .= '
    '; + break; + case NUM_BULLETS: + $toc .= '
    '; + break; + case NUM_INDENTED: + $toc .= '
    '; + break; } - -if ($print) { ///TOC for printing +if ($print) { + // TOC for printing. $toc .= ''; if ($book->customtitles) { $toc .= '

    '.get_string('toc', 'book').'

    '; @@ -60,7 +75,7 @@ if ($print) { ///TOC for printing } $titles = array(); $toc .= '
      '; - foreach($chapters as $ch) { + foreach ($chapters as $ch) { $title = trim(strip_tags($ch->title)); if (!$ch->hidden) { if (!$ch->subchapter) { @@ -68,13 +83,13 @@ if ($print) { ///TOC for printing $ns = 0; $toc .= ($first) ? '
    • ' : '
  • '; if ($book->numbering == NUM_NUMBERS) { - $title = "$nch $title"; + $title = "$nch $title"; } } else { $ns++; $toc .= ($first) ? '
    • ' : '
    • '; if ($book->numbering == NUM_NUMBERS) { - $title = "$nch.$ns $title"; + $title = "$nch.$ns $title"; } } $titles[$ch->id] = $title; @@ -84,9 +99,10 @@ if ($print) { ///TOC for printing } } $toc .= '
  • '; -} else { //normal students view +} else { + // Normal students view. $toc .= '
      '; - foreach($chapters as $ch) { + foreach ($chapters as $ch) { $title = trim(strip_tags($ch->title)); if (!$ch->hidden) { if (!$ch->subchapter) { @@ -96,7 +112,7 @@ if ($print) { ///TOC for printing if ($book->numbering == NUM_NUMBERS) { $title = "$nch $title"; } - $prevtitle = $title; + $prevtitle = $title; } else { $ns++; $toc .= ($first) ? '
      • ' : '
      • '; @@ -114,12 +130,12 @@ if ($print) { ///TOC for printing $currsubtitle = ' '; } } else { - if( array_key_exists( $ch->id, $okchapters)){ - $toc .= ''.$title.''; - }else - { - $toc .= htmlspecialchars($title); - } + if (array_key_exists( $ch->id, $okchapters)) { + $toc .= ''.$title.''; + } else { + $toc .= htmlspecialchars($title); + } } $toc .= (!$ch->subchapter) ? '
          ' : ''; $first = 0; @@ -130,6 +146,4 @@ if ($print) { ///TOC for printing $toc .= '
    '; -$toc = str_replace('
      ', '', $toc); //cleanup of invalid structures - -?> +$toc = str_replace('
        ', '', $toc); // Cleanup of invalid structures. diff --git a/bookquiz/view.php b/bookquiz/view.php index 4d02d93..78289a9 100755 --- a/bookquiz/view.php +++ b/bookquiz/view.php @@ -1,20 +1,35 @@ -. require_once('../../config.php'); require_once('lib.php'); -$id = required_param('id', PARAM_INT); // Course Module ID -$chapterid = optional_param('chapterid', 0, PARAM_INT); // Chapter ID -$edit = optional_param('edit', -1, PARAM_BOOL); // Edit mode +$id = required_param('id', PARAM_INT); // Course Module ID. +$chapterid = optional_param('chapterid', 0, PARAM_INT); // Chapter ID. +$edit = optional_param('edit', -1, PARAM_BOOL); // Edit mode. -// ========================================================================= -// security checks START - teachers edit; students view -// ========================================================================= +/* ========================================================================= + * security checks START - teachers edit; students view + * ========================================================================= + */ if (!$cm = get_coursemodule_from_id('book', $id)) { print_error('Course Module ID was incorrect'); } -if (!$course = $DB->get_record('course', array( 'id'=> $cm->course))) { +if (!$course = $DB->get_record('course', array( 'id' => $cm->course))) { print_error('Course is misconfigured'); } @@ -26,13 +41,14 @@ require_course_login($course, true, $cm); $context = get_context_instance(CONTEXT_MODULE, $cm->id); -/// read chapters +// Read chapters. $select = $allowedit ? "bookid = $book->id" : "bookid = $book->id AND hidden = 0"; $chapters = $DB->get_records_select('book_chapters', $select, null, 'pagenum', 'id, pagenum, subchapter, title, hidden'); -/// check chapterid and read chapter data -if ($chapterid == '0') { // go to first chapter if no given - foreach($chapters as $ch) { +// Check chapterid and read chapter data. +if ($chapterid == '0') { + // Go to first chapter if no given. + foreach ($chapters as $ch) { if ($allowedit) { $chapterid = $ch->id; break; @@ -44,55 +60,51 @@ if ($chapterid == '0') { // go to first chapter if no given } } - if (!$chapter = $DB->get_record('book_chapters', array('id' => $chapterid))) { print_error('Error reading book chapters.'); } -//check all variables +// Check all variables. unset($id); unset($chapterid); -/// chapter is hidden for students +// Chapter is hidden for students. if (!$allowedit && $chapter->hidden) { - print_error('Error reading book chapters.'); + print_error('Error reading book chapters.'); } -/// chapter not part of this book! +// Chapter not part of this book! if ($chapter->bookid != $book->id) { - print_error('Chapter not part of this book!'); + print_error('Chapter not part of this book!'); } -// ========================================================================= -// security checks END -// ========================================================================= - +/* ========================================================================= + * security checks END + * ========================================================================= + */ add_to_log($course->id, 'book', 'view', 'view.php?id='.$cm->id.'&chapterid='.$chapter->id, $book->id, $cm->id); - -///read standard strings +// Read standard strings. $strbooks = get_string('modulenameplural', 'book'); $strbook = get_string('modulename', 'book'); -$strTOC = get_string('TOC', 'book'); -/// prepare header +// Prepare header. if ($course->category) { $navigation = ''.$course->shortname.' ->'; } else { $navigation = ''; } -$buttons = $allowedit ? ''. - '
        '.update_module_button($cm->id, $course->id, $strbook).' '.book_edit_button($cm->id, $course->id, $chapter->id).'
        ' - : ' '; +$buttons = $allowedit ? ''. + '
        '. + update_module_button($cm->id, $course->id, $strbook).' '.book_edit_button($cm->id, $course->id, $chapter->id).'
        ' : ' '; - -/// prepare chapter navigation icons +// Prepare chapter navigation icons. $previd = null; $nextid = null; $found = 0; foreach ($chapters as $ch) { if ($found) { - $nextid= $ch->id; + $nextid = $ch->id; break; } if ($ch->id == $chapter->id) { @@ -109,36 +121,51 @@ $chnavigation = ''; echo "previd=$previd nextid=$nextid
        "; if ($previd) { - $chnavigation .= ''.get_string('navprev', 'book').''; + $chnavigation .= ''.get_string('navprev', 'book').''; } else { $chnavigation .= ''; } if ($nextid) { - $chnavigation .= ''.get_string('navnext', 'book').''; + $chnavigation .= ''.get_string('navnext', 'book').''; } else { $sec = ''; if ($section = $DB->get_record('course_sections', array( 'id' => $cm->section))) { $sec = $section->section; } - $chnavigation .= ''.get_string('navexit', 'book').''; + $chnavigation .= ''.get_string('navexit', 'book').
+        ''; } echo "chnavigation=$chnavigation
        "; -/// prepare print icons +// Prepare print icons. if ($book->disableprinting) { $printbook = ''; $printchapter = ''; } else { - $printbook = ''.get_string('printbook', 'book').''; - $printchapter = ''.get_string('printchapter', 'book').''; + $printbook = ''.get_string('printbook', 'book').''; + $printchapter = ''.
+        get_string('printchapter', 'book').''; } -// ===================================================== -// Book display HTML code -// ===================================================== +/* ===================================================== + * Book display HTML code + * ===================================================== + */ echo "OK"; ?> @@ -159,44 +186,43 @@ echo "OK";
        - box_start('generalbox'); - echo $toc; - echo $OUTPUT->box_end(); - if ($allowedit && $edit) { - echo '
        '; - helpbutton('faq', get_string('faq','book'), 'book', true, true); - echo '
        '; - } - ?> +box_start('generalbox'); +echo $toc; +echo $OUTPUT->box_end(); +if ($allowedit && $edit) { + echo '
        '; + helpbutton('faq', get_string('faq', 'book'), 'book', true, true); + echo '
        '; +} +?>
        - box_start('generalbox'); - $content = ''; - if (!$book->customtitles) { - if ($currsubtitle == ' ') { - $content .= '

        '.$currtitle.'

        '; - } else { - $content .= '

        '.$currtitle.'
        '.$currsubtitle.'

        '; - } - } - $content .= $chapter->content; - - $nocleanoption = new object(); - $nocleanoption->noclean = true; - echo '
        '; - echo format_text($content, FORMAT_HTML, $nocleanoption, $course->id); - echo '
        '; - echo $OUTPUT->box_end(); - /// lower navigation - echo '

        '.$chnavigation.'

        '; - ?> +box_start('generalbox'); +$content = ''; +if (!$book->customtitles) { + if ($currsubtitle == ' ') { + $content .= '

        '.$currtitle.'

        '; + } else { + $content .= '

        '.$currtitle.'
        '.$currsubtitle.'

        '; + } +} + +$content .= $chapter->content; + +$nocleanoption = new object(); +$nocleanoption->noclean = true; +echo '
        '; +echo format_text($content, FORMAT_HTML, $nocleanoption, $course->id); +echo '
        '; +echo $OUTPUT->box_end(); +// Lower navigation. +echo '

        '.$chnavigation.'

        '; +?>
        footer($course); - -?>