File manager - Edit - /home/theblueo/tv/fb4e3b/wp-pro-quiz.tar
Back
lib/model/WpProQuiz_Model_Statistic.php 0000666 00000005750 15214236625 0014233 0 ustar 00 <?php class WpProQuiz_Model_Statistic extends WpProQuiz_Model_Model { protected $_statisticRefId = 0; protected $_questionId = 0; protected $_correctCount = 0; protected $_incorrectCount = 0; protected $_hintCount = 0; protected $_points = 0; protected $_questionTime = 0; protected $_answerData = null; public function setStatisticRefId($_statisticRefId) { $this->_statisticRefId = (int)$_statisticRefId; return $this; } public function getStatisticRefId() { return $this->_statisticRefId; } public function setQuestionId($_questionId) { $this->_questionId = (int)$_questionId; return $this; } public function getQuestionId() { return $this->_questionId; } public function setCorrectCount($_correctCount) { $this->_correctCount = (int)$_correctCount; return $this; } public function getCorrectCount() { return $this->_correctCount; } public function setIncorrectCount($_incorrectCount) { $this->_incorrectCount = (int)$_incorrectCount; return $this; } public function getIncorrectCount() { return $this->_incorrectCount; } public function setHintCount($_hintCount) { $this->_hintCount = (int)$_hintCount; return $this; } public function getHintCount() { return $this->_hintCount; } public function setPoints($_points) { $this->_points = (int)$_points; return $this; } public function getPoints() { return $this->_points; } public function setQuestionTime($_questionTime) { $this->_questionTime = (int)$_questionTime; return $this; } public function getQuestionTime() { return $this->_questionTime; } public function setAnswerData($_answerData) { $this->_answerData = $_answerData; return $this; } public function getAnswerData() { return $this->_answerData; } public function get_object_as_array() { $object_vars = array( '_statisticRefId' => $this->getStatisticRefId(), '_questionId' => $this->getQuestionId(), '_correctCount' => $this->getCorrectCount(), '_incorrectCount' => $this->getIncorrectCount(), '_hintCount' => $this->getHintCount(), '_points' => $this->getPoints(), '_questionTime' => $this->getQuestionTime(), '_answerData' => $this->getAnswerData() ); return $object_vars; } public function set_array_to_object( $array_vars = array() ) { foreach( $array_vars as $key => $value ) { switch( $key ) { case '_statisticRefId': $this->setStatisticRefId( $value ); break; case '_questionId': $this->setQuestionId( $value ); break; case '_correctCount': $this->setCorrectCount( $value ); break; case '_incorrectCount': $this->setIncorrectCount( $value ); break; case '_hintCount': $this->setHintCount( $value ); break; case '_points': $this->setPoints( $value ); break; case '_questionTime': $this->setQuestionTime( $value ); break; case '_answerData': $this->setAnswerData( $value ); } } } } lib/model/WpProQuiz_Model_GlobalSettingsMapper.php 0000666 00000010557 15214236625 0016353 0 ustar 00 <?php class WpProQuiz_Model_GlobalSettingsMapper extends WpProQuiz_Model_Mapper { public function fetchAll() { $s = new WpProQuiz_Model_GlobalSettings(); // Why are we doing this? When the option does not exists it causes WP to execute the SQL to the wp_options table for // each access attempt. By settings a default value the option will be auto loaded when WP initialized. Then when // we call get_option we are just accessing the WP global settings array instead of causing a SQL each time. // Saves a few time slices. $wpProQuiz_addRawShortcode = get_option('wpProQuiz_addRawShortcode'); if ($wpProQuiz_addRawShortcode === false) update_option('wpProQuiz_addRawShortcode', ''); $wpProQuiz_jsLoadInHead = get_option('wpProQuiz_jsLoadInHead'); if ($wpProQuiz_jsLoadInHead === false) update_option('wpProQuiz_jsLoadInHead', ''); $wpProQuiz_touchLibraryDeactivate = get_option('wpProQuiz_touchLibraryDeactivate'); if ($wpProQuiz_touchLibraryDeactivate === false) update_option('wpProQuiz_touchLibraryDeactivate', ''); $wpProQuiz_corsActivated = get_option('wpProQuiz_corsActivated'); if ($wpProQuiz_corsActivated === false) update_option('wpProQuiz_corsActivated', ''); $s->setAddRawShortcode( $wpProQuiz_addRawShortcode ) ->setJsLoadInHead( $wpProQuiz_jsLoadInHead ) ->setTouchLibraryDeactivate( $wpProQuiz_touchLibraryDeactivate ) ->setCorsActivated( $wpProQuiz_corsActivated ); return $s; } public function save(WpProQuiz_Model_GlobalSettings $settings) { if(add_option('wpProQuiz_addRawShortcode', $settings->isAddRawShortcode()) === false) { update_option('wpProQuiz_addRawShortcode', $settings->isAddRawShortcode()); } if(add_option('wpProQuiz_jsLoadInHead', $settings->isJsLoadInHead()) === false) { update_option('wpProQuiz_jsLoadInHead', $settings->isJsLoadInHead()); } if(add_option('wpProQuiz_touchLibraryDeactivate', $settings->isTouchLibraryDeactivate()) === false) { update_option('wpProQuiz_touchLibraryDeactivate', $settings->isTouchLibraryDeactivate()); } if(add_option('wpProQuiz_corsActivated', $settings->isCorsActivated()) === false) { update_option('wpProQuiz_corsActivated', $settings->isCorsActivated()); } } public function delete() { delete_option('wpProQuiz_addRawShortcode'); delete_option('wpProQuiz_jsLoadInHead'); delete_option('wpProQuiz_touchLibraryDeactivate'); delete_option('wpProQuiz_corsActivated'); } public function getEmailSettings() { $e = get_option('wpProQuiz_emailSettings', null); if($e === null) { $e['to'] = ''; $e['from'] = ''; $e['subject'] = sprintf( esc_html_x('LearnDash %1$s: One user completed a %2$s', 'LearnDash Quiz: One user completed a quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); $e['html'] = false; $e['message'] = sprintf( esc_html_x('LearnDash %s The user "$username" has completed "$quizname" the %s. Points: $points Result: $result ', 'placeholders: Quiz, quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' )); } return $e; } public function saveEmailSettiongs($data) { if(isset($data['html']) && $data['html']) $data['html'] = true; else $data['html'] = false; if(add_option('wpProQuiz_emailSettings', $data, '', 'no') === false) { update_option('wpProQuiz_emailSettings', $data); } } public function getUserEmailSettings() { $e = get_option('wpProQuiz_userEmailSettings', null); if($e === null) { $e['from'] = ''; $e['subject'] = sprintf( esc_html_x('LearnDash %1$s: One user completed a %2$s', 'LearnDash Quiz: One user completed a quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); $e['html'] = false; $e['message'] = sprintf( esc_html_x('LearnDash %s You have completed the %s "$quizname". Points: $points Result: $result ', 'placeholders: Quiz, quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); } return $e; } public function saveUserEmailSettiongs($data) { if(isset($data['html']) && $data['html']) $data['html'] = true; else $data['html'] = false; if(add_option('wpProQuiz_userEmailSettings', $data, '', 'no') === false) { update_option('wpProQuiz_userEmailSettings', $data); } } } lib/model/WpProQuiz_Model_QuestionMapper.php 0000666 00000030264 15214236625 0015236 0 ustar 00 <?php class WpProQuiz_Model_QuestionMapper extends WpProQuiz_Model_Mapper { private $_table; public function __construct() { parent::__construct(); //$this->_table = $this->_prefix."question"; $this->_table = $this->_tableQuestion; } public function delete($id) { $this->_wpdb->delete($this->_table, array('id' => $id), '%d'); } public function deleteByQuizId($id) { $this->_wpdb->delete($this->_table, array('quiz_id' => $id), '%d'); } public function getSort($questionId) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT sort FROM {$this->_tableQuestion} WHERE id = %d", $questionId)); } public function updateSort($id, $sort) { $this->_wpdb->update( $this->_table, array( 'sort' => $sort), array('id' => $id), array('%d'), array('%d') ); if ( true === is_data_upgrade_quiz_questions_updated() ) { $question_post_id = learndash_get_question_post_by_pro_id( $id ); if ( ! empty( $question_post_id ) ) { $update_post = array( 'ID' => $question_post_id, 'menu_order' => absint( $sort ), ); wp_update_post( $update_post ); learndash_set_question_quizzes_dirty( $question_post_id ); } } } public function setOnlineOff($questionId) { return $this->_wpdb->update($this->_tableQuestion, array('online' => 0), array('id' => $questionId), null, array('%d')); } public function getQuizId($questionId) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT quiz_id FROM {$this->_tableQuestion} WHERE id = %d", $questionId)); } public function getMaxSort($quizId) { return $this->_wpdb->get_var($this->_wpdb->prepare( "SELECT MAX(sort) AS max_sort FROM {$this->_tableQuestion} WHERE quiz_id = %d AND online = 1", $quizId)); } public function save(WpProQuiz_Model_Question $question, $auto = false) { $sort = null; if($auto && $question->getId()) { $statisticMapper = new WpProQuiz_Model_StatisticMapper(); if($statisticMapper->isStatisticByQuestionId($question->getId())) { $this->setOnlineOff($question->getId()); $question->setQuizId($this->getQuizId($question->getId())); $question->setId(0); $sort = $question->getSort(); } } /** * Convert emoji to HTML entities to allow saving in DB. * * @since 2.6.0. */ $question_title = $question->getTitle(); $question_title = wp_encode_emoji( $question_title ); $question_question = $question->getQuestion(); $question_question = wp_encode_emoji( $question_question ); if($question->getId() != 0) { $this->_wpdb->update( $this->_table, array( 'quiz_id' => $question->getQuizId(), 'title' => $question_title, 'points' => $question->getPoints(), 'question' => $question_question, 'correct_msg' => $question->getCorrectMsg(), 'incorrect_msg' => $question->getIncorrectMsg(), 'correct_same_text' => (int)$question->isCorrectSameText(), 'tip_enabled' => (int)$question->isTipEnabled(), 'tip_msg' => $question->getTipMsg(), 'answer_type' => $question->getAnswerType(), 'show_points_in_box' => (int)$question->isShowPointsInBox(), 'answer_points_activated' => (int)$question->isAnswerPointsActivated(), 'answer_data' => $question->getAnswerData(true), 'category_id' => $question->getCategoryId(), 'answer_points_diff_modus_activated' => (int)$question->isAnswerPointsDiffModusActivated(), 'disable_correct' => (int)$question->isDisableCorrect(), 'matrix_sort_answer_criteria_width' => $question->getMatrixSortAnswerCriteriaWidth() ), array('id' => $question->getId()), array('%s', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%d', '%d'), array('%d')); } else { $this->_wpdb->insert($this->_table, array( 'quiz_id' => $question->getQuizId(), 'online' => 1, 'sort' => $sort !== null ? $sort : ($this->getMaxSort($question->getQuizId()) + 1), 'title' => $question_title, 'points' => $question->getPoints(), 'question' => $question_question, 'correct_msg' => $question->getCorrectMsg(), 'incorrect_msg' => $question->getIncorrectMsg(), 'correct_same_text' => (int)$question->isCorrectSameText(), 'tip_enabled' => (int)$question->isTipEnabled(), 'tip_msg' => $question->getTipMsg(), 'answer_type' => $question->getAnswerType(), 'show_points_in_box' => (int)$question->isShowPointsInBox(), 'answer_points_activated' => (int)$question->isAnswerPointsActivated(), 'answer_data' => $question->getAnswerData(true), 'category_id' => $question->getCategoryId(), 'answer_points_diff_modus_activated' => (int)$question->isAnswerPointsDiffModusActivated(), 'disable_correct' => (int)$question->isDisableCorrect(), 'matrix_sort_answer_criteria_width' => $question->getMatrixSortAnswerCriteriaWidth() ), array('%d', '%d', '%d', '%s', '%d', '%s', '%s', '%s', '%d', '%d', '%s', '%s', '%d', '%d', '%s', '%d', '%d', '%d', '%d') ); $question->setId($this->_wpdb->insert_id); } if ( ( true === is_data_upgrade_quiz_questions_updated() ) && ( LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Builder', 'enabled' ) !== 'yes' ) ) { $question_post_id = learndash_get_question_post_by_pro_id( $question->getId() ); if ( empty( $question_post_id ) ) { // We load fresh from DB. Don't use the $question object as it is not up to date. $question_pro = $this->fetchById( $question->getId() ); if ( ( $question_pro ) && ( is_a( $question_pro, 'WpProQuiz_Model_Question' ) ) ) { $question_insert_post = array(); $question_insert_post['post_type'] = learndash_get_post_type_slug( 'question' ); $question_insert_post['post_status'] = 'publish'; $question_insert_post['post_title'] = $question_pro->getTitle(); $question_insert_post['post_content'] = $question_pro->getQuestion(); $question_insert_post['menu_order'] = absint( $question_pro->getSort() ); $question_insert_post = wp_slash( $question_insert_post ); $question_insert_post_id = wp_insert_post( $question_insert_post ); if ( false !== $question_insert_post_id ) { $quiz_pro_id = $question_pro->getQuizId(); $quiz_pro_id = absint( $quiz_pro_id ); $quiz_post_id = learndash_get_quiz_id_by_pro_quiz_id( $quiz_pro_id ); learndash_update_setting( $question_insert_post_id, 'quiz', $quiz_post_id ); learndash_proquiz_sync_question_fields( $question_insert_post_id, $question_pro ); learndash_set_question_quizzes_dirty( $question_insert_post_id ); } } } } return $question; } public function fetch($id) { $row = $this->_wpdb->get_row( $this->_wpdb->prepare( "SELECT * FROM ". $this->_table. " WHERE id = %d AND online = 1", $id), ARRAY_A ); $model = new WpProQuiz_Model_Question($row); return $model; } public function fetchById($id, $online = 1 ) { $ids = array_map('intval', (array)$id); $a = array(); if(empty($ids)) return null; $sql_str = "SELECT * FROM ". $this->_table. " WHERE id IN(". implode(', ', $ids) .") "; if ( ( $online === 1 ) || ( $online === 1 ) ) { $sql_str .= " AND online = ". $online; } $results = $this->_wpdb->get_results( $sql_str, ARRAY_A ); foreach ($results as $row) { $a[] = new WpProQuiz_Model_Question($row); } return is_array($id) ? $a : (isset($a[0]) ? $a[0] : null); } public function fetchAll( $quizId = 0, $rand = false, $max = 0 ) { $quiz_post_id = 0; if ( is_a( $quizId, 'WpProQuiz_Model_Quiz' ) ) { $quiz = $quizId; $quizId = $quiz->getId(); if ( empty( $quiz_post_id ) ) { $quiz_post_id = $quiz->getPostId(); } } else { $quiz_post_id = learndash_get_question_post_by_pro_id( $quizId ); if ( empty( $quiz_post_id ) ) { if ( ( isset( $_GET['post'] ) ) && ( ! empty( $_GET['post'] ) ) ) { $quiz_post_id = learndash_get_quiz_id( absint( $_GET['post'] ) ); } } } if ( ( ! empty( $quiz_post_id ) ) && ( LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Builder', 'enabled' ) === 'yes' ) && ( true === is_data_upgrade_quiz_questions_updated() ) ) { $ld_quiz_questions_object = LDLMS_Factory_Post::quiz_questions( intval( $quiz_post_id ) ); if ( $ld_quiz_questions_object ) { $pro_questions = $ld_quiz_questions_object->get_questions( 'pro_objects' ); $pro_questions = apply_filters( 'learndash_fetch_quiz_questions', $pro_questions, $quizId, $rand, $max ); if ( ! empty( $pro_questions ) ) { if ( $rand ) { //$pro_questions = array_rand( $pro_questions, intval( $max ) ); shuffle( $pro_questions ); $max = absint( $max ); if ( $max > 0 ) { $pro_questions = array_slice( $pro_questions, 0, $max, true ); } } } if ( ! empty( $pro_questions ) ) { $category_mapper = new WpProQuiz_Model_CategoryMapper(); foreach( $pro_questions as $pro_question ) { $q_catId = $pro_question->getCategoryId(); $q_catId = absint( $q_catId ); if ( ! empty( $q_catId ) ) { $q_cat = $category_mapper->fetchById( $q_catId ); if ( ( $q_cat ) && ( is_a( $q_cat, 'WpProQuiz_Model_Category' ) ) ) { $_catName = $q_cat->getCategoryName(); if ( ! empty( $_catName ) ) { $pro_question->setCategoryName( $_catName ); } } } } } return $pro_questions; } } else { if ( $rand ) { $orderBy = 'ORDER BY RAND()'; } else { $orderBy = 'ORDER BY sort ASC'; } $limit = ''; if($max > 0) { $limit = 'LIMIT 0, '.((int)$max); } $a = array(); $results = $this->_wpdb->get_results( $this->_wpdb->prepare( 'SELECT q.*, c.category_name FROM '. $this->_table.' AS q LEFT JOIN '.$this->_tableCategory.' AS c ON c.category_id = q.category_id WHERE quiz_id = %d AND q.online = 1 '.$orderBy.' '.$limit , $quizId), ARRAY_A); foreach($results as $row) { $model = new WpProQuiz_Model_Question($row); $a[] = $model; } } return $a; } public function fetchAllList($quizId, $list) { $quiz_post_id = 0; if ( is_a( $quizId, 'WpProQuiz_Model_Quiz' ) ) { $quiz = $quizId; $quizId = $quiz->getId(); $quiz_post_id = $quiz->getPostId(); } if ( ( ! empty( $quiz_post_id ) ) && ( LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Builder', 'enabled' ) === 'yes' ) && ( true === is_data_upgrade_quiz_questions_updated() ) ) { $ld_quiz_questions_object = LDLMS_Factory_Post::quiz_questions( intval( $quiz_post_id ) ); if ( $ld_quiz_questions_object ) { $questions = $ld_quiz_questions_object->get_questions(); if ( ! empty( $questions ) ) { $sql_str = "SELECT " . implode(', ', (array) $list ) . " FROM " . $this->_tableQuestion . " WHERE id IN (". implode(',', $questions) . ") AND online = 1"; $results = $this->_wpdb->get_results( $sql_str, ARRAY_A ); return $results; } } } else { $results = $this->_wpdb->get_results( $this->_wpdb->prepare( 'SELECT '.implode(', ', (array)$list).' FROM '. $this->_tableQuestion.' WHERE quiz_id = %d AND online = 1' , $quizId), ARRAY_A); return $results; } } public function count($quizId) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT COUNT(*) FROM {$this->_table} WHERE quiz_id = %d AND online = 1", $quizId)); } public function exists($id) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT COUNT(*) FROM {$this->_table} WHERE id = %d AND online = 1", $id)); } public function existsAndWritable($id) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT COUNT(*) FROM {$this->_table} WHERE id = %d AND online = 1", $id)); } public function fetchCategoryPoints($quizId) { $results = $this->_wpdb->get_results( $this->_wpdb->prepare( 'SELECT SUM( points ) AS sum_points , category_id FROM '.$this->_tableQuestion.' WHERE quiz_id = %d AND online = 1 GROUP BY category_id', $quizId)); $a = array(); foreach($results as $result) { $a[$result['category_id']] = $result['sum_points']; } return $a; } } lib/model/WpProQuiz_Model_StatisticFormOverview.php 0000666 00000003277 15214236625 0016610 0 ustar 00 <?php class WpProQuiz_Model_StatisticFormOverview extends WpProQuiz_Model_Model { protected $_userId = 0; protected $_userName = ''; protected $_statisticRefId = 0; protected $_quizId = 0; protected $_createTime = 0; protected $_correctCount = 0; protected $_incorrectCount = 0; protected $_points = 0; public function setUserId($_userId) { $this->_userId = (int)$_userId; return $this; } public function getUserId() { return $this->_userId; } public function setUserName($_userName) { $this->_userName = (string)$_userName; return $this; } public function getUserName() { return $this->_userName; } public function setStatisticRefId($_statisticRefId) { $this->_statisticRefId = (int)$_statisticRefId; return $this; } public function getStatisticRefId() { return $this->_statisticRefId; } public function setQuizId($_quizId) { $this->_quizId = (int)$_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setCreateTime($_createTime) { $this->_createTime = (int)$_createTime; return $this; } public function getCreateTime() { return $this->_createTime; } public function setCorrectCount($_correctCount) { $this->_correctCount = (int)$_correctCount; return $this; } public function getCorrectCount() { return $this->_correctCount; } public function setIncorrectCount($_incorrectCount) { $this->_incorrectCount = (int)$_incorrectCount; return $this; } public function getIncorrectCount() { return $this->_incorrectCount; } public function setPoints($_points) { $this->_points = (int)$_points; return $this; } public function getPoints() { return $this->_points; } } lib/model/WpProQuiz_Model_QuizMapper.php 0000666 00000021427 15214236625 0014360 0 ustar 00 <?php class WpProQuiz_Model_QuizMapper extends WpProQuiz_Model_Mapper { protected $_table; function __construct() { parent::__construct(); //$this->_table = $this->_prefix."master"; $this->_table = $this->_tableMaster; } public function delete($id) { $this->_wpdb->delete($this->_table, array( 'id' => $id), array('%d')); } public function exists($id) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT COUNT(*) FROM {$this->_table} WHERE id = %d", $id)); } public function fetch($id) { $queried_object = get_queried_object(); $sql_str = $this->_wpdb->prepare("SELECT * FROM {$this->_table} WHERE id = %d", $id ); $results = $this->_wpdb->get_row( $sql_str, ARRAY_A ); if($results['result_grade_enabled']) $results['result_text'] = unserialize($results['result_text']); return new WpProQuiz_Model_Quiz($results); } public function fetchAll() { $r = array(); $results = $this->_wpdb->get_results("SELECT * FROM {$this->_table} ORDER BY id ASC", ARRAY_A); foreach ($results as $row) { if($row['result_grade_enabled']) $row['result_text'] = unserialize($row['result_text']); $r[] = new WpProQuiz_Model_Quiz($row); } return $r; } public function save(WpProQuiz_Model_Quiz $data) { if($data->isResultGradeEnabled()) { $resultText = serialize($data->getResultText()); } else { $resultText = $data->getResultText(); } $name = $data->getName(); if(empty($name)) $name = "no title"; $text = $data->getText(); if(empty($text)) $text = "AAZZAAZZ"; $set = array( 'name' => $name, 'text' => $text, 'result_text' => $resultText, 'title_hidden' => (int)$data->isTitleHidden(), 'btn_restart_quiz_hidden' => (int)$data->isBtnRestartQuizHidden(), 'btn_view_question_hidden' => (int)$data->isBtnViewQuestionHidden(), 'question_random' => (int)$data->isQuestionRandom(), 'answer_random' => (int)$data->isAnswerRandom(), 'time_limit' => (int)$data->getTimeLimit(), 'statistics_on' => (int)$data->isStatisticsOn(), 'statistics_ip_lock' => (int)$data->getStatisticsIpLock(), 'result_grade_enabled' => (int)$data->isResultGradeEnabled(), 'show_points' => (int)$data->isShowPoints(), 'quiz_run_once' => (int)$data->isQuizRunOnce(), 'quiz_run_once_type' => $data->getQuizRunOnceType(), 'quiz_run_once_cookie' => (int)$data->isQuizRunOnceCookie(), 'quiz_run_once_time' => (int)$data->getQuizRunOnceTime(), 'numbered_answer' => (int)$data->isNumberedAnswer(), 'hide_answer_message_box' => (int)$data->isHideAnswerMessageBox(), 'disabled_answer_mark' => (int)$data->isDisabledAnswerMark(), 'show_max_question' => (int)$data->isShowMaxQuestion(), 'show_max_question_value' => (int)$data->getShowMaxQuestionValue(), 'show_max_question_percent' => (int)$data->isShowMaxQuestionPercent(), 'toplist_activated' => (int)$data->isToplistActivated(), 'toplist_data' => $data->getToplistData(), 'show_average_result' => (int)$data->isShowAverageResult(), 'prerequisite' => (int)$data->isPrerequisite(), 'quiz_modus' => (int)$data->getQuizModus(), 'show_review_question' => (int)$data->isShowReviewQuestion(), 'quiz_summary_hide' => (int)$data->isQuizSummaryHide(), 'skip_question_disabled' => (int)$data->isSkipQuestionDisabled(), 'email_notification' => $data->getEmailNotification(), 'user_email_notification' => (int)$data->isUserEmailNotification(), 'show_category_score' => (int)$data->isShowCategoryScore(), 'hide_result_correct_question' => (int)$data->isHideResultCorrectQuestion(), 'hide_result_quiz_time' => (int)$data->isHideResultQuizTime(), 'hide_result_points' => (int)$data->isHideResultPoints(), 'autostart' => (int)$data->isAutostart(), 'forcing_question_solve' => (int)$data->isForcingQuestionSolve(), 'hide_question_position_overview' => (int)$data->isHideQuestionPositionOverview(), 'hide_question_numbering' => (int)$data->isHideQuestionNumbering(), 'form_activated' => (int)$data->isFormActivated(), 'form_show_position' => $data->getFormShowPosition(), 'start_only_registered_user' => (int)$data->isStartOnlyRegisteredUser(), 'questions_per_page' => $data->getQuestionsPerPage(), 'sort_categories' => (int)$data->isSortCategories(), 'show_category' => (int)$data->isShowCategory() ); /** * Convert emoji to HTML entities to allow saving in DB. * * @since 2.6.0. */ $set['name'] = wp_encode_emoji( $set['name'] ); if($data->getId() != 0) { $result = $this->_wpdb->update( $this->_table, $set, array( 'id' => $data->getId() ), array( '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d' ), array( '%d' ) ); } else { $result = $this->_wpdb->insert( $this->_table, $set, array( '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%s', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d', '%d' ) ); $data->setId($this->_wpdb->insert_id); } if($result === false) { return null; } $data->saveTimeLimitCookie(); $data->saveViewProfileStatistics(); return $data; } public function sumQuestionPoints($id) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT SUM(points) FROM {$this->_tableQuestion} WHERE quiz_id = %d AND online = 1", $id)); } public function sumQuestionPointsFromArray( $question_ids = array() ) { if ( ! empty( $question_ids ) ) { $sql_str = "SELECT SUM(points) FROM {$this->_tableQuestion} WHERE id IN (" . implode(',', $question_ids ) . ") AND online = 1"; return $this->_wpdb->get_var( $sql_str ); } else { return 0; } } public function countQuestion($id) { return $this->_wpdb->get_var($this->_wpdb->prepare("SELECT COUNT(*) FROM {$this->_tableQuestion} WHERE quiz_id = %d AND online = 1", $id)); } public function fetchAllAsArray( $list, $outIds = array() ) { $where = ' 1 '; if( !empty ($outIds ) ) { $where .= ' AND id NOT IN (' . implode( ', ', array_map( 'intval', (array) $outIds ) ) . ') '; } $sql_str = "SELECT " . implode( ', ', (array) $list ) . " FROM {$this->_tableMaster} WHERE $where ORDER BY name"; $quiz_list = $this->_wpdb->get_results( $sql_str, ARRAY_A ); if ( ! empty( $quiz_list ) ) { $quiz_pro_ids = wp_list_pluck( $quiz_list, 'id' ); $sql_str = "SELECT postmeta.meta_value as quiz_pro_id FROM {$this->_wpdb->posts} AS posts INNER JOIN {$this->_wpdb->postmeta} as postmeta ON posts.ID = postmeta.post_id WHERE posts.post_type='". learndash_get_post_type_slug( 'quiz' ) . "' AND posts.post_status = 'publish' AND postmeta.meta_key='quiz_pro_id' AND postmeta.meta_value IN ( ". implode( ',', $quiz_pro_ids ) . " )"; $quiz_pro_ids = $this->_wpdb->get_col( $sql_str ); if ( ! empty( $quiz_pro_ids ) ) { $quiz_pro_ids = array_map( 'intval', $quiz_pro_ids ); $quiz_pro_ids = array_unique( $quiz_pro_ids ); foreach( $quiz_list as $quiz_idx => $quiz_item ) { if ( ! in_array( $quiz_item['id'], $quiz_pro_ids ) ) { unset( $quiz_list[ $quiz_idx ] ); } } } } return ( array ) $quiz_list; } public function fetchCol($ids, $col) { $ids = implode(', ', array_map('intval', (array)$ids)); return $this->_wpdb->get_col("SELECT {$col} FROM {$this->_tableMaster} WHERE id IN({$ids})"); } public function activateStatitic($quizIds, $lockIpTime) { $quizIds = implode(', ', array_map('intval', (array)$quizIds)); return $this->_wpdb->query($this->_wpdb->prepare( "UPDATE {$this->_tableMaster} SET `statistics_on` = 1, `statistics_ip_lock` = %d WHERE `statistics_on` = 0 AND id IN(".$quizIds.")" , $lockIpTime)); } public function deleteAll($quizId) { return $this->_wpdb->query( $this->_wpdb->prepare( "DELETE m, q, l, p, t, f, sr, s FROM {$this->_tableMaster} AS m LEFT JOIN {$this->_tableQuestion} AS q ON(q.quiz_id = m.id) LEFT JOIN {$this->_tableLock} AS l ON(l.quiz_id = m.id) LEFT JOIN {$this->_tablePrerequisite} AS p ON(p.prerequisite_quiz_id = m.id) LEFT JOIN {$this->_tableToplist} AS t ON(t.quiz_id = m.id) LEFT JOIN {$this->_tableForm} AS f ON(f.quiz_id = m.id) LEFT JOIN {$this->_tableStatisticRef} AS sr ON(sr.quiz_id = m.id) LEFT JOIN {$this->_tableStatistic} AS s ON(s.statistic_ref_id = sr.statistic_ref_id) WHERE m.id = %d" , $quizId) ); } } lib/model/WpProQuiz_Model_Mapper.php 0000666 00000002773 15214236625 0013512 0 ustar 00 <?php class WpProQuiz_Model_Mapper { /** * Wordpress Datenbank Object * @var wpdb */ protected $_wpdb; /** * @var string */ protected $_prefix; /** * @var string */ protected $_tableQuestion; protected $_tableMaster; protected $_tableLock; protected $_tableStatistic; protected $_tableToplist; protected $_tablePrerequisite; protected $_tableCategory; protected $_tableStatisticRef; protected $_tableForm; protected $_tableTemplate; // Our reference between the ProQuiz and the Quiz (post_type) protected $_quiz_post_id; function __construct() { global $wpdb; $this->_wpdb = $wpdb; //$this->_prefix = $wpdb->prefix . 'wp_pro_quiz_'; $this->_prefix = LDLMS_DB::get_table_prefix( 'wpproquiz' ); $this->_tableQuestion = LDLMS_DB::get_table_name( 'quiz_question' ); $this->_tableMaster = LDLMS_DB::get_table_name( 'quiz_master' ); $this->_tableLock = LDLMS_DB::get_table_name( 'quiz_lock' ); $this->_tableStatistic = LDLMS_DB::get_table_name( 'quiz_statistic' ); $this->_tableToplist = LDLMS_DB::get_table_name( 'quiz_toplist' ); $this->_tablePrerequisite = LDLMS_DB::get_table_name( 'quiz_prerequisite' ); $this->_tableCategory = LDLMS_DB::get_table_name( 'quiz_category' ); $this->_tableStatisticRef = LDLMS_DB::get_table_name( 'quiz_statistic_ref' ); $this->_tableForm = LDLMS_DB::get_table_name( 'quiz_form' ); $this->_tableTemplate = LDLMS_DB::get_table_name( 'quiz_template' ); } public function getInsertId() { return $this->_wpdb->insert_id; } } lib/model/WpProQuiz_Model_StatisticRefMapper.php 0000666 00000037317 15214236625 0016041 0 ustar 00 <?php class WpProQuiz_Model_StatisticRefMapper extends WpProQuiz_Model_Mapper { public function fetchAll($quizId, $userId, $testId = 0) { $r = array(); if(!$testId || $userId > 0) $where = ' AND is_old = 0 '; else $where = ' AND statistic_ref_id = '.(int)$testId; $results = $this->_wpdb->get_results( $this->_wpdb->prepare( "SELECT * FROM {$this->_tableStatisticRef} WHERE quiz_id = %d AND user_id = %d {$where} ORDER BY create_time ASC" , $quizId, $userId) , ARRAY_A); foreach ($results as $row) { $row['form_data'] = null; $r[] = new WpProQuiz_Model_StatisticRefModel($row); } return $r; } public function fetchAllByRef($statisticRefId) { if ( ! empty( $statisticRefId ) ) { $where = 'sf.statistic_ref_id = %d'; $results = $this->_wpdb->get_results( $this->_wpdb->prepare( "SELECT sf.* FROM {$this->_tableStatisticRef} AS sf WHERE {$where}" , $statisticRefId) , ARRAY_A); foreach ($results as $row) { $row['form_data'] = $row['form_data'] === null ? null : @json_decode($row['form_data'], true); return new WpProQuiz_Model_StatisticRefModel($row); } } } public function fetchByRefId($refIdUserId, $quizId, $avg = FALSE) { $where = $avg ? 'sf.user_id = %d' : 'sf.statistic_ref_id = %d'; $results = $this->_wpdb->get_results( $this->_wpdb->prepare( "SELECT sf.*, MIN(sf.create_time) AS min_create_time, MAX(sf.create_time) AS max_create_time FROM {$this->_tableStatisticRef} AS sf WHERE {$where} AND sf.quiz_id = %d" , $refIdUserId, $quizId) , ARRAY_A); foreach ($results as $row) { $row['form_data'] = $row['form_data'] === null ? null : @json_decode($row['form_data'], true); return new WpProQuiz_Model_StatisticRefModel($row); } } public function fetchAvg($quizId, $userId) { $r = array(); $results = $this->_wpdb->get_results( $this->_wpdb->prepare(' SELECT question_id, SUM(correct_count) AS correct_count, SUM(incorrect_count) AS incorrect_count, SUM(hint_count) AS hint_count, SUM(points) AS points, (SUM(question_time) / COUNT(DISTINCT sf.statistic_ref_id)) AS question_time FROM '.$this->_tableStatistic.' AS s, '.$this->_tableStatisticRef.' AS sf WHERE s.statistic_ref_id = sf.statistic_ref_id AND sf.quiz_id = %d AND sf.user_id = %d GROUP BY s.question_id ', $quizId, $userId) , ARRAY_A); foreach ($results as $row) { $r[] = new WpProQuiz_Model_Statistic($row); } return $r; } public function fetchOverview($quizId, $onlyCompleded, $start, $limit) { $sql = 'SELECT u.`user_login`, u.`display_name`, u.ID AS user_id, SUM(s.`correct_count`) as correct_count, SUM(s.`incorrect_count`) as incorrect_count, SUM(s.`hint_count`) as hint_count, SUM(s.`points`) as points, (SUM(s.question_time)) as question_time FROM `'.$this->_wpdb->users.'` AS u '.($onlyCompleded ? 'INNER' : 'LEFT').' JOIN `'.$this->_tableStatisticRef.'` AS sf ON (sf.user_id = u.ID AND sf.quiz_id = %d) LEFT JOIN `'.$this->_tableStatistic.'` AS s ON ( s.statistic_ref_id = sf.statistic_ref_id ) GROUP BY u.ID ORDER BY u.`user_login` LIMIT %d , %d'; $a = array(); $results = $this->_wpdb->get_results( $this->_wpdb->prepare($sql, $quizId, $start, $limit), ARRAY_A); foreach($results as $row) { $row['user_name'] = $row['user_login'] . ' ('. $row['display_name'] .')'; $a[] = new WpProQuiz_Model_StatisticOverview($row); } return $a; } public function countOverview($quizId, $onlyCompleded) { if($onlyCompleded) { return $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(user_id) FROM {$this->_tableStatisticRef} WHERE quiz_id = %d", $quizId ) ); } else { return $this->_wpdb->get_var( "SELECT COUNT(ID) FROM {$this->_wpdb->users}" ); } } public function fetchByQuiz($quizId) { $sql = 'SELECT (SUM(`correct_count`) + SUM(`incorrect_count`)) as count, SUM(`points`) as points FROM '.$this->_tableStatisticRef.' AS sf, '.$this->_tableStatistic.' AS s WHERE sf.quiz_id = %d AND s.statistic_ref_id = sf.statistic_ref_id'; return $this->_wpdb->get_row( $this->_wpdb->prepare($sql, $quizId), ARRAY_A); } /** * * @param WpProQuiz_Model_StatisticRefModel $statisticRefModel * @param WpProQuiz_Model_Statistic $statisticModel */ public function statisticSave($statisticRefModel, $statisticModel) { $values = array(); $refId = null; $isOld = false; // if(!$statisticRefModel->getUserId()) { // $isOld = true; // $refId = $this->_wpdb->get_var( // $this->_wpdb->prepare(' // SELECT statistic_ref_id // FROM '.$this->_tableStatisticRef.' // WHERE quiz_id = %d AND user_id = %d // ', $statisticRefModel->getQuizId(), $statisticRefModel->getUserId()) // ); // } if($refId === null) { $refData = array( 'quiz_id' => $statisticRefModel->getQuizId(), 'user_id' => $statisticRefModel->getUserId(), 'create_time' => $statisticRefModel->getCreateTime(), 'is_old' => (int)$isOld ); $refFormat = array('%d', '%d', '%d', '%d'); if($statisticRefModel->getFormData() !== null && is_array($statisticRefModel->getFormData())) { $refData['form_data'] = @json_encode($statisticRefModel->getFormData()); $refFormat[] = '%s'; } $this->_wpdb->insert($this->_tableStatisticRef, $refData, $refFormat); $refId = $this->_wpdb->insert_id; } if ( !empty( $refId ) ) { foreach($statisticModel as $d) { $answerData = $d->getAnswerData() === null ? 'NULL' : $this->_wpdb->prepare('%s', json_encode($d->getAnswerData())); $values[] = '( '.implode(', ', array( 'statistic_ref_id' => $refId, 'question_id' => $d->getQuestionId(), 'correct_count' => $d->getCorrectCount(), 'incorrect_count' => $d->getIncorrectCount(), 'hint_count' => $d->getHintCount(), 'points' => $d->getPoints(), 'question_time' => $d->getQuestionTime(), 'answer_data' => $answerData )).' )'; } $this->_wpdb->query( 'INSERT INTO '.$this->_tableStatistic.' ( statistic_ref_id, question_id, correct_count, incorrect_count, hint_count, points, question_time, answer_data ) VALUES '.implode(', ', $values) ); } return $refId; } public function deleteUser($quizId, $userId) { return $this->_wpdb->query( $this->_wpdb->prepare(' DELETE s, sf FROM '.$this->_tableStatistic.' AS s INNER JOIN '.$this->_tableStatisticRef.' AS sf ON s.statistic_ref_id = sf.statistic_ref_id WHERE sf.quiz_id = %d AND sf.user_id = %d ', $quizId, $userId) ); } public function deleteAll($quizId) { return $this->_wpdb->query( $this->_wpdb->prepare(' DELETE s, sf FROM '.$this->_tableStatistic.' AS s INNER JOIN '.$this->_tableStatisticRef.' AS sf ON s.statistic_ref_id = sf.statistic_ref_id WHERE sf.quiz_id = %d ', $quizId) ); } public function deleteUserTest($quizId, $userId, $testId) { if(!$testId) return $this->deleteUser($quizId, $userId); return $this->_wpdb->query( $this->_wpdb->prepare(' DELETE s, sf FROM '.$this->_tableStatistic.' AS s INNER JOIN '.$this->_tableStatisticRef.' AS sf ON s.statistic_ref_id = sf.statistic_ref_id WHERE sf.quiz_id = %d AND sf.user_id = %d AND sf.statistic_ref_id = %d ', $quizId, $userId, $testId) ); } public function deleteQuestion($questionId) { return $this->_wpdb->delete($this->_tableStatistic, array('question_id' => $questionId), array('%d')); } public function fetchFormOverview($quizId, $page, $limit, $onlyUser = 0) { switch ($onlyUser) { case 1: $where = ' AND sf.user_id > 0 '; break; case 2: $where = ' AND sf.user_id = 0 '; break; default: $where = ''; } $result = $this->_wpdb->get_results( $this->_wpdb->prepare(' SELECT u.`user_login`, u.`display_name`, u.ID AS user_id, sf.*, SUM(s.correct_count) AS correct_count, SUM(s.incorrect_count) AS incorrect_count, SUM(s.points) AS points FROM '.$this->_tableStatisticRef.' AS sf INNER JOIN '.$this->_tableStatistic.' AS s ON(s.statistic_ref_id = sf.statistic_ref_id) LEFT JOIN '.$this->_wpdb->users.' AS u ON(u.ID = sf.user_id) WHERE quiz_id = %d AND sf.form_data IS NOT NULL '.$where.' GROUP BY sf.statistic_ref_id ORDER BY sf.create_time DESC LIMIT %d, %d ', $quizId, $page, $limit), ARRAY_A ); $r = array(); foreach($result as $row) { $row['user_name'] = $row['user_login'] . ' ('. $row['display_name'] .')'; $r[] = new WpProQuiz_Model_StatisticFormOverview($row); } return $r; } public function fetchHistory($quizId, $page, $limit, $users = -1, $startTime = 0, $endTime = 0) { $where = ''; $timeWhere = ''; switch ($users) { case -3: //only anonym $where = 'AND user_id = 0'; break; case -2: //only reg user $where = 'AND user_id > 0'; break; case -1: //all $where = ''; break; default: $where = 'AND user_id = '.(int)$users; break; } if($startTime) $timeWhere = 'AND create_time >= '.(int)$startTime; if($endTime) $timeWhere .= ' AND create_time <= '.(int)$endTime; $result = $this->_wpdb->get_results( $this->_wpdb->prepare(' SELECT u.`user_login`, u.`display_name`, u.ID AS user_id, sf.*, SUM(s.correct_count) AS correct_count, SUM(s.incorrect_count) AS incorrect_count, SUM(s.points) AS points, SUM(q.points) AS g_points FROM '.$this->_tableStatisticRef.' AS sf INNER JOIN '.$this->_tableStatistic.' AS s ON(s.statistic_ref_id = sf.statistic_ref_id) LEFT JOIN '.$this->_wpdb->users.' AS u ON(u.ID = sf.user_id) INNER JOIN '.$this->_tableQuestion.' AS q ON(q.id = s.question_id) WHERE sf.quiz_id = %d AND sf.is_old = 0 '.$where.' '.$timeWhere.' GROUP BY sf.statistic_ref_id ORDER BY sf.create_time DESC LIMIT %d, %d ', $quizId, $page, $limit), ARRAY_A ); $r = array(); foreach($result as $row) { if(!empty($row['user_login'])) $row['user_name'] = $row['user_login'] . ' ('. $row['display_name'] .')'; $r[] = new WpProQuiz_Model_StatisticHistory($row); } return $r; } public function countFormOverview($quizId, $onlyUser) { switch ($onlyUser) { case 1: $where = ' AND user_id > 0 '; break; case 2: $where = ' AND user_id = 0 '; break; default: $where = ''; } return $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(user_id) FROM {$this->_tableStatisticRef} WHERE quiz_id = %d AND form_data IS NOT NULL ".$where, $quizId ) ); } public function countHistory($quizId, $users = -1, $startTime = 0, $endTime = 0) { $timeWhere = ''; $where = ''; switch ($users) { case -3: //only anonym $where = 'AND user_id = 0'; break; case -2: //only reg user $where = 'AND user_id > 0'; break; case -1: //all $where = ''; break; default: $where = 'AND user_id = '.(int)$users; break; } if($startTime) $timeWhere = 'AND create_time >= '.(int)$startTime; if($endTime) $timeWhere .= ' AND create_time <= '.(int)$endTime; return $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(user_id) FROM {$this->_tableStatisticRef} WHERE quiz_id = %d AND is_old = 0 {$where} {$timeWhere}", $quizId ) ); } public function deleteByRefId($refId) { return $this->_wpdb->query( $this->_wpdb->prepare(' DELETE s, sf FROM '.$this->_tableStatistic.' AS s INNER JOIN '.$this->_tableStatisticRef.' AS sf ON (s.statistic_ref_id = sf.statistic_ref_id) WHERE sf.statistic_ref_id = %d ', $refId) ); } public function deleteByUserIdQuizId($userId, $quizId) { return $this->_wpdb->query( $this->_wpdb->prepare(' DELETE s, sf FROM '.$this->_tableStatistic.' AS s INNER JOIN '.$this->_tableStatisticRef.' AS sf ON (s.statistic_ref_id = sf.statistic_ref_id) WHERE sf.user_id = %d AND sf.quiz_id = %d ', $userId, $quizId) ); } public function fetchStatisticOverview($quizId, $onlyCompleded, $start, $limit) { $a = array(); $results = $this->_wpdb->get_results( $this->_wpdb->prepare( '( SELECT u.`user_login`, u.`display_name`, u.ID AS user_id, SUM(s.`correct_count`) as correct_count, SUM(s.`incorrect_count`) as incorrect_count, SUM(s.`hint_count`) as hint_count, SUM(s.`points`) as points, AVG(s.question_time) as question_time, SUM(q.points * (s.correct_count + s.incorrect_count)) AS g_points FROM '.$this->_wpdb->users.' AS u '.($onlyCompleded ? 'INNER' : 'LEFT').' JOIN '.$this->_tableStatisticRef.' AS sf ON (sf.user_id = u.ID AND sf.quiz_id = %d) LEFT JOIN '.$this->_tableStatistic.' AS s ON ( s.statistic_ref_id = sf.statistic_ref_id ) LEFT JOIN '.$this->_tableQuestion.' AS q ON(q.id = s.question_id) GROUP BY u.ID ) UNION ( SELECT NULL, NULL, 0, SUM(s.`correct_count`) as correct_count, SUM(s.`incorrect_count`) as incorrect_count, SUM(s.`hint_count`) as hint_count, SUM(s.`points`) as points, AVG(s.question_time) as question_time, SUM(q.points * (s.correct_count + s.incorrect_count)) AS g_points FROM '.$this->_tableMaster.' AS m '.($onlyCompleded ? 'INNER' : 'LEFT').' JOIN '.$this->_tableStatisticRef.' AS sf ON(sf.quiz_id = m.id AND sf.user_id = 0) LEFT JOIN '.$this->_tableStatistic.' AS s ON (s.statistic_ref_id = sf.statistic_ref_id) LEFT JOIN '.$this->_tableQuestion.' AS q ON (q.id = s.question_id) WHERE m.id = %d GROUP BY sf.user_id ) ORDER BY user_login LIMIT %d, %d', $quizId, $quizId, $start, $limit), ARRAY_A ); foreach($results as $row) { if(!empty($row['user_login'])) $row['user_name'] = $row['user_login'] . ' ('. $row['display_name'] .')'; $a[] = new WpProQuiz_Model_StatisticOverview($row); } return $a; } public function countOverviewNew($quizId, $onlyCompleded) { return $this->_wpdb->get_var( $this->_wpdb->prepare( 'SELECT COUNT(*) as g_count FROM ( (SELECT u.ID FROM '.$this->_wpdb->users.' AS u '.($onlyCompleded ? 'INNER' : 'LEFT').' JOIN '.$this->_tableStatisticRef.' AS sf ON (sf.user_id = u.ID AND sf.quiz_id = %d) LEFT JOIN '.$this->_tableStatistic.' AS s ON ( s.statistic_ref_id = sf.statistic_ref_id ) LEFT JOIN '.$this->_tableQuestion.' AS q ON(q.id = s.question_id) GROUP BY u.ID ) UNION (SELECT sf.user_id FROM '.$this->_tableMaster.' AS m '.($onlyCompleded ? 'INNER' : 'LEFT').' JOIN '.$this->_tableStatisticRef.' AS sf ON(sf.quiz_id = m.id AND sf.user_id = 0) LEFT JOIN '.$this->_tableStatistic.' AS s ON (s.statistic_ref_id = sf.statistic_ref_id) LEFT JOIN '.$this->_tableQuestion.' AS q ON (q.id = s.question_id) WHERE m.id = %d GROUP BY sf.user_id) ) AS c_all', $quizId, $quizId)); } public function fetchFrontAvg($quizId) { return $this->_wpdb->get_row($this->_wpdb->prepare( "SELECT SUM(s.points) AS points, SUM(q.points * (s.correct_count + s.incorrect_count)) AS g_points FROM {$this->_tableStatisticRef} AS sf INNER JOIN {$this->_tableStatistic} AS s ON ( s.statistic_ref_id = sf.statistic_ref_id ) INNER JOIN {$this->_tableQuestion} AS q ON ( q.id = s.question_id ) WHERE sf.quiz_id = %d", $quizId), ARRAY_A); } } lib/model/WpProQuiz_Model_GlobalSettings.php 0000666 00000002070 15214236625 0015175 0 ustar 00 <?php class WpProQuiz_Model_GlobalSettings extends WpProQuiz_Model_Model { protected $_addRawShortcode = false; protected $_jsLoadInHead = false; protected $_touchLibraryDeactivate = false; protected $_corsActivated = false; public function setAddRawShortcode($_addRawShortcode) { $this->_addRawShortcode = (bool)$_addRawShortcode; return $this; } public function isAddRawShortcode() { return $this->_addRawShortcode; } public function setJsLoadInHead($_jsLoadInHead) { $this->_jsLoadInHead = (bool)$_jsLoadInHead; return $this; } public function isJsLoadInHead() { return $this->_jsLoadInHead; } public function setTouchLibraryDeactivate($_touchLibraryDeactivate) { $this->_touchLibraryDeactivate = (bool)$_touchLibraryDeactivate; return $this; } public function isTouchLibraryDeactivate() { return $this->_touchLibraryDeactivate; } public function setCorsActivated($_corsActivated) { $this->_corsActivated = (bool)$_corsActivated; return $this; } public function isCorsActivated() { return $this->_corsActivated; } } lib/model/WpProQuiz_Model_Category.php 0000666 00000001001 15214236625 0014022 0 ustar 00 <?php class WpProQuiz_Model_Category extends WpProQuiz_Model_Model { protected $_categoryId = 0; protected $_categoryName = ''; public function setCategoryId($_categoryId) { $this->_categoryId = (int)$_categoryId; return $this; } public function getCategoryId() { return $this->_categoryId; } public function setCategoryName( $_categoryName = '' ) { $this->_categoryName = (string)$_categoryName; return $this; } public function getCategoryName() { return $this->_categoryName; } } lib/model/WpProQuiz_Model_AnswerTypes.php 0000666 00000006777 15214236625 0014562 0 ustar 00 <?php class WpProQuiz_Model_AnswerTypes extends WpProQuiz_Model_Model { protected $_answer = ''; protected $_html = false; protected $_points = LEARNDASH_LMS_DEFAULT_ANSWER_POINTS; protected $_correct = false; protected $_sortString = ''; protected $_sortStringHtml = false; protected $_graded = false; protected $_gradingProgression = 'not-graded-none'; protected $_gradedType = null; public function setAnswer($_answer) { $this->_answer = (string)$_answer; return $this; } public function getAnswer() { return $this->_answer; } public function setHtml($_html) { $this->_html = (bool)$_html; return $this; } public function isHtml() { return $this->_html; } public function setPoints($_points) { $this->_points = (int)$_points; return $this; } public function getPoints() { return $this->_points; } public function setCorrect($_correct) { $this->_correct = (bool)$_correct; return $this; } public function isCorrect() { return $this->_correct; } public function setSortString($_sortString) { $this->_sortString = (string)$_sortString; return $this; } public function getSortString() { return $this->_sortString; } public function setSortStringHtml($_sortStringHtml) { $this->_sortStringHtml = (bool)$_sortStringHtml; return $this; } public function isSortStringHtml() { return $this->_sortStringHtml; } public function setGraded($_graded) { $this->_graded = (string)$_graded; return $this; } public function isGraded() { return $this->_graded; } public function setGradedType($_gradedType) { $this->_gradedType = (string)$_gradedType; return $this; } public function getGradedType() { return $this->_gradedType; } public function setGradingProgression($_gradingProgression) { if ( ( is_null( $_gradingProgression ) ) || ( empty( $_gradingProgression ) ) ) { $_gradingProgression = 'not-graded-none'; } $this->_gradingProgression = (string)$_gradingProgression; return $this; } public function getGradingProgression() { if ( ( is_null( $this->_gradingProgression ) ) || ( empty( $this->_gradingProgression ) ) ) { $this->_gradingProgression = 'not-graded-none'; } return $this->_gradingProgression; } public function get_object_as_array() { $object_vars = array( '_answer' => $this->getAnswer(), '_html' => $this->isHtml(), '_points' => $this->getPoints(), '_correct' => $this->isCorrect(), '_sortString' => $this->getSortString(), '_sortStringHtml' => $this->isSortStringHtml(), '_graded' => $this->isGraded(), '_gradingProgression' => $this->getGradingProgression(), '_gradedType' => $this->getGradedType() ); return $object_vars; } public function set_array_to_object( $array_vars = array() ) { foreach( $array_vars as $key => $value ) { switch( $key ) { case '_answer': $this->setAnswer( $value ); break; case '_html': $this->setHtml( $value ); break; case '_points': $this->setPoints( $value ); break; case '_correct': $this->setCorrect( $value ); break; case '_sortString': $this->setSortString( $value ); break; case '_sortStringHtml': $this->setSortStringHtml( $value ); break; case '_graded': $this->setGraded( $value ); break; case '_gradingProgression': $this->setGradingProgression( $value ); break; case '_gradedType': $this->setGradedType( $value ); break; default: break; } } } } lib/model/WpProQuiz_Model_Toplist.php 0000666 00000003136 15214236625 0013716 0 ustar 00 <?php class WpProQuiz_Model_Toplist extends WpProQuiz_Model_Model { protected $_toplistId; protected $_quizId; protected $_userId; protected $_date; protected $_name; protected $_email; protected $_points; protected $_result; protected $_ip; public function setToplistId($_toplistId) { $this->_toplistId = (int)$_toplistId; return $this; } public function getToplistId() { return $this->_toplistId; } public function setQuizId($_quizId) { $this->_quizId = (int)$_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setUserId($_userId) { $this->_userId = (int)$_userId; return $this; } public function getUserId() { return $this->_userId; } public function setDate($_date) { $this->_date = (int)$_date; return $this; } public function getDate() { return $this->_date; } public function setName($_name) { $this->_name = (string)$_name; return $this; } public function getName() { return $this->_name; } public function setEmail($_email) { $this->_email = (string)$_email; return $this; } public function getEmail() { return $this->_email; } public function setPoints($_points) { $this->_points = (int)$_points; return $this; } public function getPoints() { return $this->_points; } public function setResult($_result) { $this->_result = (float)$_result; return $this; } public function getResult() { return $this->_result; } public function setIp($_ip) { $this->_ip = (string)$_ip; return $this; } public function getIp() { return $this->_ip; } } lib/model/WpProQuiz_Model_StatisticRefModel.php 0000666 00000005603 15214236625 0015646 0 ustar 00 <?php class WpProQuiz_Model_StatisticRefModel extends WpProQuiz_Model_Model { protected $_statisticRefId = 0; protected $_quizId = 0; protected $_userId = 0; protected $_createTime = 0; protected $_isOld = false; protected $_formData = null; protected $_minCreateTime = 0; protected $_maxCreateTime = 0; public function setStatisticRefId($_statisticRefId) { $this->_statisticRefId = (int)$_statisticRefId; return $this; } public function getStatisticRefId() { return $this->_statisticRefId; } public function setQuizId($_quizId) { $this->_quizId = (int)$_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setUserId($_userId) { $this->_userId = (int)$_userId; return $this; } public function getUserId() { return $this->_userId; } public function setCreateTime($_createTime) { $this->_createTime = (int)$_createTime; return $this; } public function getCreateTime() { return $this->_createTime; } public function setIsOld($_isOld) { $this->_isOld = (bool)$_isOld; return $this; } public function isIsOld() { return $this->_isOld; } public function setFormData($_formData) { $this->_formData = $_formData === null ? null : (array)$_formData; return $this; } public function getFormData() { return $this->_formData; } public function setMinCreateTime($_minCreateTime) { $this->_minCreateTime = (int)$_minCreateTime; return $this; } public function getMinCreateTime() { return $this->_minCreateTime; } public function setMaxCreateTime($_maxCreateTime) { $this->_maxCreateTime = (int)$_maxCreateTime; return $this; } public function getMaxCreateTime() { return $this->_maxCreateTime; } public function get_object_as_array() { $object_vars = array( '_statisticRefId' => $this->getStatisticRefId(), '_quizId' => $this->getQuizId(), '_userId' => $this->getUserId(), '_createTime' => $this->getCreateTime(), '_isOld' => $this->isIsOld(), '_formData' => $this->getFormData(), '_minCreateTime' => $this->getMinCreateTime(), '_maxCreateTime' => $this->getMaxCreateTime() ); return $object_vars; } public function set_array_to_object( $array_vars = array() ) { foreach( $array_vars as $key => $value ) { switch( $key ) { case '_statisticRefId': $this->setStatisticRefId( $value ); break; case '_quizId': $this->setQuizId( $value ); break; case '_userId': $this->setUserId( $value ); break; case '_createTime': $this->setCreateTime( $value ); break; case '_isOld': $this->isIsOld( $value ); break; case '_formData': $this->setFormData( $value ); break; case '_minCreateTime': $this->setMinCreateTime( $value ); break; case '_maxCreateTime': $this->setMaxCreateTime( $value ); break; } } } } lib/model/WpProQuiz_Model_StatisticUser.php 0000666 00000005761 15214236625 0015074 0 ustar 00 <?php class WpProQuiz_Model_StatisticUser extends WpProQuiz_Model_Model { protected $_correctCount = 0; protected $_incorrectCount = 0; protected $_hintCount = 0; protected $_points = 0; protected $_questionTime = 0; protected $_questionId = 0; protected $_questionName = ''; protected $_gPoints = 0; protected $_categoryId = 0; protected $_categoryName = ''; protected $_statisticAnswerData = null; protected $_questionAnswerData = null; protected $_answerType = ''; public function setCorrectCount($_correctCount) { $this->_correctCount = (int)$_correctCount; return $this; } public function getCorrectCount() { return $this->_correctCount; } public function setIncorrectCount($_incorrectCount) { $this->_incorrectCount = (int)$_incorrectCount; return $this; } public function getIncorrectCount() { return $this->_incorrectCount; } public function setHintCount($_hintCount) { $this->_hintCount = (int)$_hintCount; return $this; } public function getHintCount() { return $this->_hintCount; } public function setPoints($_points) { $this->_points = (int)$_points; return $this; } public function getPoints() { return $this->_points; } public function setQuestionTime($_questionTime) { $this->_questionTime = (int)$_questionTime; return $this; } public function getQuestionTime() { return $this->_questionTime; } public function setQuestionId($_questionId) { $this->_questionId = (int)$_questionId; return $this; } public function getQuestionId() { return $this->_questionId; } public function setQuestionName($_questionName) { $this->_questionName = (string)$_questionName; return $this; } public function getQuestionName() { return $this->_questionName; } public function setGPoints($_gPoints) { $this->_gPoints = (int)$_gPoints; return $this; } public function getGPoints() { return $this->_gPoints; } public function setCategoryId($_categoryId) { $this->_categoryId = (int)$_categoryId; return $this; } public function getCategoryId() { return $this->_categoryId; } public function setCategoryName($_categoryName) { $this->_categoryName = (string)$_categoryName; return $this; } public function getCategoryName() { return $this->_categoryName; } public function setStatisticAnswerData($_statisticAnswerData) { $this->_statisticAnswerData = $_statisticAnswerData; return $this; } public function getStatisticAnswerData() { return $this->_statisticAnswerData; } public function setQuestionAnswerData($_questionAnswerData) { $this->_questionAnswerData = null; if(WpProQuiz_Helper_Until::saveUnserialize($_questionAnswerData, $into) !== false) { $this->_questionAnswerData = $into; } return $this; } public function getQuestionAnswerData() { return $this->_questionAnswerData; } public function setAnswerType($_answerType) { $this->_answerType = (string)$_answerType; return $this; } public function getAnswerType() { return $this->_answerType; } } lib/model/WpProQuiz_Model_Lock.php 0000666 00000001762 15214236625 0013153 0 ustar 00 <?php class WpProQuiz_Model_Lock extends WpProQuiz_Model_Model { protected $_quizId; protected $_lockIp; protected $_lockDate; protected $_userId; protected $_lockType; const TYPE_STATISTIC = 1; const TYPE_QUIZ = 2; public function setQuizId($_quizId) { $this->_quizId = $_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setLockIp($_lockIp) { $this->_lockIp = $_lockIp; return $this; } public function getLockIp() { return $this->_lockIp; } public function setLockDate($_lockDate) { $this->_lockDate = $_lockDate; return $this; } public function getLockDate() { return $this->_lockDate; } public function setUserId($_userId) { $this->_userId = (int)$_userId; return $this; } public function getUserId() { return $this->_userId; } public function setLockType($_lockType) { $this->_lockType = (int)$_lockType; return $this; } public function getLockType() { return $this->_lockType; } } lib/model/WpProQuiz_Model_Template.php 0000666 00000001522 15214236625 0014030 0 ustar 00 <?php class WpProQuiz_Model_Template extends WpProQuiz_Model_Model { const TEMPLATE_TYPE_QUIZ = 0; const TEMPLATE_TYPE_QUESTION = 1; protected $_templateId = 0; protected $_name = ''; protected $_type = 0; protected $_data = null; public function setTemplateId($_templateId) { $this->_templateId = (int)$_templateId; return $this; } public function getTemplateId() { return $this->_templateId; } public function setName($_name) { $this->_name = (string)$_name; return $this; } public function getName() { return $this->_name; } public function setType($_type) { $this->_type = (int)$_type; return $this; } public function getType() { return $this->_type; } public function setData($_data) { $this->_data = $_data; return $this; } public function getData() { return $this->_data; } } lib/model/WpProQuiz_Model_StatisticOverview.php 0000666 00000003520 15214236625 0015753 0 ustar 00 <?php class WpProQuiz_Model_StatisticOverview extends WpProQuiz_Model_Model { protected $_correctCount = 0; protected $_incorrectCount = 0; protected $_hintCount = 0; protected $_points = 0; protected $_userName = ''; protected $_quizId = 0; protected $_userId = 0; protected $_questionTime = 0; protected $_gPoints = 0; public function setCorrectCount($_correctCount) { $this->_correctCount = (int)$_correctCount; return $this; } public function getCorrectCount() { return $this->_correctCount; } public function setIncorrectCount($_incorrectCount) { $this->_incorrectCount = (int)$_incorrectCount; return $this; } public function getIncorrectCount() { return $this->_incorrectCount; } public function setHintCount($_hintCount) { $this->_hintCount = (int)$_hintCount; return $this; } public function getHintCount() { return $this->_hintCount; } public function setPoints($_points) { $this->_points = (int)$_points; return $this; } public function getPoints() { return $this->_points; } public function setUserName($_userName) { $this->_userName = (string)$_userName; return $this; } public function getUserName() { return $this->_userName; } public function setQuizId($_quizId) { $this->_quizId = (int)$_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setUserId($_userId) { $this->_userId = (int)$_userId; return $this; } public function getUserId() { return $this->_userId; } public function setQuestionTime($_questionTime) { $this->_questionTime = (int)$_questionTime; return $this; } public function getQuestionTime() { return $this->_questionTime; } public function setGPoints($_gPoints) { $this->_gPoints = (int)$_gPoints; return $this; } public function getGPoints() { return $this->_gPoints; } } lib/model/WpProQuiz_Model_Quiz.php 0000666 00000065705 15214236625 0013222 0 ustar 00 <?php class WpProQuiz_Model_Quiz extends WpProQuiz_Model_Model { const QUIZ_RUN_ONCE_TYPE_ALL = 1; const QUIZ_RUN_ONCE_TYPE_ONLY_USER = 2; const QUIZ_RUN_ONCE_TYPE_ONLY_ANONYM = 3; const QUIZ_TOPLIST_TYPE_ALL = 1; const QUIZ_TOPLIST_TYPE_ONLY_USER = 2; const QUIZ_TOPLIST_TYPE_ONLY_ANONYM = 3; const QUIZ_TOPLIST_SORT_BEST = 1; const QUIZ_TOPLIST_SORT_NEW = 2; const QUIZ_TOPLIST_SORT_OLD = 3; const QUIZ_TOPLIST_SHOW_IN_NONE = 0; const QUIZ_TOPLIST_SHOW_IN_NORMAL = 1; const QUIZ_TOPLIST_SHOW_IN_BUTTON = 2; const QUIZ_MODUS_NORMAL = 0; const QUIZ_MODUS_BACK_BUTTON = 1; const QUIZ_MODUS_CHECK = 2; const QUIZ_MODUS_SINGLE = 3; const QUIZ_EMAIL_NOTE_NONE = 0; const QUIZ_EMAIL_NOTE_REG_USER = 1; const QUIZ_EMAIL_NOTE_ALL = 2; const QUIZ_FORM_POSITION_START = 0; const QUIZ_FORM_POSITION_END = 1; protected $_id = 0; protected $_quiz_post_id = 0; protected $_name = ''; protected $_text = ''; protected $_resultText = ''; protected $_titleHidden = true; protected $_btnRestartQuizHidden = false; protected $_btnViewQuestionHidden = false; protected $_questionRandom = false; protected $_answerRandom = false; protected $_timeLimit = 0; protected $_timeLimitCookie = 0; protected $_statisticsOn = true; protected $_viewPofileStatistics = true; // changed in v2.2.1.2 to default to '0' instead of '1440' protected $_statisticsIpLock = 0; protected $_resultGradeEnabled = true; protected $_showPoints = false; protected $_quizRunOnce = false; protected $_quizRunOnceType = 0; protected $_quizRunOnceCookie = false; protected $_quizRunOnceTime = 0; protected $_numberedAnswer = false; protected $_hideAnswerMessageBox = false; protected $_disabledAnswerMark = false; protected $_showMaxQuestion = false; protected $_showMaxQuestionValue = 1; protected $_showMaxQuestionPercent = false; //0.19 protected $_toplistActivated = false; protected $_toplistDataAddPermissions = 1; protected $_toplistDataSort = 1; protected $_toplistDataAddMultiple = false; protected $_toplistDataAddBlock = 1; protected $_toplistDataShowLimit = 1; protected $_toplistDataShowQuizResult = false; protected $_toplistDataShowIn = 0; protected $_toplistDataCaptcha = false; protected $_toplistData = array(); protected $_showAverageResult = false; protected $_prerequisite = false; //0.22 protected $_toplistDataAddAutomatic = false; protected $_quizModus = 0; protected $_showReviewQuestion = false; protected $_quizSummaryHide = true; protected $_skipQuestionDisabled = true; protected $_emailNotification = 0; //0.24 protected $_userEmailNotification = false; protected $_showCategoryScore = false; protected $_hideResultCorrectQuestion = false; protected $_hideResultQuizTime = false; protected $_hideResultPoints = false; //0.25 protected $_autostart = false; protected $_forcingQuestionSolve = false; protected $_hideQuestionPositionOverview = true; protected $_hideQuestionNumbering = true; //0.27 protected $_formActivated = false; protected $_formShowPosition = 0; protected $_startOnlyRegisteredUser = false; protected $_questionsPerPage = 0; protected $_sortCategories = false; protected $_showCategory = false; public function setId( $_id = 0 ) { $this->_id = (int) $_id; if ( empty( $this->_quiz_post_id ) ) { $this->_quiz_post_id = learndash_get_quiz_id_by_pro_quiz_id( $this->_id ); } return $this; } public function getId() { return $this->_id; } public function setPostId( $post_id ) { $this->_quiz_post_id = (int)$post_id; return $this; } public function getPostId() { return $this->_quiz_post_id; } public function setName($_name) { $this->_name = (string)$_name; return $this; } public function getName() { return $this->_name; } public function setText($_text) { $this->_text = (string)$_text; return $this; } public function getText() { return $this->_text; } public function setResultText($_resultText = '') { if (is_null( $_resultText )) $_resultText = ''; $this->_resultText = $_resultText; return $this; } public function getResultText() { if ( is_null( $this->_resultText ) ) { $this->_resultText = array(); } else if ( is_string( $this->_resultText ) ) { $this->_resultText = array( 'prozent' => array(0), 'activ' => array(1), 'text' => array( $this->_resultText ), ); } $this->_resultText = learndash_quiz_result_message_sort( $this->_resultText ); return $this->_resultText; } public function setTitleHidden($_titleHidden) { $this->_titleHidden = (bool)$_titleHidden; return $this; } public function isTitleHidden() { return $this->_titleHidden; } public function setQuestionRandom($_questionRandom) { $this->_questionRandom = (bool)$_questionRandom; return $this; } public function isQuestionRandom() { return $this->_questionRandom; } public function setAnswerRandom($_answerRandom) { $this->_answerRandom = (bool)$_answerRandom; return $this; } public function isAnswerRandom() { return $this->_answerRandom; } public function setTimeLimit($_timeLimit) { $this->_timeLimit = (int)$_timeLimit; return $this; } public function getTimeLimit() { return $this->_timeLimit; } public function setTimeLimitCookie($_timeLimitCookie) { $this->_timeLimitCookie = (int)$_timeLimitCookie; return $this; } // The TimeLimitCookie var does NOT follow the convention for the WPProQuiz in that it is not stored into the wp_wp_pro_quiz_master table // Instead it is read from and save to the post meta table public function getTimeLimitCookie() { if ( ( property_exists( $this, '_quiz_post_id') ) && ( !empty( $this->_quiz_post_id ) ) ) { $this->_timeLimitCookie = get_post_meta($this->_quiz_post_id, '_timeLimitCookie', true); } return absint( $this->_timeLimitCookie ); } public function saveTimeLimitCookie() { if ( ( property_exists( $this, '_quiz_post_id') ) && ( !empty( $this->_quiz_post_id ) ) ) { return update_post_meta( $this->_quiz_post_id, '_timeLimitCookie', $this->_timeLimitCookie ); } } public function getViewProfileStatistics() { if ( ( property_exists( $this, '_quiz_post_id') ) && ( !empty( $this->_quiz_post_id ) ) ) { $this->_viewPofileStatistics = get_post_meta($this->_quiz_post_id, '_viewProfileStatistics', true); } // standardize the value if ( '1' === $this->_viewPofileStatistics ) { $this->_viewPofileStatistics = true; } else { $this->_viewPofileStatistics = false; } return apply_filters( 'learndash_quiz_default_viewPofileStatistics', $this->_viewPofileStatistics ); } public function setViewProfileStatistics( $_viewPofileStatistics ) { $this->_viewPofileStatistics = $_viewPofileStatistics; } public function saveViewProfileStatistics() { if ( property_exists( $this, '_quiz_post_id') ) { return update_post_meta( $this->_quiz_post_id, '_viewProfileStatistics', $this->_viewPofileStatistics ); } } public function setStatisticsOn($_statisticsOn) { $this->_statisticsOn = (bool)$_statisticsOn; return $this; } public function isStatisticsOn() { return $this->_statisticsOn; } public function setStatisticsIpLock($_statisticsIpLock) { $this->_statisticsIpLock = (int)$_statisticsIpLock; return $this; } public function getStatisticsIpLock() { return $this->_statisticsIpLock; } public function setResultGradeEnabled($_resultGradeEnabled) { //$this->_resultGradeEnabled = (bool)$_resultGradeEnabled; $this->_resultGradeEnabled = true; return $this; } public function isResultGradeEnabled() { //return $this->_resultGradeEnabled; return true; } public function setShowPoints($_showPoints) { $this->_showPoints = (bool)$_showPoints; return $this; } public function isShowPoints() { return $this->_showPoints; } public function fetchSumQuestionPoints() { $m = new WpProQuiz_Model_QuizMapper(); return $m->sumQuestionPoints($this->_id); } public function fetchCountQuestions() { $m = new WpProQuiz_Model_QuizMapper(); return $m->countQuestion($this->_id); } public function setBtnRestartQuizHidden($_btnRestartQuizHidden) { $this->_btnRestartQuizHidden = (bool)$_btnRestartQuizHidden; return $this; } public function isBtnRestartQuizHidden() { return $this->_btnRestartQuizHidden; } public function setBtnViewQuestionHidden($_btnViewQuestionHidden) { $this->_btnViewQuestionHidden = (bool)$_btnViewQuestionHidden; return $this; } public function isBtnViewQuestionHidden() { return $this->_btnViewQuestionHidden; } public function setQuizRunOnce($_quizRunOnce) { $this->_quizRunOnce = (bool)$_quizRunOnce; return $this; } public function isQuizRunOnce() { return $this->_quizRunOnce; } public function setQuizRunOnceCookie($_quizRunOnceCookie) { $this->_quizRunOnceCookie = (bool)$_quizRunOnceCookie; return $this; } public function isQuizRunOnceCookie() { return $this->_quizRunOnceCookie; } public function setQuizRunOnceType($_quizRunOnceType) { $this->_quizRunOnceType = (int)$_quizRunOnceType; return $this; } public function getQuizRunOnceType() { return $this->_quizRunOnceType; } public function setQuizRunOnceTime($_quizRunOnceTime) { $this->_quizRunOnceTime = (int)$_quizRunOnceTime; return $this; } public function getQuizRunOnceTime() { return $this->_quizRunOnceTime; } public function setNumberedAnswer($_numberedAnswer) { $this->_numberedAnswer = (bool)$_numberedAnswer; return $this; } public function isNumberedAnswer() { return $this->_numberedAnswer; } public function setHideAnswerMessageBox($_hideAnswerMessageBox) { $this->_hideAnswerMessageBox = (bool)$_hideAnswerMessageBox; return $this; } public function isHideAnswerMessageBox() { return $this->_hideAnswerMessageBox; } public function setDisabledAnswerMark($_disabledAnswerMark) { $this->_disabledAnswerMark = (bool)$_disabledAnswerMark; return $this; } public function isDisabledAnswerMark() { return $this->_disabledAnswerMark; } public function setShowMaxQuestion($_showMaxQuestion) { $this->_showMaxQuestion = (bool)$_showMaxQuestion; return $this; } public function isShowMaxQuestion() { return $this->_showMaxQuestion; } public function setShowMaxQuestionValue($_showMaxQuestionValue) { $this->_showMaxQuestionValue = (int)$_showMaxQuestionValue; return $this; } public function getShowMaxQuestionValue() { return $this->_showMaxQuestionValue; } public function setShowMaxQuestionPercent($_showMaxQuestionPercent) { $this->_showMaxQuestionPercent = (bool)$_showMaxQuestionPercent; return $this; } public function isShowMaxQuestionPercent() { return $this->_showMaxQuestionPercent; } public function setToplistActivated($_toplistActivated) { $this->_toplistActivated = (bool)$_toplistActivated; return $this; } public function isToplistActivated() { return $this->_toplistActivated; } public function setToplistDataAddPermissions($_toplistDataAddPermissions) { $this->_toplistDataAddPermissions = (int)$_toplistDataAddPermissions; return $this; } public function getToplistDataAddPermissions() { return $this->_toplistDataAddPermissions; } public function setToplistDataSort($_toplistDataSort) { $this->_toplistDataSort = (int)$_toplistDataSort; return $this; } public function getToplistDataSort() { return $this->_toplistDataSort; } public function setToplistDataAddMultiple($_toplistDataAddMultiple) { $this->_toplistDataAddMultiple = (bool)$_toplistDataAddMultiple; return $this; } public function isToplistDataAddMultiple() { return $this->_toplistDataAddMultiple; } public function setToplistDataAddBlock($_toplistDataAddBlock) { $this->_toplistDataAddBlock = (int)$_toplistDataAddBlock; return $this; } public function getToplistDataAddBlock() { return $this->_toplistDataAddBlock; } public function setToplistDataShowLimit($_toplistDataShowLimit) { $this->_toplistDataShowLimit = (int)$_toplistDataShowLimit; return $this; } public function getToplistDataShowLimit() { return $this->_toplistDataShowLimit; } public function setToplistData($_toplistData) { if(!empty($_toplistData)) { $d = unserialize($_toplistData); if($d !== false) { $this->setModelData($d); } } return $this; } public function getToplistData() { $a = array( 'toplistDataAddPermissions' => $this->getToplistDataAddPermissions(), 'toplistDataSort' => $this->getToplistDataSort(), 'toplistDataAddMultiple' => $this->isToplistDataAddMultiple(), 'toplistDataAddBlock' => $this->getToplistDataAddBlock(), 'toplistDataShowLimit' => $this->getToplistDataShowLimit(), 'toplistDataShowIn' => $this->getToplistDataShowIn(), 'toplistDataCaptcha' => $this->isToplistDataCaptcha(), 'toplistDataAddAutomatic' => $this->isToplistDataAddAutomatic() ); return serialize($a); } public function setToplistDataShowIn($_toplistDataShowIn) { $this->_toplistDataShowIn = (int)$_toplistDataShowIn; return $this; } public function getToplistDataShowIn() { return $this->_toplistDataShowIn; } public function setToplistDataCaptcha($_toplistDataCaptcha) { $this->_toplistDataCaptcha = (bool)$_toplistDataCaptcha; return $this; } public function isToplistDataCaptcha() { return $this->_toplistDataCaptcha; } public function setShowAverageResult($_showAverageResult) { $this->_showAverageResult = (bool)$_showAverageResult; return $this; } public function isShowAverageResult() { return $this->_showAverageResult; } public function setPrerequisite($_prerequisite) { $this->_prerequisite = (bool)$_prerequisite; return $this; } public function isPrerequisite() { return $this->_prerequisite; } public function setToplistDataAddAutomatic($_toplistDataAddAutomatic) { $this->_toplistDataAddAutomatic = (bool)$_toplistDataAddAutomatic; return $this; } public function isToplistDataAddAutomatic() { return $this->_toplistDataAddAutomatic; } public function setQuizModus($_quizModus) { $this->_quizModus = (int)$_quizModus; return $this; } public function getQuizModus() { return $this->_quizModus; } public function setShowReviewQuestion($_showReviewQuestion) { $this->_showReviewQuestion = (bool)$_showReviewQuestion; return $this; } public function isShowReviewQuestion() { return $this->_showReviewQuestion; } public function setQuizSummaryHide($_quizSummaryHide) { $this->_quizSummaryHide = (bool)$_quizSummaryHide; return $this; } public function isQuizSummaryHide() { return $this->_quizSummaryHide; } public function setSkipQuestionDisabled($_skipQuestion) { $this->_skipQuestionDisabled = (bool)$_skipQuestion; return $this; } public function isSkipQuestionDisabled() { return $this->_skipQuestionDisabled; } public function setEmailNotification($_emailNotification) { $this->_emailNotification = (int)$_emailNotification; return $this; } public function getEmailNotification() { return $this->_emailNotification; } public function setUserEmailNotification($_userEmailNotification) { $this->_userEmailNotification = (bool)$_userEmailNotification; return $this; } public function isUserEmailNotification() { return $this->_userEmailNotification; } public function setShowCategoryScore($_showCategoryScore) { $this->_showCategoryScore = (bool)$_showCategoryScore; return $this; } public function isShowCategoryScore() { return $this->_showCategoryScore; } public function setHideResultCorrectQuestion($_hideResultCorrectQuestion) { $this->_hideResultCorrectQuestion = (bool)$_hideResultCorrectQuestion; return $this; } public function isHideResultCorrectQuestion() { return $this->_hideResultCorrectQuestion; } public function setHideResultQuizTime($_hideResultQuizTime) { $this->_hideResultQuizTime = (bool)$_hideResultQuizTime; return $this; } public function isHideResultQuizTime() { return $this->_hideResultQuizTime; } public function setHideResultPoints($_hideResultPoints) { $this->_hideResultPoints = (bool)$_hideResultPoints; return $this; } public function isHideResultPoints() { return $this->_hideResultPoints; } public function setAutostart($_autostart) { $this->_autostart = (bool)$_autostart; return $this; } public function isAutostart() { return $this->_autostart; } public function setForcingQuestionSolve($_forcingQuestionSolve) { $this->_forcingQuestionSolve = (bool)$_forcingQuestionSolve; return $this; } public function isForcingQuestionSolve() { return $this->_forcingQuestionSolve; } public function setHideQuestionPositionOverview($_hideQuestionPositionOverview) { $this->_hideQuestionPositionOverview = (bool)$_hideQuestionPositionOverview; return $this; } public function isHideQuestionPositionOverview() { return $this->_hideQuestionPositionOverview; } public function setHideQuestionNumbering($_hideQuestionNumbering) { $this->_hideQuestionNumbering = (bool)$_hideQuestionNumbering; return $this; } public function isHideQuestionNumbering() { return $this->_hideQuestionNumbering; } public function setFormActivated($_formActivated) { $this->_formActivated = (bool)$_formActivated; return $this; } public function isFormActivated() { return $this->_formActivated; } public function setFormShowPosition($_formShowPosition) { $this->_formShowPosition = (int)$_formShowPosition; return $this; } public function getFormShowPosition() { return $this->_formShowPosition; } public function setStartOnlyRegisteredUser($_startOnlyRegisteredUser) { $this->_startOnlyRegisteredUser = (bool)$_startOnlyRegisteredUser; return $this; } public function isStartOnlyRegisteredUser() { return $this->_startOnlyRegisteredUser; } public function setQuestionsPerPage($_questionsPerPage) { $this->_questionsPerPage = (int)$_questionsPerPage; return $this; } public function getQuestionsPerPage() { return $this->_questionsPerPage; } public function setSortCategories($_sortCategories) { $this->_sortCategories = (bool)$_sortCategories; return $this; } public function isSortCategories() { return $this->_sortCategories; } public function setShowCategory($_showCategory) { $this->_showCategory = (bool)$_showCategory; return $this; } public function isShowCategory() { return $this->_showCategory; } public function get_object_as_array() { $object_vars = array( '_quiz_post_id' => 0, '_name' => $this->getName(), //'_text' => $this->getText(), '_resultText' => $this->getResultText(), '_titleHidden' => $this->isTitleHidden(), '_btnRestartQuizHidden' => $this->isBtnRestartQuizHidden(), '_btnViewQuestionHidden' => $this->isBtnViewQuestionHidden(), '_questionRandom' => $this->isQuestionRandom(), '_answerRandom' => $this->isAnswerRandom(), '_timeLimit' => $this->getTimeLimit(), '_timeLimitCookie' => $this->getTimeLimitCookie(), '_statisticsOn' => $this->isStatisticsOn(), '_viewPofileStatistics' => $this->getViewProfileStatistics(), '_statisticsIpLock' => $this->getStatisticsIpLock(), '_resultGradeEnabled' => $this->isResultGradeEnabled(), '_showPoints' => $this->isShowPoints(), '_quizRunOnce' => $this->isQuizRunOnce(), '_quizRunOnceType' => $this->getQuizRunOnceType(), '_quizRunOnceCookie' => $this->isQuizRunOnceCookie(), '_quizRunOnceTime' => $this->getQuizRunOnceTime(), '_numberedAnswer' => $this->isNumberedAnswer(), '_hideAnswerMessageBox' => $this->isHideAnswerMessageBox(), '_disabledAnswerMark' => $this->isDisabledAnswerMark(), '_showMaxQuestion' => $this->isShowMaxQuestion(), '_showMaxQuestionValue' => $this->getShowMaxQuestionValue(), '_showMaxQuestionPercent' => $this->isShowMaxQuestionPercent(), '_toplistActivated' => $this->isToplistActivated(), '_toplistDataAddPermissions' => $this->getToplistDataAddPermissions(), '_toplistDataSort' => $this->getToplistDataSort(), '_toplistDataAddMultiple' => $this->isToplistDataAddMultiple(), '_toplistDataAddBlock' => $this->getToplistDataAddBlock(), '_toplistDataShowLimit' => $this->getToplistDataShowLimit(), '_toplistDataShowIn' => $this->getToplistDataShowIn(), '_toplistDataCaptcha' => $this->isToplistDataCaptcha(), '_toplistData' => $this->getToplistData(), '_showAverageResult' => $this->isShowAverageResult(), '_prerequisite' => $this->isPrerequisite(), '_toplistDataAddAutomatic' => $this->isToplistDataAddAutomatic(), '_quizModus' => $this->getQuizModus(), '_showReviewQuestion' => $this->isShowReviewQuestion(), '_quizSummaryHide' => $this->isQuizSummaryHide(), '_skipQuestionDisabled' => $this->isSkipQuestionDisabled(), '_emailNotification' => $this->getEmailNotification(), '_userEmailNotification' => $this->isUserEmailNotification(), '_showCategoryScore' => $this->isShowCategoryScore(), '_hideResultCorrectQuestion' => $this->isHideResultCorrectQuestion(), '_hideResultQuizTime' => $this->isHideResultQuizTime(), '_hideResultPoints' => $this->isHideResultPoints(), '_autostart' => $this->isAutostart(), '_forcingQuestionSolve' => $this->isForcingQuestionSolve(), '_hideQuestionPositionOverview' => $this->isHideQuestionPositionOverview(), '_hideQuestionNumbering' => $this->isHideQuestionNumbering(), '_formActivated' => $this->isFormActivated(), '_formShowPosition' => $this->getFormShowPosition(), '_startOnlyRegisteredUser' => $this->isStartOnlyRegisteredUser(), '_questionsPerPage' => $this->getQuestionsPerPage(), '_sortCategories' => $this->isSortCategories(), '_showCategory' => $this->isShowCategory() ); return $object_vars; } public function set_array_to_object( $array_vars = array() ) { $array_vars['_text'] = "AAZZAAZZ"; foreach( $array_vars as $key => $value ) { switch( $key ) { case '_name': $this->setName( $value ); break; case '_text': $this->setText( "AAZZAAZZ" ); break; case '_resultText': $this->setResultText( $value ); break; case '_titleHidden': $this->setTitleHidden( $value ); break; case '_btnRestartQuizHidden': $this->setBtnRestartQuizHidden( $value ); break; case '_btnViewQuestionHidden': $this->setBtnViewQuestionHidden( $value ); break; case '_questionRandom': $this->setQuestionRandom( $value ); break; case '_answerRandom': $this->setAnswerRandom( $value ); break; case '_timeLimit': $this->setTimeLimit( $value ); break; case '_timeLimitCookie': $this->setTimeLimitCookie( $value ); break; case '_statisticsOn': $this->setStatisticsOn( $value ); break; case '_viewPofileStatistics': $this->setViewProfileStatistics( $value ); break; case '_statisticsIpLock': $this->setStatisticsIpLock( $value ); break; case '_resultGradeEnabled': $this->setResultGradeEnabled( $value ); break; case '_showPoints': $this->setShowPoints( $value ); break; case '_quizRunOnce': $this->setQuizRunOnce( $value ); break; case 'setQuizRunOnceCookie': $this->setQuizRunOnceType( $value ); break; case '_quizRunOnceCookie': $this->setQuizRunOnceCookie( $value ); break; case '_quizRunOnceTime': $this->setQuizRunOnceTime( $value ); break; case '_numberedAnswer': $this->setNumberedAnswer( $value ); break; case '_hideAnswerMessageBox': $this->setHideAnswerMessageBox( $value ); break; case '_disabledAnswerMark': $this->setDisabledAnswerMark( $value ); break; case '_showMaxQuestion': $this->setShowMaxQuestion( $value ); break; case '_showMaxQuestionValue': $this->setShowMaxQuestionValue( $value ); break; case '_showMaxQuestionPercent': $this->setShowMaxQuestionPercent( $value ); break; case '_toplistActivated': $this->setToplistActivated( $value ); break; case '_toplistDataAddPermissions': $this->setToplistDataAddPermissions( $value ); break; case '_toplistDataSort': $this->setToplistDataSort( $value ); break; case '_toplistDataAddMultiple': $this->setToplistDataAddMultiple( $value ); break; case '_toplistDataAddBlock': $this->setToplistDataAddBlock( $value ); break; case '_toplistDataShowLimit': $this->setToplistDataShowLimit( $value ); break; case '_toplistDataShowIn': $this->setToplistDataShowIn( $value ); break; case '_toplistDataCaptcha': $this->setToplistDataCaptcha( $value ); break; case '_toplistData': $this->setToplistData( $value ); break; case '_showAverageResult': $this->setShowAverageResult( $value ); break; case '_prerequisite': $this->setPrerequisite( $value ); break; case '_toplistDataAddAutomatic': $this->setToplistDataAddAutomatic( $value ); break; case '_quizModus': $this->setQuizModus( $value ); break; case '_showReviewQuestion': $this->setShowReviewQuestion( $value ); break; case '_quizSummaryHide': $this->setQuizSummaryHide( $value ); break; case '_skipQuestionDisabled': $this->setSkipQuestionDisabled( $value ); break; case '_emailNotification': $this->setEmailNotification( $value ); break; case '_userEmailNotification': $this->setUserEmailNotification( $value ); break; case '_showCategoryScore': $this->setShowCategoryScore( $value ); break; case '_hideResultCorrectQuestion': $this->setHideResultCorrectQuestion( $value ); break; case '_hideResultQuizTime': $this->setHideResultQuizTime( $value ); break; case '_hideResultPoints': $this->setHideResultPoints( $value ); break; case '_autostart': $this->setAutostart( $value ); break; case '_forcingQuestionSolve': $this->setForcingQuestionSolve( $value ); break; case '_hideQuestionPositionOverview': $this->setHideQuestionPositionOverview( $value ); break; case '_hideQuestionNumbering': $this->setHideQuestionNumbering( $value ); break; case '_formActivated': $this->setFormActivated( $value ); break; case '_formShowPosition': $this->setFormShowPosition( $value ); break; case '_startOnlyRegisteredUser': $this->setStartOnlyRegisteredUser( $value ); break; case '_questionsPerPage': $this->setQuestionsPerPage( $value ); break; case '_sortCategories': $this->setSortCategories( $value ); break; case '_showCategory': $this->setShowCategoryScore( $value ); break; default: break; } } } } lib/model/WpProQuiz_Model_LockMapper.php 0000666 00000004051 15214236625 0014312 0 ustar 00 <?php class WpProQuiz_Model_LockMapper extends WpProQuiz_Model_Mapper { protected $_table; public function __construct() { parent::__construct(); //$this->_table = $this->_prefix.'lock'; $this->_table = $this->_tableLock; } public function insert(WpProQuiz_Model_Lock $lock) { $this->_wpdb->insert($this->_table, array( 'quiz_id' => $lock->getQuizId(), 'lock_ip' => $lock->getLockIp(), 'user_id' => $lock->getUserId(), 'lock_type' => $lock->getLockType(), 'lock_date' => $lock->getLockDate(), 'lock_type' => $lock->getLockType() ), array('%d', '%s', '%d', '%d', '%d', '%d')); } public function fetch($quizId, $lockIp, $userId) { $row = $this->_wpdb->get_row( $this->_wpdb->prepare( "SELECT * FROM ". $this->_table. " WHERE quiz_id = %d AND lock_ip = %s AND user_id = %d", $quizId, $lockIp, $userId) ); if($row === null) return null; return new WpProQuiz_Model_Lock($row); } public function isLock($quizId, $lockIp, $userId, $type) { $c = $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(*) FROM {$this->_table} WHERE quiz_id = %d AND lock_ip = %s AND user_id = %d AND lock_type = %d", $quizId, $lockIp, $userId, $type)); if($c === null || $c == 0) return false; return true; } public function deleteOldLock($lockTime, $quizId, $time, $type, $userId = false) { $user = ''; if($userId !== false) { $user = 'AND user_id = '.((int) $userId); } return $this->_wpdb->query( $this->_wpdb->prepare( "DELETE FROM {$this->_table} WHERE quiz_id = %d AND (lock_date + %d) < %d AND lock_type = %d ".$user, $quizId, $lockTime, $time, $type ) ); } public function deleteByQuizId($quizId, $type = false) { $where = array('quiz_id' => $quizId); $whereP = array('%d'); if($type !== false) { $where = array('quiz_id' => $quizId, 'lock_type' => $type); $whereP = array('%d', '%d'); } return $this->_wpdb->delete($this->_tableLock, $where, $whereP); } } lib/model/WpProQuiz_Model_ToplistMapper.php 0000666 00000005511 15214236625 0015062 0 ustar 00 <?php class WpProQuiz_Model_ToplistMapper extends WpProQuiz_Model_Mapper { public function countFree($quizId, $name, $email, $ip, $clearTime = null) { $c = ''; if($clearTime !== null) { $c = 'AND date >= '.(time() - $clearTime); } $flooding = time() - 15; return $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(*) FROM {$this->_tableToplist} WHERE quiz_id = %d AND (name = %s OR email = %s OR (ip = %s AND date >= {$flooding})) ".$c, $quizId, $name, $email, $ip ) ); } public function countUser($quizId, $userId, $clearTime = null) { $c = ''; if($clearTime !== null) { $c = 'AND date >= '.(time() - $clearTime); } return $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(*) FROM {$this->_tableToplist} WHERE quiz_id = %d AND user_id = %d ".$c, $quizId, $userId ) ); } public function count($quizId) { return $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(*) FROM {$this->_tableToplist} WHERE quiz_id = %d", $quizId ) ); } public function save(WpProQuiz_Model_Toplist $toplist) { $result = $this->_wpdb->insert($this->_tableToplist, array( 'quiz_id' => $toplist->getQuizId(), 'user_id' => $toplist->getUserId(), 'date' => $toplist->getDate(), 'name' => $toplist->getName(), 'email' => $toplist->getEmail(), 'points' => $toplist->getPoints(), 'result' => $toplist->getResult(), 'ip' => $toplist->getIp()), array('%d', '%d', '%d', '%s', '%s', '%d', '%f', '%s')); $toplist->setToplistId($this->_wpdb->insert_id); } public function fetch($quizId, $limit, $sort, $start = 0) { $s = ''; $r = array(); $start = (int)$start; switch ($sort) { case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SORT_BEST: $s = 'ORDER BY result DESC'; break; case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SORT_NEW: $s = 'ORDER BY date DESC'; break; case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SORT_OLD: default: $s = 'ORDER BY date ASC'; break; } $results = $this->_wpdb->get_results( $this->_wpdb->prepare( 'SELECT * FROM '. $this->_tableToplist.' WHERE quiz_id = %d '.$s.' LIMIT %d, %d' , $quizId, $start, $limit), ARRAY_A); foreach($results as $row) { $r[] = new WpProQuiz_Model_Toplist($row); } return $r; } public function delete($quizId, $toplistIds = null) { $quizId = (int)$quizId; if($toplistIds === null) { return $this->_wpdb->delete($this->_tableToplist, array('quiz_id' => $quizId), array('%d')); } $ids = array_map('intval', (array)$toplistIds); return $this->_wpdb->query("DELETE FROM {$this->_tableToplist} WHERE quiz_id = {$quizId} AND toplist_id IN(".implode(', ', $ids).")"); } } lib/model/WpProQuiz_Model_Form.php 0000666 00000004764 15214236625 0013173 0 ustar 00 <?php class WpProQuiz_Model_Form extends WpProQuiz_Model_Model { const FORM_TYPE_TEXT = 0; const FORM_TYPE_TEXTAREA = 1; const FORM_TYPE_NUMBER = 2; const FORM_TYPE_CHECKBOX = 3; const FORM_TYPE_EMAIL = 4; const FORM_TYPE_YES_NO = 5; const FORM_TYPE_DATE = 6; const FORM_TYPE_SELECT = 7; const FORM_TYPE_RADIO = 8; protected $_formId = 0; protected $_quizId = 0; protected $_fieldname = ''; protected $_type = 0; protected $_required = false; protected $_sort = 0; protected $_data = null; public function setFormId($_formId) { $this->_formId = (int)$_formId; return $this; } public function getFormId() { return $this->_formId; } public function setQuizId($_quizId) { $this->_quizId = (int)$_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setFieldname($_fieldname) { $this->_fieldname = (string)$_fieldname; return $this; } public function getFieldname() { return $this->_fieldname; } public function setType($_type) { $this->_type = (int)$_type; return $this; } public function getType() { return $this->_type; } public function setRequired($_required) { $this->_required = (bool)$_required; return $this; } public function isRequired() { return $this->_required; } public function setSort($_sort) { $this->_sort = (int)$_sort; return $this; } public function getSort() { return $this->_sort; } public function setData($_data) { $this->_data = $_data === null ? null : (array)$_data; return $this; } public function getData() { return $this->_data; } public function getValue( $form_data = '' ) { switch ( $this->getType() ) { case WpProQuiz_Model_Form::FORM_TYPE_TEXT: case WpProQuiz_Model_Form::FORM_TYPE_TEXTAREA: case WpProQuiz_Model_Form::FORM_TYPE_EMAIL: case WpProQuiz_Model_Form::FORM_TYPE_NUMBER: case WpProQuiz_Model_Form::FORM_TYPE_RADIO: case WpProQuiz_Model_Form::FORM_TYPE_SELECT: return esc_html( $form_data ); break; case WpProQuiz_Model_Form::FORM_TYPE_CHECKBOX: return $form_data == '1' ? esc_html__('ticked', 'learndash') : esc_html__('not ticked', 'learndash'); break; case WpProQuiz_Model_Form::FORM_TYPE_YES_NO: return $form_data == 1 ? esc_html__('Yes', 'learndash') : esc_html__('No', 'learndash'); break; case WpProQuiz_Model_Form::FORM_TYPE_DATE: return date_format( date_create( $form_data ), get_option( 'date_format' ) ); break; default: return $form_data; break; } } } lib/model/WpProQuiz_Model_StatisticMapper.php 0000666 00000006637 15214236625 0015405 0 ustar 00 <?php class WpProQuiz_Model_StatisticMapper extends WpProQuiz_Model_Mapper { public function fetchAllByRef($statisticRefId) { $a = array(); $results = $this->_wpdb->get_results( $this->_wpdb->prepare( 'SELECT * FROM '. $this->_tableStatistic.' WHERE statistic_ref_id = %d', $statisticRefId), ARRAY_A); foreach($results as $row) { $a[] = new WpProQuiz_Model_Statistic($row); } return $a; } public function isStatisticByQuestionId($questionId) { return $this->_wpdb->get_var( $this->_wpdb->prepare( "SELECT COUNT(*) FROM {$this->_tableStatistic} WHERE question_id = %d", $questionId) ); } /* public function save($s) { $values = array(); if($s->getUserId()) { $refId = $this->_wpdb->get_var( $this->_wpdb->prepare(' SELECT statistic_ref_id FROM '.$this->_tableStatisticRef.' WHERE quiz_id = %d AND user_id = %d ', $quiz_id, $user_id) ); if($refId === null) { $this->_wpdb->insert($this->_tableStatisticRef, array( 'quiz_id' => 0, 'user_id' => 0, 'create_time' => 0, 'is_old' => 1 ), array( '%d', '%d', '%d', '%d' )); } } foreach($s as $d) { $values[] = '( '.implode(', ', array( 'quiz_id' => $d->getQuizId(), 'question_id' => $d->getQuestionId(), 'user_id' => $d->getUserId(), 'correct_count' => $d->getCorrectCount(), 'incorrect_count' => $d->getIncorrectCount(), 'hint_count' => $d->getHintCount(), 'points' => $d->getPoints() )).' )'; } $this->_wpdb->query( 'INSERT INTO '.$this->_tableStatistic.' ( quiz_id, question_id, user_id, correct_count, incorrect_count, hint_count, points ) VALUES '.implode(', ', $values).' ON DUPLICATE KEY UPDATE correct_count = correct_count + VALUES(correct_count), incorrect_count = incorrect_count + VALUES(incorrect_count), hint_count = hint_count + VALUES(hint_count), points = points + VALUES(points)' ); } */ /* public function save($quizId, $userId, $array) { $ids = $this->_wpdb->get_col($this->_wpdb->prepare("SELECT id FROM {$this->_tableQuestion} WHERE quiz_id = %d", $quizId)); $ak = array_keys($array); if(array_diff($ids, $ak) !== array_diff($ak, $ids)) return false; $values = array(); $globalValue = array( 'quiz_id' => $quizId, 'question_id' => 0, 'user_id' => $userId, 'correct_count' => 0, 'incorrect_count' => 0, 'hint_count' => 0, 'correct_answer_count' => 0 ); foreach($array as $k => $v) { $value = $globalValue; $value['question_id'] = $k; if(isset($v['tip'])) { $value['hint_count'] = 1; } if($v['correct']) { $value['correct_count'] = 1; } else { $value['incorrect_count'] = 1; } $value['correct_answer_count'] = isset($v['correct_answer_count']) ? (int)$v['correct_answer_count'] : 0; $values[] = '('.implode(', ', $value).')'; } $this->_wpdb->query( 'INSERT INTO '.$this->_tableStatistic.' ('.implode(', ', array_keys($globalValue)).') VALUES '.implode(', ', $values).' ON DUPLICATE KEY UPDATE correct_count = correct_count + VALUES(correct_count), incorrect_count = incorrect_count + VALUES(incorrect_count), hint_count = hint_count + VALUES(hint_count), correct_answer_count = correct_answer_count + VALUES(correct_answer_count)' ); } */ } lib/model/WpProQuiz_Model_Question.php 0000666 00000023604 15214236625 0014071 0 ustar 00 <?php class WpProQuiz_Model_Question extends WpProQuiz_Model_Model { protected $_id = 0; protected $_questionPostId = 0; protected $_quizId = 0; protected $_sort = 0; protected $_title = ''; protected $_question = ''; protected $_correctMsg = ''; protected $_incorrectMsg = ''; protected $_answerType = 'single'; protected $_correctSameText = false; protected $_tipEnabled = false; protected $_tipMsg = ''; protected $_points = LEARNDASH_LMS_DEFAULT_QUESTION_POINTS; protected $_showPointsInBox = false; //0.19 protected $_answerPointsActivated = false; protected $_answerData = null; //0.23 protected $_categoryId = 0; //0.24 protected $_categoryName = ''; //0.25 protected $_answerPointsDiffModusActivated = false; protected $_disableCorrect = false; //0.27 protected $_matrixSortAnswerCriteriaWidth = 20; public function setId( $_id ) { $this->_id = (int) $_id; return $this; } public function getId() { return $this->_id; } public function setQuestionPostId( $question_post_id = 0 ) { $this->_questionPostId = absint( $question_post_id ); } public function getQuestionPostId() { return $this->_questionPostId; } public function setQuizId( $_quizId ) { $this->_quizId = (int) $_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setSort( $_sort ) { $this->_sort = (int) $_sort; return $this; } public function getSort() { return $this->_sort; } public function setTitle( $_title ) { $this->_title = (string) $_title; return $this; } public function getTitle() { return $this->_title; } public function setQuestion( $_question ) { $this->_question = (string) $_question; return $this; } public function getQuestion() { return $this->_question; } public function setCorrectMsg( $_correctMsg ) { $this->_correctMsg = (string) $_correctMsg; return $this; } public function getCorrectMsg() { return $this->_correctMsg; } public function setIncorrectMsg( $_incorrectMsg ) { $this->_incorrectMsg = (string) $_incorrectMsg; return $this; } public function getIncorrectMsg() { if ( $this->_correctSameText == true ) return $this->_correctMsg; else return $this->_incorrectMsg; } public function setAnswerType( $_answerType ) { $this->_answerType = (string) $_answerType; return $this; } public function getAnswerType() { return $this->_answerType; } public function setCorrectSameText( $_correctSameText ) { $this->_correctSameText = (bool) $_correctSameText; return $this; } public function isCorrectSameText() { return $this->_correctSameText; } public function setTipEnabled( $_tipEnabled ) { $this->_tipEnabled = (bool) $_tipEnabled; return $this; } public function isTipEnabled() { return $this->_tipEnabled; } public function setTipMsg( $_tipMsg ) { $this->_tipMsg = (string) $_tipMsg; return $this; } public function getTipMsg() { return $this->_tipMsg; } public function setPoints( $_points ) { $this->_points = (int) $_points; return $this; } public function getPoints() { return $this->_points; } public function setShowPointsInBox( $_showPointsInBox ) { $this->_showPointsInBox = (bool) $_showPointsInBox; return $this; } public function isShowPointsInBox() { return $this->_showPointsInBox; } public function setAnswerPointsActivated( $_answerPointsActivated ) { $this->_answerPointsActivated = (bool) $_answerPointsActivated; return $this; } public function isAnswerPointsActivated() { return $this->_answerPointsActivated; } public function setAnswerData( $_answerData ) { $this->_answerData = $_answerData; return $this; } public function getAnswerData( $serialize = false ) { global $wpdb; if ( ! is_null( $this->_answerData ) ) { if ( ! is_array( $this->_answerData ) ) { $answerData = @maybe_unserialize( $this->_answerData ); if ( false === $answerData ) { $answerData = learndash_recount_serialized_bytes( $this->_answerData ); if ( false !== $answerData ) { $answerData = @maybe_unserialize( $answerData ); if ( false === $answerData ) { return null; } } } if ( ( ! empty( $answerData ) ) && ( is_array( $answerData ) ) ) { $changes = false; foreach ( $answerData as $a_idx => $answer ) { if ( ! is_a( $answer, 'WpProQuiz_Model_AnswerTypes' ) ) { $answer_model = learndash_cast_WpProQuiz_Model_AnswerTypes( $answer, 'WpProQuiz_Model_AnswerTypes' ); if ( ! is_a( $answer_model, 'WpProQuiz_Model_AnswerTypes' ) ) { continue; } $changes = true; $answerData[ $a_idx ] = $answer_model; } } if ( true === $changes ) { $wpdb->update( LDLMS_DB::get_table_name( 'quiz_question' ), array( 'answer_data' => serialize( $answerData ), ), array( 'id' => $this->_id, ), array( '%s' ), array( '%d' ) ); } } $this->_answerData = $answerData; } } /* if ( $this->_answerData === null ) { return null; } if ( is_array( $this->_answerData ) || $this->_answerData instanceof WpProQuiz_Model_AnswerTypes ) { if ( $serialize ) { return @serialize( $this->_answerData ); } } else { if ( ! $serialize ) { if ( WpProQuiz_Helper_Until::saveUnserialize( $this->_answerData, $into ) === false ) { return null; } $this->_answerData = $into; } } */ if ( $serialize ) { return @serialize( $this->_answerData ); } else { return $this->_answerData; } } public function setCategoryId( $_categoryId ) { $this->_categoryId = (int) $_categoryId; return $this; } public function getCategoryId() { return $this->_categoryId; } public function setCategoryName( $_categoryName ) { $this->_categoryName = (string) $_categoryName; return $this; } public function getCategoryName() { return $this->_categoryName; } public function setAnswerPointsDiffModusActivated( $_answerPointsDiffModusActivated ) { $this->_answerPointsDiffModusActivated = (bool) $_answerPointsDiffModusActivated; return $this; } public function isAnswerPointsDiffModusActivated() { return $this->_answerPointsDiffModusActivated; } public function setDisableCorrect( $_disableCorrect ) { $this->_disableCorrect = (bool) $_disableCorrect; return $this; } public function isDisableCorrect() { return $this->_disableCorrect; } public function setMatrixSortAnswerCriteriaWidth( $_matrixSortAnswerCriteriaWidth ) { $this->_matrixSortAnswerCriteriaWidth = (int) $_matrixSortAnswerCriteriaWidth; return $this; } public function getMatrixSortAnswerCriteriaWidth() { return $this->_matrixSortAnswerCriteriaWidth; } public function get_object_as_array() { $object_vars = array( '_id' => $this->getId(), '_quizId' => $this->getQuizId(), '_sort' => $this->getSort(), '_title' => $this->getTitle(), '_question' => $this->getQuestion(), '_correctMsg' => $this->getCorrectMsg(), '_incorrectMsg' => $this->getIncorrectMsg(), '_correctSameText' => $this->isCorrectSameText(), '_tipEnabled' => $this->isTipEnabled(), '_tipMsg' => $this->getTipMsg(), '_points' => $this->getPoints(), '_showPointsInBox' => $this->isShowPointsInBox(), '_answerPointsActivated' => $this->isAnswerPointsActivated(), '_answerType' => $this->getAnswerType(), '_answerData' => $this->getAnswerData(), '_answerPointsDiffModusActivated' => $this->isAnswerPointsDiffModusActivatedfalse(), '_disableCorrect' => $this->isDisableCorrect(), '_matrixSortAnswerCriteriaWidth' => $this->getMatrixSortAnswerCriteriaWidth(), ); return $object_vars; } public function set_array_to_object( $array_vars = array() ) { foreach( $array_vars as $key => $value ) { switch( $key ) { case '_quizId': $this->setQuizId( $value ); break; case '_sort': $this->setSort( $value ); break; case '_title': $this->setTitle( $value ); break; case '_question': $this->setQuestion( $value ); break; case '_correctMsg': $this->setCorrectMsg( $value ); break; case '_incorrectMsg': $this->setIncorrectMsg( $value ); break; case '_answerType': $this->setAnswerType( $value ); break; case '_answerData': if ( is_array( $value ) ) { $answer_import_array = array(); foreach( $value as $answer_item ) { if ( is_array( $answer_item ) ) { $answer_import = new WpProQuiz_Model_AnswerTypes(); $answer_import->set_array_to_object( $answer_item ); $answer_import_array[] = $answer_import; } else if ( is_a($answer_item, 'WpProQuiz_Model_AnswerTypes' ) ) { $answer_import_array[] = $answer_item; } } //if ( !empty( $answer_import_array ) ) { $this->setAnswerData( $answer_import_array ); //} } break; case '_correctSameText': $this->setCorrectSameText( $value ); break; case '_tipEnabled': $this->setTipEnabled( $value ); break; case '_tipMsg': $this->setTipMsg( $value ); break; case '_points': $this->setPoints( $value ); break; case '_showPointsInBox': $this->setShowPointsInBox( $value ); break; case '_answerPointsActivated': $this->setAnswerPointsActivated( $value ); break; case '_categoryId': $this->setCategoryId( $value ); break; case '_categoryName': $this->setCategoryName( $value ); break; case '_answerPointsDiffModusActivated': $this->setAnswerPointsDiffModusActivated( $value ); break; case '_disableCorrect': $this->setDisableCorrect( $value ); break; case '_matrixSortAnswerCriteriaWidth': $this->setMatrixSortAnswerCriteriaWidth( $value ); break; default: break; } } } } lib/model/WpProQuiz_Model_TemplateMapper.php 0000666 00000003642 15214236625 0015202 0 ustar 00 <?php class WpProQuiz_Model_TemplateMapper extends WpProQuiz_Model_Mapper { /** * @param WpProQuiz_Model_Template $template */ public function save($template) { $this->_wpdb->replace($this->_tableTemplate, array( 'template_id' => $template->getTemplateId(), 'name' => $template->getName(), 'type' => $template->getType(), 'data' => @serialize($template->getData()) ), array('%d', '%s', '%d', '%s')); $template->setTemplateId($this->getInsertId()); return $template; } public function updateName($templateId, $name) { return $this->_wpdb->update($this->_tableTemplate, array( 'name' => $name ), array( 'template_id' => $templateId ), array('%s'), array('%d')); } public function delete($templateId) { return $this->_wpdb->delete($this->_tableTemplate, array('template_id' => $templateId), array('%d')); } public function fetchAll($type, $loadData = true) { $r = array(); $result = $this->_wpdb->get_results($this->_wpdb->prepare( "SELECT * FROM {$this->_tableTemplate} WHERE type = %d AND name != '' ORDER BY name ASC" , $type), ARRAY_A); foreach($result as $row) { $data = $row['data']; unset($row['data']); $template = new WpProQuiz_Model_Template($row); if($loadData && WpProQuiz_Helper_Until::saveUnserialize($data, $into)) { $template->setData($into); } $r[] = $template; } return $r; } public function fetchById($templateId, $loadData = true) { $row = $this->_wpdb->get_row($this->_wpdb->prepare( "SELECT * FROM {$this->_tableTemplate} WHERE template_id = %d " , $templateId), ARRAY_A); if($row !== null) { $data = $row['data']; unset($row['data']); $template = new WpProQuiz_Model_Template($row); if($loadData && WpProQuiz_Helper_Until::saveUnserialize($data, $into)) { $template->setData($into); } return $template; } return new WpProQuiz_Model_Template(); } } lib/model/WpProQuiz_Model_PrerequisiteMapper.php 0000666 00000004755 15214236625 0016116 0 ustar 00 <?php class WpProQuiz_Model_PrerequisiteMapper extends WpProQuiz_Model_Mapper { public function delete($prerequisiteQuizId) { global $wpdb; return $wpdb->delete( $this->_tablePrerequisite, array('prerequisite_quiz_id' => $prerequisiteQuizId), array('%d') ); } public function isQuizId($quizId) { return $this->_wpdb->get_var( $this->_wpdb->prepare("SELECT (quiz_id) FROM {$this->_tablePrerequisite} WHERE quiz_id = %d", $quizId) ); } public function fetchQuizIds($prerequisiteQuizId) { $sql_str = $this->_wpdb->prepare( "SELECT quiz_id FROM {$this->_tablePrerequisite} WHERE prerequisite_quiz_id = %d", $prerequisiteQuizId); $quiz_pro_ids = $this->_wpdb->get_col( $sql_str ); if ( ! empty( $quiz_pro_ids ) ) { $sql_str = "SELECT postmeta.meta_value as quiz_pro_id FROM {$this->_wpdb->posts} AS posts INNER JOIN {$this->_wpdb->postmeta} as postmeta ON posts.ID = postmeta.post_id WHERE posts.post_type='". learndash_get_post_type_slug( 'quiz' ) . "' AND posts.post_status = 'publish' AND postmeta.meta_key='quiz_pro_id' AND postmeta.meta_value IN ( ". implode( ',', $quiz_pro_ids ) . " )"; $quiz_pro_ids = $this->_wpdb->get_col( $sql_str ); if ( ! empty( $quiz_pro_ids ) ) { $quiz_pro_ids = array_map( 'intval', $quiz_pro_ids ); $quiz_pro_ids = array_unique( $quiz_pro_ids ); } } return ( array ) $quiz_pro_ids; } public function save($prerequisiteQuizId, $quiz_ids) { foreach($quiz_ids as $quiz_id) { $this->_wpdb->insert($this->_tablePrerequisite, array( 'prerequisite_quiz_id' => $prerequisiteQuizId, 'quiz_id' => $quiz_id ), array('%d', '%d')); } } public function getNoPrerequisite($prerequisiteQuizId, $userId) { if ( ( defined( 'LEARNDASH_QUIZ_PREREQUISITE_ALT' ) ) && ( LEARNDASH_QUIZ_PREREQUISITE_ALT === true ) ) { $sql_str = $this->_wpdb->prepare( "SELECT p.quiz_id FROM {$this->_tablePrerequisite} AS p WHERE p.prerequisite_quiz_id = %d", $prerequisiteQuizId ); $prereq_quiz_ids = $this->_wpdb->get_col( $sql_str ); return $prereq_quiz_ids; } else { return $this->_wpdb->get_col( $this->_wpdb->prepare( "SELECT p.quiz_id FROM {$this->_tablePrerequisite} AS p LEFT JOIN {$this->_tableStatisticRef} AS s ON ( s.quiz_id = p.quiz_id AND s.user_id = %d ) WHERE s.user_id IS NULL AND p.prerequisite_quiz_id = %d GROUP BY p.quiz_id", $userId, $prerequisiteQuizId) ); } } } lib/model/WpProQuiz_Model_CategoryMapper.php 0000666 00000007527 15214236625 0015212 0 ustar 00 <?php class WpProQuiz_Model_CategoryMapper extends WpProQuiz_Model_Mapper { public function fetchAll() { $r = array(); $results = $this->_wpdb->get_results("SELECT * FROM {$this->_tableCategory}", ARRAY_A); foreach ($results as $row) { $r[] = new WpProQuiz_Model_Category($row); } return $r; } public function fetchByQuiz( $quizId ) { $r = array(); if ( is_a( $quizId, 'WpProQuiz_Model_Quiz' ) ) { $quiz = $quizId; $quizId = $quiz->getId(); if ( empty( $quiz_post_id ) ) { $quiz_post_id = $quiz->getPostId(); } } if ( ( ! empty( $quiz_post_id ) ) && ( LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Builder', 'enabled' ) === 'yes' ) && ( true === is_data_upgrade_quiz_questions_updated() ) ) { $ld_quiz_questions_object = LDLMS_Factory_Post::quiz_questions( intval( $quiz_post_id ) ); if ( $ld_quiz_questions_object ) { $quiz_questions = $ld_quiz_questions_object->get_questions(); if ( ! empty( $quiz_questions ) ) { $cat_sql_str = 'SELECT c.* FROM ' . $this->_tableCategory . ' AS c RIGHT JOIN ' . $this->_tableQuestion . ' AS q ON c.category_id = q.category_id WHERE q.id IN ('. implode( ',', $quiz_questions ) . ') GROUP BY q.category_id ORDER BY c.category_name'; $results = $this->_wpdb->get_results( $cat_sql_str, ARRAY_A ); } } } else { $results = $this->_wpdb->get_results($this->_wpdb->prepare(' SELECT c.* FROM '.$this->_tableCategory.' AS c RIGHT JOIN '.$this->_tableQuestion.' AS q ON c.category_id = q.category_id WHERE q.quiz_id = %d GROUP BY q.category_id ORDER BY c.category_name ', $quizId), ARRAY_A); } foreach($results as $row) { $r[] = new WpProQuiz_Model_Category($row); } return $r; } public function save(WpProQuiz_Model_Category $category) { $data = array('category_name' => $category->getCategoryName()); $format = array('%s'); if($category->getCategoryId() == 0) { $this->_wpdb->insert($this->_tableCategory, $data, $format); $category->setCategoryId($this->_wpdb->insert_id); } else { $this->_wpdb->update( $this->_tableCategory, $data, array('category_id' => $category->getCategoryId()), $format, array('%d')); } return $category; } public function updateCatgoryName($categoryId, $name) { return $this->_wpdb->update( $this->_tableCategory, array( 'category_name' => $name ), array( 'category_id' => $categoryId ), array('%s'), array('%d') ); } public function delete($categoryId) { $this->_wpdb->update($this->_tableQuestion, array('category_id' => 0), array('category_id' => $categoryId), array('%d'), array('%d')); return $this->_wpdb->delete($this->_tableCategory, array('category_id' => $categoryId), array('%d')); } public function getCategoryArrayForImport() { $r = array(); $results = $this->_wpdb->get_results("SELECT * FROM {$this->_tableCategory}", ARRAY_A); foreach ($results as $row) { $r[strtolower($row['category_name'])] = (int)$row['category_id']; } return $r; } public function fetchById($categoryId, $loadData = true) { $row = $this->_wpdb->get_row( $this->_wpdb->prepare( "SELECT * FROM {$this->_tableCategory} WHERE category_id = %d ", $categoryId ), ARRAY_A ); if ( $row !== null ) { $category = new WpProQuiz_Model_Category( $row ); return $category; } return new WpProQuiz_Model_Category(); } public function fetchByName( $categoryName = '' ) { if ( ! empty( $categoryName ) ) { $row = $this->_wpdb->get_row( $this->_wpdb->prepare( "SELECT * FROM {$this->_tableCategory} WHERE category_name = %s ", $categoryName ), ARRAY_A ); if ( $row !== null ) { $category = new WpProQuiz_Model_Category( $row ); return $category; } } return new WpProQuiz_Model_Category(); } } lib/model/WpProQuiz_Model_Model.php 0000666 00000002470 15214236625 0013320 0 ustar 00 <?php class WpProQuiz_Model_Model { /** * @var WpProQuiz_Model_QuizMapper */ protected $_mapper = null; public function __construct($array = null) { $this->setModelData($array); } public function setModelData($array) { if($array != null) { // foreach($array as $k => $v) { // if(strpos($k, '_') !== false) { // // $k = str_replace(' ', '', ucwords(str_replace('_', ' ', $k))); // $k = implode('', array_map('ucfirst', explode('_', $k))); // } else { // $k = ucfirst($k); // } // // $this->{'set'.ucfirst($k)}($v); // $this->{'set'.$k}($v); // } //3,4x faster $n = explode(' ', implode('', array_map('ucfirst', explode('_', implode(' _', array_keys($array)))))); $a = array_combine($n, $array); if (isset($a['Id'])) { $this->setId($a['Id']); } foreach($a as $k => $v) { $this->{'set'.$k}($v); } } } public function __call($name, $args) { } /** * * @return WpProQuiz_Model_QuizMapper */ public function getMapper() { if($this->_mapper === null) { $this->_mapper = new WpProQuiz_Model_QuizMapper(); } return $this->_mapper; } /** * @param WpProQuiz_Model_QuizMapper $mapper * @return WpProQuiz_Model_Model */ public function setMapper($mapper) { $this->_mapper = $mapper; return $this; } } lib/model/WpProQuiz_Model_StatisticHistory.php 0000666 00000005341 15214236625 0015611 0 ustar 00 <?php class WpProQuiz_Model_StatisticHistory extends WpProQuiz_Model_Model { protected $_userId = 0; protected $_userName = ''; protected $_statisticRefId = 0; protected $_quizId = 0; protected $_createTime = 0; protected $_correctCount = 0; protected $_incorrectCount = 0; protected $_points = 0; protected $_result = 0; protected $_formatTime = ''; protected $_formatCorrect = ''; protected $_formatIncorrect = ''; protected $_gPoints = 0; public function setUserId($_userId) { $this->_userId = (int)$_userId; return $this; } public function getUserId() { return $this->_userId; } public function setUserName($_userName) { $this->_userName = (string)$_userName; return $this; } public function getUserName() { return $this->_userName; } public function setStatisticRefId($_statisticRefId) { $this->_statisticRefId = (int)$_statisticRefId; return $this; } public function getStatisticRefId() { return $this->_statisticRefId; } public function setQuizId($_quizId) { $this->_quizId = (int)$_quizId; return $this; } public function getQuizId() { return $this->_quizId; } public function setCreateTime($_createTime) { $this->_createTime = (int)$_createTime; return $this; } public function getCreateTime() { return $this->_createTime; } public function setCorrectCount($_correctCount) { $this->_correctCount = (int)$_correctCount; return $this; } public function getCorrectCount() { return $this->_correctCount; } public function setIncorrectCount($_incorrectCount) { $this->_incorrectCount = (int)$_incorrectCount; return $this; } public function getIncorrectCount() { return $this->_incorrectCount; } public function setPoints($_points) { $this->_points = (int)$_points; return $this; } public function getPoints() { return $this->_points; } public function setResult($_result) { $this->_result = (float)$_result; return $this; } public function getResult() { return $this->_result; } public function setFormatTime($_formatTime) { $this->_formatTime = (string)$_formatTime; return $this; } public function getFormatTime() { return $this->_formatTime; } public function setFormatCorrect($_formatCorrect) { $this->_formatCorrect = (string)$_formatCorrect; return $this; } public function getFormatCorrect() { return $this->_formatCorrect; } public function setFormatIncorrect($_formatIncorrect) { $this->_formatIncorrect = (string)$_formatIncorrect; return $this; } public function getFormatIncorrect() { return $this->_formatIncorrect; } public function setGPoints($_gPoints) { $this->_gPoints = (int)$_gPoints; return $this; } public function getGPoints() { return $this->_gPoints; } } lib/model/WpProQuiz_Model_FormMapper.php 0000666 00000003403 15214236625 0014325 0 ustar 00 <?php class WpProQuiz_Model_FormMapper extends WpProQuiz_Model_Mapper { public function deleteForm($formIds, $quizId) { return $this->_wpdb->query( $this->_wpdb->prepare(' DELETE FROM '.$this->_tableForm.' WHERE form_id IN('.implode(', ', array_map('intval', (array)$formIds)).') AND quiz_id = %d ', $quizId) ); } /** * @param WpProQuiz_Model_Form $forms */ public function update($forms) { $values = $values2 = array(); foreach($forms as $form) { /* @var $form WpProQuiz_Model_Form */ $data = array( $form->getFormId(), $form->getQuizId(), $form->getFieldname(), $form->getType(), (int)$form->isRequired(), $form->getSort() ); if($form->getData() === null) { $values[] = '('. $this->_wpdb->prepare('%d, %d, %s, %d, %d, %d', $data).')'; } else { $data[] = @json_encode($form->getData()); $values2[] = '('. $this->_wpdb->prepare('%d, %d, %s, %d, %d, %d, %s', $data).')'; } } if(!empty($values)) { $this->_wpdb->query(' REPLACE INTO '.$this->_tableForm.' (form_id, quiz_id, fieldname, type, required, sort) VALUES '.implode(', ', $values).' '); } if(!empty($values2)) { $this->_wpdb->query(' REPLACE INTO '.$this->_tableForm.' (form_id, quiz_id, fieldname, type, required, sort, data) VALUES '.implode(', ', $values2).' '); } } public function fetch($quizId) { $results = $this->_wpdb->get_results( $this->_wpdb->prepare(' SELECT * FROM '.$this->_tableForm.' WHERE quiz_id = %d ORDER BY sort', $quizId), ARRAY_A); $a = array(); foreach($results as $row) { $row['data'] = $row['data'] === null ? null : @json_decode($row['data'], true); $a[] = new WpProQuiz_Model_Form($row); } return $a; } } lib/model/WpProQuiz_Model_StatisticUserMapper.php 0000666 00000003300 15214236625 0016224 0 ustar 00 <?php class WpProQuiz_Model_StatisticUserMapper extends WpProQuiz_Model_Mapper { public function fetchUserStatistic($refIdUserId, $quizId, $avg = false) { $where = $avg ? 'sf.user_id = %d' : 'sf.statistic_ref_id = %d'; $result = $this->_wpdb->get_results( $this->_wpdb->prepare( "SELECT SUM(s.correct_count) AS correct_count, SUM(s.incorrect_count) AS incorrect_count, SUM(s.hint_count) AS hint_count, SUM(s.points) AS points, AVG(s.question_time) AS question_time, s.answer_data AS statistic_answer_data, q.id AS question_id, q.". apply_filters('ld_fetchUserStatistic_question_title', 'question')." AS question_name, q.answer_data AS question_answer_data, q.answer_type, SUM(q.points * (s.correct_count + s.incorrect_count)) AS g_points, c.category_id, c.category_name FROM {$this->_tableStatisticRef} AS sf INNER JOIN {$this->_tableStatistic} AS s ON(s.statistic_ref_id = sf.statistic_ref_id) INNER JOIN {$this->_tableQuestion} AS q ON(q.id = s.question_id) LEFT JOIN {$this->_tableCategory} AS c ON(c.category_id = q.category_id) WHERE {$where} AND sf.quiz_id = %d GROUP BY s.question_id ORDER BY ISNULL(c.category_name), c.category_name, q.sort", $refIdUserId, $quizId), ARRAY_A); $r = array(); foreach($result as $row) { if(!$avg) { if($row['statistic_answer_data'] !== null) { $row['statistic_answer_data'] = json_decode($row['statistic_answer_data'], true); } } else { $row['statistic_answer_data'] = null; $row['question_answer_data'] = null; } $r[] = new WpProQuiz_Model_StatisticUser($row); } return $r; } } lib/plugin/WpProQuiz_Plugin_BpAchievementsV2.php 0000666 00000003237 15214236625 0015763 0 ustar 00 <?php class WpProQuiz_Plugin_BpAchievementsV2 { public function __construct() { add_filter('dpa_get_addedit_action_descriptions_category_name', array($this, 'setCategoryName'), 10, 2); add_action('wp_pro_quiz_completed_quiz', array($this, 'quizFinished')); } public function setCategoryName( $category_name, $category ) { $other = 'Other'; if (__($other, 'dpa') == $category_name && 'Wp-Pro-Quiz' == $category) return 'Wp-Pro-Quiz'; else return $category_name; } public function quizFinished() { do_action('wp_pro_quiz_quiz_finished'); } public static function install() { global $wpdb; if($wpdb->get_var("SHOW TABLES LIKE '{$wpdb->prefix}achievements_actions'") === null) return false; $actions = array( array( 'category' => 'Wp-Pro-Quiz', 'name' => 'wp_pro_quiz_quiz_finished', 'description' => sprintf( esc_html_x('The user completed a %s.', 'The user completed a quiz.', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ) ) ); foreach($actions as $action) { if($wpdb->get_var("SELECT id FROM {$wpdb->prefix}achievements_actions WHERE name = 'wp_pro_quiz_quiz_finished'") === null) $wpdb->insert($wpdb->prefix.'achievements_actions', $action); } return true; } public static function deinstall() { global $wpdb; if($wpdb->get_var("SHOW TABLES LIKE '{$wpdb->prefix}achievements_actions'") === null) return false; $wpdb->delete($wpdb->prefix.'achievements_actions', array('name' => 'wp_pro_quiz_quiz_finished')); } } function dpa_handle_action_wp_pro_quiz_quiz_finished() { $func_get_args = func_get_args(); dpa_handle_action('wp_pro_quiz_quiz_finished', $func_get_args); } lib/plugin/WpProQuiz_Plugin_BpAchievementsV3.php 0000666 00000003320 15214236625 0015755 0 ustar 00 <?php class WpProQuiz_Plugin_BpAchievementsV3 extends DPA_Extension { public function __construct() { $this->actions = array( 'wp_pro_quiz_completed_quiz' => sprintf( esc_html_x('The user completed a %s.', 'The user completed a quiz.', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ), 'wp_pro_quiz_completed_quiz_100_percent' => sprintf( esc_html_x('The user completed a %s with 100 percent.', 'The user completed a quiz with 100 percent.', 'learndash'), learndash_get_custom_label_lower( 'quiz' )), ); $this->contributors = array( array( 'name' => 'Julius Fischer', 'gravatar_url' => 'http://gravatar.com/avatar/c3736cd18c273f32569726c93f76244d', 'profile_url' => 'http://profiles.wordpress.org/xeno010', ) ); $this->description = sprintf( esc_html_x('A powerful and beautiful %s plugin for WordPress.', 'A powerful and beautiful quiz plugin for WordPress.', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); $this->id = 'wp-pro-quiz'; $this->image_url = WPPROQUIZ_URL.'/img/wp_pro_quiz.jpg'; $this->name = esc_html__( 'WP-Pro-Quiz', 'learndash' ); //$this->rss_url = ''; $this->small_image_url = WPPROQUIZ_URL.'/img/wp_pro_quiz_small.jpg'; $this->version = 5; $this->wporg_url = 'http://wordpress.org/extend/plugins/wp-pro-quiz/'; } public function do_update($current_version) { $this->insertTerm(); } public function insertTerm() { $taxId = dpa_get_event_tax_id(); foreach ($this->actions as $actionName => $desc) { $e = term_exists($actionName, $taxId); if($e === 0 || $e === null) { wp_insert_term($actionName, $taxId, array('description' => $desc)); } } } } lib/controller/WpProQuiz_Controller_Toplist.php 0000666 00000026411 15214236625 0016065 0 ustar 00 <?php class WpProQuiz_Controller_Toplist extends WpProQuiz_Controller_Controller { public function route() { $quizId = $_GET['id']; $action = isset($_GET['action']) ? $_GET['action'] : 'show'; switch($action) { case 'load_toplist': $this->loadToplist($quizId); break; case 'show': default: $this->showAdminToplist($quizId); break; } } private function loadToplist($quizId) { if(!current_user_can('wpProQuiz_toplist_edit')) { echo json_encode(array()); return; } $toplistMapper = new WpProQuiz_Model_ToplistMapper(); $j = array('data' => array()); $limit = (int)$this->_post['limit']; $start = $limit * ($this->_post['page'] - 1); $isNav = isset($this->_post['nav']); if(isset($this->_post['a'])) { switch ($this->_post['a']) { case 'deleteAll': $toplistMapper->delete($quizId); break; case 'delete': if(!empty($this->_post['toplistIds'])) $toplistMapper->delete($quizId, $this->_post['toplistIds']); break; } $start = 0; $isNav = true; } $toplist = $toplistMapper->fetch($quizId, $limit, $this->_post['sort'], $start); foreach($toplist as $tp) { $j['data'][] = array( 'id' => $tp->getToplistId(), 'name' => $tp->getName(), 'email' => $tp->getEmail(), 'type' => $tp->getUserId() ? 'R' : 'UR', 'date' => WpProQuiz_Helper_Until::convertTime( $tp->getDate(), LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'toplist_time_format' ) //get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A') ), 'points' => $tp->getPoints(), 'result' => $tp->getResult() ); } if($isNav) { $count = $toplistMapper->count($quizId); $pages = ceil($count / $limit); $j['nav'] = array( 'count' => $count, 'pages' => $pages ? $pages : 1 ); } echo json_encode($j); } private function editAdminToplist() { $toplistId = $this->_post['toplistId']; $username = trim($this->_post['name']); $email = trim($this->_post['email']); if(empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) { return array('error' => esc_html__('No name or e-mail entered.', 'learndash')); } } private function showAdminToplist($quizId) { if(!current_user_can('wpProQuiz_toplist_edit')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $view = new WpProQuiz_View_AdminToplist(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $quiz = $quizMapper->fetch($quizId); $view->quiz = $quiz; $view->show(); } public function getAddToplist(WpProQuiz_Model_Quiz $quiz) { $userId = get_current_user_id(); if(!$quiz->isToplistActivated()) return null; $data = array( 'userId' => $userId, 'token' => wp_create_nonce('wpProQuiz_toplist'), 'canAdd' => $this->preCheck($quiz->getToplistDataAddPermissions(), $userId), ); if($quiz->isToplistDataCaptcha() && $userId == 0) { $captcha = WpProQuiz_Helper_Captcha::getInstance(); if($captcha->isSupported()) { $data['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL.'/'.$captcha->createImage(); $data['captcha']['code'] = $captcha->getPrefix(); } } return $data; } public function addInToplist() { if ( is_user_logged_in() ) { $user_id = get_current_user_id(); } else { $user_id = 0; } $include_admin_in_reports = true; if ( !empty( $user_id ) ) { if ( learndash_is_admin_user( $user_id ) ) { $include_admin_in_reports = LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Section_General_Admin_User', 'reports_include_admin_users' ); if ( $include_admin_in_reports == 'yes' ) $include_admin_in_reports = true; else $include_admin_in_reports = false; } else { $include_admin_in_reports = true; } // For logged in users to allow an override filter. $include_admin_in_reports = apply_filters( 'learndash_quiz_add_toplist_bypass', $include_admin_in_reports, $user_id, $this->_post ); } if ( $include_admin_in_reports ) { $quizId = isset($this->_post['quizId']) ? $this->_post['quizId'] : 0; $prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : ''; $quizMapper = new WpProQuiz_Model_QuizMapper(); $quiz = $quizMapper->fetch($quizId); $r = $this->handleAddInToplist($quiz); if($quiz->isToplistActivated() && $quiz->isToplistDataCaptcha() && get_current_user_id() == 0) { $captcha = WpProQuiz_Helper_Captcha::getInstance(); if($captcha->isSupported()) { $captcha->remove($prefix); $captcha->cleanup(); if($r !== true) { $r['captcha']['img'] = WPPROQUIZ_CAPTCHA_URL.'/'.$captcha->createImage(); $r['captcha']['code'] = $captcha->getPrefix(); } } } } else { $r = true; } if ( $r === true) { $r = array( 'text' => esc_html__( 'You signed up successfully.', 'learndash' ), 'clear' => true ); } echo json_encode($r); } private function handleAddInToplist(WpProQuiz_Model_Quiz $quiz) { if(!wp_verify_nonce($this->_post['token'], 'wpProQuiz_toplist')) { return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); } //if(!isset($this->_post['points']) || !isset($this->_post['totalPoints'])) { // return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); //} $quizId = $quiz->getId(); $userId = get_current_user_id(); $quiz_post_id = (int)$this->_post['quiz']; //$points = (int)$this->_post['points']; // Added v2.4.3 to validate the comp points with nonce. See ld-quiz-pro.php checkAnswers() for nonce definition logic. //if ( !wp_verify_nonce($this->_post['p_nonce'], 'ld_quiz_pnonce'. $userId .'_'. $quizId .'_'. $quiz_post_id .'_'. 'comp' .'_'. $points) ) { // return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); //} if ( !isset( $this->_post['results']) ) { return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); } $results = $this->_post['results']; if ( !empty( $results ) ) { $total_possible_points = 0; $total_awarded_points = 0; foreach( $results as $r_idx => $result ) { if ( $r_idx == 'comp' ) { $points = intval( $total_awarded_points ); continue; } $points_array = array( 'points' => intval( $result['points'] ), 'correct' => intval( $result['correct'] ), 'possiblePoints' => intval( $result['possiblePoints'] ) ); if ( $points_array['correct'] === false ) $points_array['correct'] = 0; else if ( $points_array['correct'] === true ) $points_array['correct'] = 1; $points_str = maybe_serialize( $points_array ); if ( !wp_verify_nonce( $result['p_nonce'], 'ld_quiz_pnonce'. $userId .'_'. $quizId .'_'. $quiz_post_id .'_'. $r_idx .'_'. $points_str ) ) { $this->_post['results'][$r_idx]['points'] = 0; $this->_post['results'][$r_idx]['correct'] = 0; $this->_post['results'][$r_idx]['possiblePoints'] = 0; } $total_awarded_points += intval( $this->_post['results'][$r_idx]['points'] ); $total_possible_points += intval( $_POST['results'][$r_idx]['possiblePoints'] ); } } //$points = (int)$this->_post['points']; //$totalPoints = (int)$this->_post['totalPoints']; $name = !empty($this->_post['name']) ? trim($this->_post['name']) : ''; $email = !empty($this->_post['email']) ? trim($this->_post['email']) : ''; $ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP); $captchaAnswer = !empty($this->_post['captcha']) ? trim($this->_post['captcha']) : ''; $prefix = !empty($this->_post['prefix']) ? trim($this->_post['prefix']) : ''; $quizMapper = new WpProQuiz_Model_QuizMapper(); $toplistMapper = new WpProQuiz_Model_ToplistMapper(); if($quiz == null || $quiz->getId() == 0 || !$quiz->isToplistActivated()) { return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); } if(!$this->preCheck($quiz->getToplistDataAddPermissions(), $userId)) { return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); } //$numPoints = $quizMapper->sumQuestionPoints($quizId); //$totalPoints = $quizMapper->sumQuestionPoints($quizId); //if($totalPoints > $numPoints || $points > $numPoints) { // return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); //} $clearTime = null; if($quiz->isToplistDataAddMultiple()) { $clearTime = $quiz->getToplistDataAddBlock() * 60; } if($userId > 0) { if($toplistMapper->countUser($quizId, $userId, $clearTime)) { return array('text' => esc_html__('You can not enter again.', 'learndash'), 'clear' => true); } $user = wp_get_current_user(); $email = $user->user_email; $name = $user->display_name; } else { if($toplistMapper->countFree($quizId, $name, $email, $ip, $clearTime)) { return array('text' => esc_html__('You can not enter again.', 'learndash'), 'clear' => true); } if(empty($name) || empty($email) || filter_var($email, FILTER_VALIDATE_EMAIL) === false) { return array('text' => esc_html__('No name or e-mail entered.', 'learndash'), 'clear' => false); } if(strlen($name) > 15) { return array('text' => esc_html__('Your name can not exceed 15 characters.', 'learndash'), 'clear' => false); } if($quiz->isToplistDataCaptcha()) { $captcha = WpProQuiz_Helper_Captcha::getInstance(); if($captcha->isSupported()) { if(!$captcha->check($prefix, $captchaAnswer)) { return array('text' => esc_html__('You entered wrong captcha code.', 'learndash'), 'clear' => false); } } } } $toplist = new WpProQuiz_Model_Toplist(); $toplist->setQuizId($quizId) ->setUserId($userId) ->setDate(time()) ->setName($name) ->setEmail($email) ->setPoints($points) ->setResult(round($points / $total_possible_points * 100, 2)) ->setIp($ip); $toplistMapper->save($toplist); return true; } private function preCheck($type, $userId) { switch($type) { case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ALL: return true; case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_ANONYM: return $userId == 0; case WpProQuiz_Model_Quiz::QUIZ_TOPLIST_TYPE_ONLY_USER: return $userId > 0; } return false; } public function showFrontToplist() { $quizIds = empty($this->_post['quizIds']) ? array() : array_unique((array)$this->_post['quizIds']); $toplistMapper = new WpProQuiz_Model_ToplistMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $r = array(); $j = array(); foreach($quizIds as $quizId) { $quiz = $quizMapper->fetch($quizId); if($quiz == null || $quiz->getId() == 0) continue; $toplist = $toplistMapper->fetch($quizId, $quiz->getToplistDataShowLimit(), $quiz->getToplistDataSort()); foreach($toplist as $tp) { $j[$quizId][] = array( 'name' => $tp->getName(), 'date' => WpProQuiz_Helper_Until::convertTime( $tp->getDate(), LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'toplist_time_format' ) //get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A') ), 'points' => $tp->getPoints(), 'result' => $tp->getResult() ); } } echo json_encode($j); } } lib/controller/WpProQuiz_Controller_Quiz.php 0000666 00000124436 15214236625 0015365 0 ustar 00 <?php class WpProQuiz_Controller_Quiz extends WpProQuiz_Controller_Controller { private $view; public function route($get = null, $post = null) { if(empty($get)) $get = $_GET; $action = isset($get['action']) ? $get['action'] : 'show'; switch ($action) { case 'show': $this->showAction(); break; case 'addEdit': $this->addEditQuiz($get, $post); break; case 'getEdit': return $this->getEditQuiz($get, $post); break; case 'addUpdateQuiz': return $this->addUpdateQuiz($get, $post); break; // case 'add': // $this->createAction(); // break; // case 'edit': // if(isset($_GET['id'])) // $this->editAction($get['id']); // break; case 'delete': if( isset( $get['id'] ) ) $this->deleteAction( intval( $get['id'] ) ); break; case 'reset_lock': if( isset($get['id'] ) ) $this->resetLock( intval( $get['id'] ) ); break; } } private function addEditQuiz($get = null, $post = null) { if(empty($get)) $get = $_GET; if(!empty($post)) $this->_post = $post; $quizId = isset($get['quizId']) ? (int)$get['quizId'] : 0; if($quizId) { if(!current_user_can('wpProQuiz_edit_quiz')) { wp_die(__('You do not have sufficient permissions to access this page.')); } } else { if(!current_user_can('wpProQuiz_add_quiz')) { wp_die(__('You do not have sufficient permissions to access this page.')); } } $prerequisiteMapper = new WpProQuiz_Model_PrerequisiteMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); $quiz = new WpProQuiz_Model_Quiz(); $forms = null; $prerequisiteQuizList = array(); if(!empty($get["post_id"])) { $quiz_post = get_post($get["post_id"]); if ( ( !empty( $quiz_post ) ) && ( is_a( $quiz_post, 'WP_Post' ) ) ) { $this->_post["name"] = $quiz_post->post_title; } } if($quizId && $quizMapper->exists($quizId) == 0) { WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s not found', 'Quiz not found', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ), 'error'); return; } if(isset($this->_post['template']) || (isset($this->_post['templateLoad']) && isset($this->_post['templateLoadId']))) { if(isset($this->_post['template'])) $template = $this->saveTemplate(); else $template = $templateMapper->fetchById($this->_post['templateLoadId']); $data = $template->getData(); if($data !== null) { $quiz = $data['quiz']; $quiz->setId($quizId); $quiz->setName($this->_post["name"]); $quiz->setText("AAZZAAZZ"); $quizMapper->save($quiz); if(empty($quizId) && !empty($get["post_id"])) { learndash_update_setting($get["post_id"], "quiz_pro", $quiz->getId()); } $quizId = $quiz->getId(); $forms = $data['forms']; $prerequisiteQuizList = $data['prerequisiteQuizList']; } } else if(isset($this->_post['form'])) { if(isset($this->_post['resultGradeEnabled'])) { $this->_post['result_text'] = $this->filterResultTextGrade($this->_post); } // Patch to only set Statistics on if post from form save. // LEARNDASH-1434 & LEARNDASH-1481 if ( !isset( $this->_post['statisticsOn'] ) ) { $this->_post['statisticsOn'] = '0'; $this->_post['viewProfileStatistics'] = '0'; } $quiz = new WpProQuiz_Model_Quiz($this->_post); $quiz->setId($quizId); if($this->checkValidit($this->_post)) { //if($quizId) // WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s edited', 'Quiz edited', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )), 'info'); //else // WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s created', 'Quiz created', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )), 'info'); $quiz->setText("AAZZAAZZ"); $quizMapper->save($quiz); if ( empty( $quizId ) && !empty( $get["post_id"] ) ) { learndash_update_setting($get["post_id"], "quiz_pro", $quiz->getId()); } //if ( ( isset( $get["post_id"] ) ) && ( !empty( $get["post_id"] ) ) ) { // if ( isset( $this->_post['viewProfileStatistics'] ) ) { // $quiz->setViewProfileStatistics( true ); // update_post_meta( $get["post_id"], '_viewProfileStatistics', 1 ); // } else { // $quiz->setViewProfileStatistics( false ); // update_post_meta( $get["post_id"], '_viewProfileStatistics', 0 ); // } //} $quizId = $quiz->getId(); $prerequisiteMapper->delete($quizId); if($quiz->isPrerequisite() && !empty($this->_post['prerequisiteList'])) { $prerequisiteMapper->save($quizId, $this->_post['prerequisiteList']); $quizMapper->activateStatitic($this->_post['prerequisiteList'], 1440); } if(!$this->formHandler($quiz->getId(), $this->_post)) { $quiz->setFormActivated(false); $quiz->setText("AAZZAAZZ"); $quizMapper->save($quiz); } $forms = $formMapper->fetch($quizId); $prerequisiteQuizList = $prerequisiteMapper->fetchQuizIds($quizId); } else { //WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s title or %s description are not filled', 'Quiz title or quiz description are not filled', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ))); } } else if($quizId) { $quiz = $quizMapper->fetch($quizId); $forms = $formMapper->fetch($quizId); $prerequisiteQuizList = $prerequisiteMapper->fetchQuizIds($quizId); } $this->view = new WpProQuiz_View_QuizEdit(); $this->view->quiz = $quiz; $this->view->forms = $forms; $this->view->prerequisiteQuizList = $prerequisiteQuizList; $this->view->templates = $templateMapper->fetchAll(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUIZ, false); $this->view->quizList = $quizMapper->fetchAllAsArray(array('id', 'name'), $quizId ? array($quizId) : array()); $this->view->captchaIsInstalled = class_exists('ReallySimpleCaptcha'); $this->view->header = $quizId ? sprintf( esc_html_x('Edit %s', 'Edit quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ) : sprintf( esc_html_x('Create %s', 'Create quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' )); $this->view->show($get); } private function addUpdateQuiz( $get = null, $post = null ) { if( empty( $get ) ) $get = $_GET; if( ! empty( $post ) ) $this->_post = $post; $quizId = isset( $get['quizId'] ) ? (int)$get['quizId'] : 0; if( $quizId ) { if(!current_user_can('wpProQuiz_edit_quiz')) { wp_die(__('You do not have sufficient permissions to access this page.')); } } else { if(!current_user_can('wpProQuiz_add_quiz')) { wp_die(__('You do not have sufficient permissions to access this page.')); } } $prerequisiteMapper = new WpProQuiz_Model_PrerequisiteMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); $quiz = new WpProQuiz_Model_Quiz(); $forms = null; $prerequisiteQuizList = array(); if(!empty($get["post_id"])) { $quiz_post = get_post($get["post_id"]); if ( ( !empty( $quiz_post ) ) && ( is_a( $quiz_post, 'WP_Post' ) ) ) { $this->_post["name"] = $quiz_post->post_title; } } if( $quizId && $quizMapper->exists( $quizId ) == 0 ) { WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s not found', 'Quiz not found', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ), 'error'); return; } if ( ( ( isset( $this->_post['templateSaveList'] ) ) && ( intval( $this->_post['templateSaveList'] ) > 0 ) ) || ( ( isset( $this->_post['templateName'] ) ) && ( ! empty( $this->_post['templateName'] ) ) ) ) { $template = $this->saveTemplate(); } //if ( ( isset( $this->_post['templateName'] ) ) && ( ! empty( $this->_post['templateName'] ) ) ) { // $template = $this->saveTemplate(); //} if( isset( $this->_post['form'] ) ) { if( isset( $this->_post['resultGradeEnabled'] ) ) { $this->_post['result_text'] = $this->filterResultTextGrade( $this->_post ); } // Patch to only set Statistics on if post from form save. // LEARNDASH-1434 & LEARNDASH-1481 if ( !isset( $this->_post['statisticsOn'] ) ) { $this->_post['statisticsOn'] = '0'; $this->_post['viewProfileStatistics'] = '0'; } $quiz = new WpProQuiz_Model_Quiz( $this->_post ); $quiz->setId( $quizId ); if ( ! empty( $get['post_id'] ) ) { $quiz_post = get_post( $get['post_id'] ); if ( ( ! empty( $quiz_post ) ) && ( is_a( $quiz_post, 'WP_Post' ) ) ) { $quiz->setPostId = $quiz_post->ID; } } if( $this->checkValidit( $this->_post ) ) { //if( $quizId ) // WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s edited', 'Quiz edited', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ), 'info'); //else // WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s created', 'Quiz created', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )), 'info'); $quiz->setText("AAZZAAZZ"); $quiz2 = $quizMapper->save($quiz); if ( ( empty( $quizId ) ) && ( isset( $get["post_id"] ) ) && ( !empty( $get["post_id"] ) ) ) { learndash_update_setting($get["post_id"], "quiz_pro", $quiz->getId()); $quiz_id_primary_new = absint( learndash_get_quiz_primary_shared( $quiz->getId(), false ) ); if ( empty( $quiz_id_primary_new ) ) { update_post_meta( $get["post_id"], 'quiz_pro_primary_'. $quiz->getId(), $quiz->getId() ); } } //if ( ( isset( $get["post_id"] ) ) && ( !empty( $get["post_id"] ) ) ) { // if ( isset( $this->_post['viewProfileStatistics'] ) ) { // $quiz->setViewProfileStatistics( true ); // update_post_meta( $get["post_id"], '_viewProfileStatistics', 1 ); // } else { // $quiz->setViewProfileStatistics( false ); // update_post_meta( $get["post_id"], '_viewProfileStatistics', 0 ); // } //} $quizId = $quiz->getId(); $prerequisiteMapper->delete($quizId); if($quiz->isPrerequisite() && !empty($this->_post['prerequisiteList'])) { $prerequisiteMapper->save($quizId, $this->_post['prerequisiteList']); $quizMapper->activateStatitic($this->_post['prerequisiteList'], 1440); } if(!$this->formHandler( $quiz->getId(), $this->_post ) ) { $quiz->setFormActivated( false ); $quiz->setText(" AAZZAAZZ" ); $quizMapper->save( $quiz ); } } else { //WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s title or %s description are not filled', 'Quiz title or quiz description are not filled', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ))); return false; } } } private function getEditQuiz($get = null, $post = null) { if(empty($get)) $get = $_GET; if(!empty($post)) $this->_post = $post; $quizId = isset($get['quizId']) ? (int)$get['quizId'] : 0; //if($quizId) { // if(!current_user_can('wpProQuiz_edit_quiz')) { // wp_die(__('You do not have sufficient permissions to access this page.')); // } //} else { // if(!current_user_can('wpProQuiz_add_quiz')) { // wp_die(__('You do not have sufficient permissions to access this page.')); // } //} $prerequisiteMapper = new WpProQuiz_Model_PrerequisiteMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); $quiz = new WpProQuiz_Model_Quiz(); $forms = null; $prerequisiteQuizList = array(); if(!empty($get["post_id"])) { $quiz_post = get_post($get["post_id"]); if ( ( !empty( $quiz_post ) ) && ( is_a( $quiz_post, 'WP_Post' ) ) ) { $this->_post["name"] = $quiz_post->post_title; } } if($quizId && $quizMapper->exists($quizId) == 0) { WpProQuiz_View_View::admin_notices( esc_html__( 'Missing ProQuiz Associated Settings.', 'learndash' ), 'error' ); $this->view = new WpProQuiz_View_QuizEdit(); $this->view->quiz = $quiz; $this->view->forms = $forms; $this->view->prerequisiteQuizList = $prerequisiteQuizList; $this->view->templates = $templateMapper->fetchAll(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUIZ, false); $this->view->quizList = $quizMapper->fetchAllAsArray(array('id', 'name'), $quizId ? array($quizId) : array()); $this->view->captchaIsInstalled = class_exists('ReallySimpleCaptcha'); return $this->view; } if ( ( isset( $get['templateLoad'] ) ) && ( ! empty( $get['templateLoad'] ) ) && ( isset( $get['templateLoadId'] ) ) && ( ! empty( $get['templateLoadId'] ) ) ) { $template = $templateMapper->fetchById( (int) $get['templateLoadId'] ); if ( ( $template ) && is_a( $template, 'WpProQuiz_Model_Template' ) ) { $data = $template->getData(); if ( $data !== null ) { $quiz = $data['quiz']; $quiz->setId( $quizId ); $quiz->setName($this->_post["name"]); $quiz->setText("AAZZAAZZ"); //$quizMapper->save( $quiz ); //if ( empty( $quizId ) && ! empty( $get["post_id"] ) ) { // learndash_update_setting($get["post_id"], "quiz_pro", $quiz->getId()); //} //$quizId = $quiz->getId(); $forms = $data['forms']; $prerequisiteQuizList = $data['prerequisiteQuizList']; } } } else { $quiz = $quizMapper->fetch($quizId); $forms = $formMapper->fetch($quizId); $prerequisiteQuizList = $prerequisiteMapper->fetchQuizIds($quizId); } $this->view = new WpProQuiz_View_QuizEdit(); $this->view->quiz = $quiz; $this->view->forms = $forms; $this->view->prerequisiteQuizList = $prerequisiteQuizList; $this->view->templates = $templateMapper->fetchAll(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUIZ, false); $this->view->quizList = $quizMapper->fetchAllAsArray(array('id', 'name'), $quizId ? array($quizId) : array()); $this->view->captchaIsInstalled = class_exists('ReallySimpleCaptcha'); $this->view->header = $quizId ? sprintf( esc_html_x('Edit %s', 'Edit quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ) : sprintf( esc_html_x('Create %s', 'Create quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' )); return $this->view; } public function checkLock() { if($userId > 0) { $quizIds = $prerequisiteMapper->getNoPrerequisite($quizId, $userId); } else { $checkIds = $prerequisiteMapper->fetchQuizIds($quizId); if(isset($this->_post['wpProQuiz_result'])) { $r = json_encode($this->_post['wpProQuiz_result'], true); if($r !== null && is_array($r)) { foreach($checkIds as $id) { if(!isset($r[$id]) || !$r[$id]) { $quizIds[] = $id; } } } } else { $quizIds = $checkIds; } } $names = $quizMapper->fetchCol($quizIds, 'name'); } public function isLockQuiz($quizId) { $quizId = (int)$this->_post['quizId']; $userId = get_current_user_id(); $data = array(); if ( learndash_is_admin_user( $userId ) ) { $bypass_course_limits_admin_users = LearnDash_Settings_Section::get_section_setting('LearnDash_Settings_Section_General_Admin_User', 'bypass_course_limits_admin_users' ); if ( $bypass_course_limits_admin_users == 'yes' ) { return $data; } } $lockMapper = new WpProQuiz_Model_LockMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $prerequisiteMapper = new WpProQuiz_Model_PrerequisiteMapper(); $quiz = $quizMapper->fetch($this->_post['quizId']); if($quiz === null || $quiz->getId() <= 0) { return null; } if($this->isPreLockQuiz($quiz)) { $lockIp = $lockMapper->isLock($this->_post['quizId'], $this->getIp(), $userId, WpProQuiz_Model_Lock::TYPE_QUIZ); $lockCookie = false; $cookieTime = $quiz->getQuizRunOnceTime(); if(isset($this->_cookie['wpProQuiz_lock']) && $userId == 0 && $quiz->isQuizRunOnceCookie()) { $cookieJson = json_decode($this->_cookie['wpProQuiz_lock'], true); if($cookieJson !== false) { if(isset($cookieJson[$this->_post['quizId']]) && $cookieJson[$this->_post['quizId']] == $cookieTime) { $lockCookie = true; } } } $data['lock'] = array( 'is' => ($lockIp || $lockCookie), 'pre' => true ); } if($quiz->isPrerequisite()) { $quizIds = array(); if($userId > 0) { $quizIds = $prerequisiteMapper->getNoPrerequisite($quizId, $userId); } else { $checkIds = $prerequisiteMapper->fetchQuizIds($quizId); if(isset($this->_cookie['wpProQuiz_result'])) { $r = json_decode($this->_cookie['wpProQuiz_result'], true); if($r !== null && is_array($r)) { foreach($checkIds as $id) { if(!isset($r[$id]) || !$r[$id]) { $quizIds[] = $id; } } } } else { $quizIds = $checkIds; } } if(!empty($quizIds)) { $post_quiz_ids = array(); foreach( $quizIds as $pro_quiz_id ) { $post_quiz_id = learndash_get_quiz_id_by_pro_quiz_id( $pro_quiz_id ); if ( ! empty( $post_quiz_id ) ) { $post_quiz_ids[$post_quiz_id] = $pro_quiz_id; } } if ( !empty( $post_quiz_ids ) ) { if ( ( isset( $this->_post['course_id'] ) ) && ( ! empty( $this->_post['course_id'] ) ) ) { $post_course_id = intval( $this->_post['course_id'] ); } else { $post_course_id = 0; } $post_course_id = apply_filters( 'learndash_quiz_prerequisite_course_check', $post_course_id, $userId, $post_quiz_ids ); $post_quiz_ids = learndash_is_quiz_notcomplete($userId, $post_quiz_ids, true, -1 ); if ( !empty( $post_quiz_ids ) ) { $quizIds = array_values( $post_quiz_ids ); } else { $quizIds = array(); } } if (!empty($quizIds)) { $names = $quizMapper->fetchCol($quizIds, 'name'); if(!empty($names)) { $data['prerequisite'] = implode(', ', $names); } } } } if($quiz->isStartOnlyRegisteredUser()) { $data['startUserLock'] = (int)!is_user_logged_in(); } return $data; } public function loadQuizData() { $quizId = (int)$_POST['quizId']; $userId = get_current_user_id(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $toplistController = new WpProQuiz_Controller_Toplist(); $statisticController = new WpProQuiz_Controller_Statistics(); $quiz = $quizMapper->fetch($quizId); $data = array(); if($quiz === null || $quiz->getId() <= 0) { return array(); } $data['toplist'] = $toplistController->getAddToplist($quiz); if ( $quiz->isShowAverageResult() ) { $data['averageResult'] = $statisticController->getAverageResult($quizId); } else { $data['averageResult'] = 0; } /* $data['quiz_repeats'] = (int)0; $data['user_attempts_left'] = (int)0; $data['user_attempts_taken'] = (int)0; // We need the user quiz stats when they click the start quiz button $quiz_post_id = learndash_get_quiz_id_by_pro_quiz_id( $quizId ); if (!empty($quiz_post_id)) { $quiz_post_meta = get_post_meta( $quiz_post_id, '_sfwd-quiz', true); if ( isset( $quiz_post_meta['sfwd-quiz_repeats'] ) ) { $data['quiz_repeats'] = intval( $quiz_post_meta['sfwd-quiz_repeats'] ); } } if ( !empty( $userId ) ) { $usermeta = get_user_meta( $userId, '_sfwd-quizzes', true ); $usermeta = maybe_unserialize( $usermeta ); if ( ! is_array( $usermeta ) ) { $usermeta = array(); } if ( ! empty( $usermeta ) ) { foreach ( $usermeta as $k => $v ) { if ( $v['quiz'] == $quiz_post_id ) { //error_log('match quiz<pre>'. print_r($v, true) .'</pre>'); $data['user_attempts_taken'] += 1; } } } $data['user_attempts_left'] = (int)( $data['quiz_repeats'] == '' || $data['quiz_repeats'] >= $data['user_attempts_taken'] ); } */ return $data; } private function resetLock($quizId) { if(!current_user_can('wpProQuiz_edit_quiz')) { exit; } $lm = new WpProQuiz_Model_LockMapper(); $qm = new WpProQuiz_Model_QuizMapper(); $q = $qm->fetch($quizId); if($q->getId() > 0) { $q->setQuizRunOnceTime(time()); $qm->save($q); $lm->deleteByQuizId($quizId, WpProQuiz_Model_Lock::TYPE_QUIZ); } exit; } private function showAction() { if(!current_user_can('wpProQuiz_show')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $this->view = new WpProQuiz_View_QuizOverall(); $m = new WpProQuiz_Model_QuizMapper(); $this->view->quiz = $m->fetchAll(); $this->view->show(); } private function editAction($id) { if(!current_user_can('wpProQuiz_edit_quiz')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $prerequisiteMapper = new WpProQuiz_Model_PrerequisiteMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); $m = new WpProQuiz_Model_QuizMapper(); $this->view = new WpProQuiz_View_QuizEdit(); $this->view->header = sprintf( esc_html_x('Edit %s', 'Edit quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); $forms = $formMapper->fetch($id); $prerequisiteQuizList = $prerequisiteMapper->fetchQuizIds($id); if($m->exists($id) == 0) { WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s not found', 'Quiz not found', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ), 'error'); return; } if(isset($this->_post['submit'])) { if(isset($this->_post['resultGradeEnabled'])) { $this->_post['result_text'] = $this->filterResultTextGrade($this->_post); } $quiz = new WpProQuiz_Model_Quiz($this->_post); $quiz->setId($id); if($this->checkValidit($this->_post)) { //WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%s edited', 'Quiz edited', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )), 'info'); $prerequisiteMapper = new WpProQuiz_Model_PrerequisiteMapper(); $prerequisiteMapper->delete($id); if($quiz->isPrerequisite() && !empty($this->_post['prerequisiteList'])) { $prerequisiteMapper->save($id, $this->_post['prerequisiteList']); $quizMapper->activateStatitic($this->_post['prerequisiteList'], 1440); } if(!$this->formHandler($quiz->getId(), $this->_post)) { $quiz->setFormActivated(false); } $quizMapper->save($quiz); $this->showAction(); return; } else { //WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%1$s title or %2$s description are not filled', 'Quiz title or quiz description are not filled', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' )) ); } } else if(isset($this->_post['template']) || isset($this->_post['templateLoad'])) { if(isset($this->_post['template'])) $template = $this->saveTemplate(); else $template = $templateMapper->fetchById($this->_post['templateLoadId']); $data = $template->getData(); if($data !== null) { $quiz = $data['quiz']; $forms = $data['forms']; $prerequisiteQuizList = $data['prerequisiteQuizList']; } } else { $quiz = $m->fetch($id); } $this->view->quiz = $quiz; $this->view->prerequisiteQuizList = $prerequisiteQuizList; $this->view->quizList = $m->fetchAllAsArray(array('id', 'name'), array($id)); $this->view->captchaIsInstalled = class_exists('ReallySimpleCaptcha'); $this->view->forms = $forms; $this->view->templates = $templateMapper->fetchAll(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUIZ, false); $this->view->show(); } private function createAction() { if(!current_user_can('wpProQuiz_add_quiz')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $this->view = new WpProQuiz_View_QuizEdit(); $this->view->header = sprintf( esc_html_x('Create %s', 'Create quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); $forms = null; $prerequisiteQuizList = array(); $m = new WpProQuiz_Model_QuizMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); if(isset($this->_post['submit'])) { if(isset($this->_post['resultGradeEnabled'])) { $this->_post['result_text'] = $this->filterResultTextGrade($this->_post); } $quiz = new WpProQuiz_Model_Quiz($this->_post); $quizMapper = new WpProQuiz_Model_QuizMapper(); if($this->checkValidit($this->_post)) { //WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('Create %s', 'Create quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ), 'info'); $quizMapper->save($quiz); $id = $quizMapper->getInsertId(); $prerequisiteMapper = new WpProQuiz_Model_PrerequisiteMapper(); if($quiz->isPrerequisite() && !empty($this->_post['prerequisiteList'])) { $prerequisiteMapper->save($id, $this->_post['prerequisiteList']); $quizMapper->activateStatitic($this->_post['prerequisiteList'], 1440); } if(!$this->formHandler($id, $this->_post)) { $quiz->setFormActivated(false); $quizMapper->save($quiz); } $this->showAction(); return; } else { //WpProQuiz_View_View::admin_notices( sprintf( esc_html_x('%1$s title or %2$s description are not filled', 'Quiz title or quiz description are not filled', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), learndash_get_custom_label_lower( 'quiz' )) ); } } else if(isset($this->_post['template']) || isset($this->_post['templateLoad'])) { if(isset($this->_post['template'])) $template = $this->saveTemplate(); else $template = $templateMapper->fetchById($this->_post['templateLoadId']); $data = $template->getData(); if($data !== null) { $quiz = $data['quiz']; $forms = $data['forms']; $prerequisiteQuizList = $data['prerequisiteQuizList']; } } else { $quiz = new WpProQuiz_Model_Quiz(); } $this->view->quiz = $quiz; $this->view->prerequisiteQuizList = $prerequisiteQuizList; $this->view->quizList = $m->fetchAllAsArray(array('id', 'name')); $this->view->captchaIsInstalled = class_exists('ReallySimpleCaptcha'); $this->view->forms = $forms; $this->view->templates = $templateMapper->fetchAll(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUIZ, false); $this->view->show(); } private function saveTemplate() { $templateMapper = new WpProQuiz_Model_TemplateMapper(); if(isset($this->_post['resultGradeEnabled'])) { $this->_post['result_text'] = $this->filterResultTextGrade($this->_post); } $quiz = new WpProQuiz_Model_Quiz($this->_post); if($quiz->isPrerequisite() && !empty($this->_post['prerequisiteList']) && !$quiz->isStatisticsOn()) { $quiz->setStatisticsOn(true); $quiz->setStatisticsIpLock(1440); } $form = $this->_post['form']; unset($form[0]); $forms = array(); foreach($form as $f) { if ( isset( $f['fieldname'] ) ) { $f['fieldname'] = trim( $f['fieldname'] ); if ( empty( $f['fieldname'] ) ) { continue; } if ( absint( $f['form_id'] ) && absint( $f['form_delete'] ) ) { continue; } if( $f['type'] == WpProQuiz_Model_Form::FORM_TYPE_SELECT || $f['type'] == WpProQuiz_Model_Form::FORM_TYPE_RADIO ) { if(!empty($f['data'])) { $items = explode("\n", $f['data']); $f['data'] = array(); foreach ($items as $item) { $item = trim($item); if(!empty($item)) $f['data'][] = $item; } } } if(empty($f['data']) || !is_array($f['data'])) $f['data'] = null; $forms[] = new WpProQuiz_Model_Form($f); } } //WpProQuiz_View_View::admin_notices(__('Template stored', 'learndash'), 'info'); $data = array( 'quiz' => $quiz, 'forms' => $forms, 'prerequisiteQuizList' => isset($this->_post['prerequisiteList']) ? $this->_post['prerequisiteList'] : array() ); $quiz_post_id = $quiz->getPostId(); if ( ! empty( $quiz_post_id ) ) { $data['_' . learndash_get_post_type_slug( 'quiz' ) ] = learndash_get_setting( $quiz_post_id ); } // Zero out the ProQuiz Post ID and the reference for the associated settings. $data['quiz']->setPostId(0); $data['_' . learndash_get_post_type_slug( 'quiz' ) ]['quiz_pro'] = 0; $template = new WpProQuiz_Model_Template(); if($this->_post['templateSaveList'] == '0') { $template->setName(trim($this->_post['templateName'])); } else { $template = $templateMapper->fetchById($this->_post['templateSaveList'], false); } $template->setType(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUIZ); $template->setData($data); $templateMapper->save($template); return $template; } private function formHandler($quizId, $post) { if(!isset($post['form'])) return false; $form = $post['form']; unset($form[0]); if(empty($form)) return false; $formMapper = new WpProQuiz_Model_FormMapper(); $deleteIds = array(); $forms = array(); $sort = 0; foreach($form as $f) { if ( ( !isset( $f['fieldname'] ) ) || ( empty( $f['fieldname'] ) ) ) continue; $f['fieldname'] = trim($f['fieldname']); if((int) $f['form_id'] && (int) $f['form_delete']) { $deleteIds[] = (int) $f['form_id']; continue; } $f['sort'] = $sort++; $f['quizId'] = $quizId; if($f['type'] == WpProQuiz_Model_Form::FORM_TYPE_SELECT || $f['type'] == WpProQuiz_Model_Form::FORM_TYPE_RADIO) { if(!empty($f['data'])) { $items = explode("\n", $f['data']); $f['data'] = array(); foreach ($items as $item) { $item = trim($item); if(!empty($item)) $f['data'][] = $item; } } } if(empty($f['data']) || !is_array($f['data'])) $f['data'] = null; $forms[] = new WpProQuiz_Model_Form($f); } if(!empty($deleteIds)) $formMapper->deleteForm($deleteIds, $quizId); $formMapper->update($forms); return !empty($forms); } private function deleteAction($id) { if(!current_user_can('wpProQuiz_delete_quiz')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $m = new WpProQuiz_Model_QuizMapper(); // $qm = new WpProQuiz_Model_QuestionMapper(); // $lm = new WpProQuiz_Model_LockMapper(); // $srm = new WpProQuiz_Model_StatisticRefMapper(); // $pm = new WpProQuiz_Model_PrerequisiteMapper(); // $tm = new WpProQuiz_Model_ToplistMapper(); // $m->delete($id); // $qm->deleteByQuizId($id); // $lm->deleteByQuizId($id); // $srm->deleteAll($id); // $pm->delete($id); // $tm->delete($id); $m->deleteAll($id); //WpProQuiz_View_View::admin_notices(sprintf( esc_html_x('%s deleted', 'Quiz deleted', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ), 'info'); $this->showAction(); } private function checkValidit($post) { if ( ( isset( $post['name'] ) ) && ( ! empty( $post['name'] ) ) && ( isset( $post['text'] ) ) && ( ! empty( $post['text'] ) ) ) { return true; } if ( ( isset( $post['post_ID'] ) ) && ( ! empty( $post['post_ID'] ) ) ) { if ( learndash_get_post_type_slug( 'quiz' ) === get_post_type( absint( $post['post_ID'] ) ) ) { return true; } } } private function filterResultTextGrade($post) { $result = array(); $sorted = array(); if ( isset( $post['resultTextGrade'] ) ) { $sorted = learndash_quiz_result_message_sort( $post['resultTextGrade'] ); return $sorted; } // if ( ! empty( $sorted ) ) { // foreach ( $sorted as $item ) { // $result['text'][] = $item['text']; // $result['prozent'][] = $item['prozent']; // } // } return $result; } private function setResultCookie(WpProQuiz_Model_Quiz $quiz) { $prerequisite = new WpProQuiz_Model_PrerequisiteMapper(); if(get_current_user_id() == 0 && $prerequisite->isQuizId($quiz->getId())) { $cookieData = array(); if(isset($this->_cookie['wpProQuiz_result'])) { $d = json_decode($this->_cookie['wpProQuiz_result'], true); if($d !== null && is_array($d)) { $cookieData = $d; } } $cookieData[$quiz->getId()] = 1; $url = parse_url(get_bloginfo( 'url' )); setcookie('wpProQuiz_result', json_encode($cookieData), time() + 60*60*24*300, empty($url['path']) ? '/' : $url['path']); } } public function completedQuiz() { $lockMapper = new WpProQuiz_Model_LockMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $is100P = $this->_post['results']['comp']['result'] == 100; $userId = get_current_user_id(); $quiz = $quizMapper->fetch($this->_post['quizId']); if ( ( isset( $this->_post['quiz'] ) ) && ( ! empty( $this->_post['quiz'] ) ) ) { if ( absint( $this->_post['quiz'] ) !== absint( $quiz->getPostId() ) ) { $quiz->setPostId( absint( $this->_post['quiz'] ) ); } } if ( $quiz === null || $quiz->getId() <= 0 ) { exit; } $categories = $categoryMapper->fetchByQuiz($quiz); $this->setResultCookie( $quiz ); $this->emailNote( $quiz, $this->_post['results']['comp'], $categories ); if( ! $this->isPreLockQuiz( $quiz ) ) { $statistics = new WpProQuiz_Controller_Statistics(); $statisticRefMapper_id = $statistics->save($quiz); do_action('wp_pro_quiz_completed_quiz', $statisticRefMapper_id) ; if ( $is100P ) do_action( 'wp_pro_quiz_completed_quiz_100_percent' ); exit; } $lockMapper->deleteOldLock(60*60*24*7, $this->_post['quizId'], time(), WpProQuiz_Model_Lock::TYPE_QUIZ, 0); $lockIp = $lockMapper->isLock($this->_post['quizId'], $this->getIp(), get_current_user_id(), WpProQuiz_Model_Lock::TYPE_QUIZ); $lockCookie = false; $cookieTime = $quiz->getQuizRunOnceTime(); $cookieJson = null; if(isset($this->_cookie['wpProQuiz_lock']) && get_current_user_id() == 0 && $quiz->isQuizRunOnceCookie()) { $cookieJson = json_decode($this->_cookie['wpProQuiz_lock'], true); if($cookieJson !== false) { if(isset($cookieJson[$this->_post['quizId']]) && $cookieJson[$this->_post['quizId']] == $cookieTime) { $lockCookie = true; } } } if(!$lockIp && !$lockCookie) { $statistics = new WpProQuiz_Controller_Statistics(); $statisticRefMapper_id = $statistics->save($quiz); //do_action('wp_pro_quiz_completed_quiz'); do_action('wp_pro_quiz_completed_quiz', $statisticRefMapper_id); if($is100P) do_action('wp_pro_quiz_completed_quiz_100_percent'); if(get_current_user_id() == 0 && $quiz->isQuizRunOnceCookie()) { $cookieData = array(); if($cookieJson !== null || $cookieJson !== false) { $cookieData = $cookieJson; } $cookieData[$this->_post['quizId']] = $quiz->getQuizRunOnceTime(); $url = parse_url(get_bloginfo( 'url' )); setcookie('wpProQuiz_lock', json_encode($cookieData), time() + 60*60*24*60, empty($url['path']) ? '/' : $url['path']); } $lock = new WpProQuiz_Model_Lock(); $lock->setUserId(get_current_user_id()); $lock->setQuizId($this->_post['quizId']); $lock->setLockDate(time()); $lock->setLockIp($this->getIp()); $lock->setLockType(WpProQuiz_Model_Lock::TYPE_QUIZ); $lockMapper->insert($lock); } exit; } public function isPreLockQuiz(WpProQuiz_Model_Quiz $quiz) { $userId = get_current_user_id(); if($quiz->isQuizRunOnce()) { switch ($quiz->getQuizRunOnceType()) { case WpProQuiz_Model_Quiz::QUIZ_RUN_ONCE_TYPE_ALL: return true; case WpProQuiz_Model_Quiz::QUIZ_RUN_ONCE_TYPE_ONLY_USER: return $userId > 0; case WpProQuiz_Model_Quiz::QUIZ_RUN_ONCE_TYPE_ONLY_ANONYM: return $userId == 0; } } return false; } private function getIp() { if(get_current_user_id() > 0) return '0'; else return filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP); } private function emailNote(WpProQuiz_Model_Quiz $quiz, $result, $categories) { $globalMapper = new WpProQuiz_Model_GlobalSettingsMapper(); $email_settings_admin = LearnDash_Settings_Section::get_section_settings_all( 'LearnDash_Settings_Quizzes_Admin_Email' ); //error_log('email_settings_admin<pre>'. print_r($email_settings_admin, true) .'</pre>'); $email_settings_user = LearnDash_Settings_Section::get_section_settings_all( 'LearnDash_Settings_Quizzes_User_Email' ); //error_log('email_settings_user<pre>'. print_r($email_settings_user, true) .'</pre>'); $user = wp_get_current_user(); $r = array( '$userId' => $user->ID, '$username' => $user->display_name, '$quizname' => $quiz->getName(), '$result' => $result['result'].'%', '$points' => $result['points'], '$ip' => filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP), '$categories' => empty($result['cats']) ? '' : $this->setCategoryOverview($result['cats'], $categories) ); if($user->ID == 0) { $r['$username'] = $r['$ip']; } if($quiz->isUserEmailNotification()) { //$msg = str_replace(array_keys($r), $r, $userEmail['message']); $msg = str_replace(array_keys($r), $r, $email_settings_user['user_mail_message']); $msg = apply_filters( 'learndash_quiz_email_note_user_message', $msg, $r, $quiz, $result, $categories ); $headers = ''; if ( ( isset( $email_settings_user['user_mail_from'] ) ) && ( !empty( $email_settings_user['user_mail_from'] ) ) && ( is_email( $email_settings_user['user_mail_from'] ) ) ) { if ( ( !isset( $email_settings_user['user_mail_from_name'] ) ) || ( empty( $email_settings_user['user_mail_from_name'] ) ) ) { $email_settings_user['user_mail_from_name'] = ''; $email_user = get_user_by('emal', $email_settings_user['user_mail_from'] ); if ( ( $email_user ) && ( is_a( $email_user, 'WP_User' ) ) ) { $email_settings_user['user_mail_from_name'] = $email_user->display_name; } } $headers .= 'From: '; if ( ( isset( $email_settings_user['user_mail_from_name'] ) ) && ( !empty( $email_settings_user['user_mail_from_name'] ) ) ) { $headers .= $email_settings_user['user_mail_from_name'] .' <'. $email_settings_user['user_mail_from'] .'>'; } else { $headers .= $email_settings_user['user_mail_from']; } } if ( ( isset( $email_settings_user['user_mail_html'] ) ) && ( 'yes' === $email_settings_user['user_mail_html'] ) ) { add_filter( 'wp_mail_content_type', array( $this, 'htmlEmailContent' ) ); $msg = wpautop( $msg ); } $email_params = array( "email" => $user->user_email, "subject" => $email_settings_user['user_mail_subject'], "msg" => $msg, "headers" => $headers ); $email_params = apply_filters("learndash_quiz_email", $email_params, $quiz); //error_log('Quiz User Email params<pre>'. print_r($email_params, true) .'</pre>'); wp_mail( $email_params['email'], $email_params['subject'], $email_params['msg'], $email_params['headers'] ); if ( ( isset( $email_settings_user['user_mail_html'] ) ) && ( 'yes' === $email_settings_user['user_mail_html'] ) ) { remove_filter( 'wp_mail_content_type', array( $this, 'htmlEmailContent' ) ); } } if($quiz->getEmailNotification() == WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_ALL || (get_current_user_id() > 0 && $quiz->getEmailNotification() == WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_REG_USER)) { $msg = str_replace( array_keys( $r ), $r, $email_settings_admin['admin_mail_message'] ); $msg = apply_filters( 'learndash_quiz_email_note_admin_message', $msg, $r, $quiz, $result, $categories ); $headers = ''; if ( ( ! isset( $email_settings_admin['admin_mail_from'] ) ) || ( empty( $email_settings_admin['admin_mail_from'] ) ) || ( !is_email( $email_settings_admin['admin_mail_from'] ) ) ) { $email_settings_admin['admin_mail_from'] = get_option( 'admin_email' ); } if ( ( !isset( $email_settings_admin['admin_mail_from_name'] ) ) || ( empty( $email_settings_admin['admin_mail_from_name'] ) ) ) { $email_settings_admin['admin_mail_from_name'] = ''; if ( ! empty( $email_settings_admin['admin_mail_from'] ) ) { $email_user = get_user_by('emal', $email_settings_admin['admin_mail_from'] ); if ( ( $email_user ) && ( is_a( $email_user, 'WP_User' ) ) ) { $email_settings_admin['admin_mail_from_name'] = $email_user->display_name; } } } if ( ! empty( $email_settings_admin['admin_mail_from'] ) ) { $headers .= 'From: '; if ( ( isset( $email_settings_admin['admin_mail_from_name'] ) ) && ( !empty( $email_settings_admin['admin_mail_from_name'] ) ) ) { $headers .= $email_settings_admin['admin_mail_from_name'] .' <'. $email_settings_admin['admin_mail_from'] .'>'; } else { $headers .= $email_settings_admin['admin_mail_from']; } } if ( ( isset( $email_settings_admin['admin_mail_html'] ) ) && ( $email_settings_admin['admin_mail_html'] ) ) { add_filter( 'wp_mail_content_type', array( $this, 'htmlEmailContent' ) ); $msg = wpautop( $msg ); } $email_params = array( 'email' => $email_settings_admin['admin_mail_to'], 'subject' => $email_settings_admin['admin_mail_subject'], 'msg' => $msg, 'headers' => $headers ); $email_params = apply_filters( 'learndash_quiz_email_admin', $email_params, $quiz); //error_log('Quiz Admin Email params<pre>'. print_r($email_params, true) .'</pre>'); wp_mail($email_params['email'], $email_params['subject'], $email_params['msg'], $email_params['headers'] ); if ( ( isset( $email_settings_admin['admin_mail_html'] ) ) && ( 'yes' === $email_settings_admin['admin_mail_html'] ) ) { remove_filter( 'wp_mail_content_type', array( $this, 'htmlEmailContent' ) ); } } } public function htmlEmailContent($contentType) { return 'text/html'; } private function setCategoryOverview( $category_scores = array() , $question_cats = array() ) { if ( ( ! empty( $category_scores ) ) && ( ! empty( $question_cats ) ) ) { $question_categories = array(); foreach ( $question_cats as $cat ) { if ( ! $cat->getCategoryId() ) { $cat->setCategoryName( esc_html__( 'Not categorized', 'learndash' ) ); } $question_categories[ $cat->getCategoryId() ] = $cat->getCategoryName(); } } $output = SFWD_LMS::get_template( 'quiz_result_categories_email.php', array( 'question_categories' => $question_categories, 'category_scores' => $category_scores, ) ); return $output; //$cats = array(); // //foreach($categories as $cat) { // /* @var $cat WpProQuiz_Model_Category */ // // if(!$cat->getCategoryId()) { // $cat->setCategoryName(__('Not categorized', 'learndash')); // } // // $cats[$cat->getCategoryId()] = $cat->getCategoryName(); //} // //$a = esc_html__('Categories', 'learndash').":\n"; // //foreach($catArray as $id => $value) { // if(!isset($cats[$id])) // continue; // // $a .= '* '.str_pad($cats[$id], 35, '.').((float)$value)."%\n"; //} // //return $a; } } lib/controller/WpProQuiz_Controller_Request.php 0000666 00000001311 15214236625 0016047 0 ustar 00 <?php class WpProQuiz_Controller_Request { static protected $_post = null; static protected $_cookie = null; public static function getPost() { if(self::$_post == null) { self::$_post = self::clear($_POST); } return self::$_post; } public static function getPostValue($name) { if(self::$_post == null) { self::$_post = self::clear($_POST); } return isset(self::$_post[$name]) ? self::$_post[$name] : null; } public static function getCookie() { if(self::$_post == null) { self::$_cookie = self::clear($_COOKIE); } return self::$_cookie; } private static function clear($data) { if($data !== null) return stripslashes_deep($data); return array(); } } lib/controller/WpProQuiz_Controller_ImportExport.php 0000666 00000005341 15214236625 0017102 0 ustar 00 <?php class WpProQuiz_Controller_ImportExport extends WpProQuiz_Controller_Controller { public function route() { @set_time_limit(0); @ini_set('memory_limit', '128M'); if(!isset($_GET['action']) || $_GET['action'] != 'import' && $_GET['action'] != 'export') { wp_die("Error"); } if($_GET['action'] == 'export') { $this->handleExport(); } else { $this->handleImport(); } } private function handleExport() { if(!current_user_can('wpProQuiz_export')) { wp_die(__('You do not have sufficient permissions to access this page.')); } if(isset($this->_post ['exportType']) && $this->_post ['exportType'] == 'xml') { $export = new WpProQuiz_Helper_ExportXml(); $filename = 'WpProQuiz_export_'.time().'.xml'; } else { $export = new WpProQuiz_Helper_Export(); $filename = 'WpProQuiz_export_'.time().'.wpq'; } $a = $export->export($this->_post['exportIds']); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.$filename.'"'); echo $a; exit; } private function handleImport() { if(!current_user_can('wpProQuiz_import')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $this->view = new WpProQuiz_View_Import(); $this->view->error = false; if(isset($_FILES, $_FILES['import']) && substr($_FILES['import']['name'], -3) == 'xml' || isset($this->_post['importType']) && $this->_post['importType'] == 'xml') { $import = new WpProQuiz_Helper_ImportXml(); $importType = 'xml'; } else { $import = new WpProQuiz_Helper_Import(); $importType = 'wpq'; } $this->view->importType = $importType; if(isset($_FILES, $_FILES['import']) && $_FILES['import']['error'] == 0) { if($import->setImportFileUpload($_FILES['import']) === false) { $this->view->error = $import->getError(); } else { $data = $import->getImportData(); if($data === false) { $this->view->error = $import->getError(); } $this->view->import = $data; $this->view->importData = $import->getContent(); unset($data); } } else if(isset($this->_post, $this->_post['importSave'])) { if($import->setImportString($this->_post['importData']) === false) { $this->view->error = $import->getError(); } else { $ids = isset($this->_post['importItems']) ? $this->_post['importItems'] : false; if($ids !== false && $import->saveImport($ids) === false) { $this->view->error = $import->getError(); } else { $this->view->finish = true; $this->view->import_post_id = absint( $import->import_post_id ); } } } else { $this->view->error = esc_html__('File cannot be processed', 'learndash'); } $this->view->show(); } } lib/controller/WpProQuiz_Controller_Question.php 0000666 00000041415 15214236625 0016237 0 ustar 00 <?php class WpProQuiz_Controller_Question extends WpProQuiz_Controller_Controller { private $_quizId; public function route() { if ( ! isset( $_GET['quiz_id'] ) || empty( $_GET['quiz_id'] ) ) { WpProQuiz_View_View::admin_notices( sprintf( esc_html_x( '%s not found', 'Quiz not found', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ), 'error' ); return; } $this->_quizId = (int) $_GET['quiz_id']; $action = isset( $_GET['action'] ) ? $_GET['action'] : 'show'; $m = new WpProQuiz_Model_QuizMapper(); if ( $m->exists( $this->_quizId ) == 0 ) { WpProQuiz_View_View::admin_notices( sprintf( esc_html_x( '%s not found', 'Quiz not found', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ),'error' ); return; } // if(isset($this->_post['hidden_action'])) { // switch ($this->_post['hidden_action']) { // case 'edit': // $this->editPostAction($this->_post['questionId']); // break; // } // } switch ( $action ) { // case 'add': // $this->createAction(); // break; case 'show': $this->showAction(); break; case 'addEdit': $this->addEditQuestion( (int) $_GET['quiz_id'] ); break; // case 'edit': // $this->editAction($_GET['id']); // break; case 'delete': $this->deleteAction( $_GET['id'] ); break; case 'save_sort': $this->saveSort(); break; case 'load_question': $this->loadQuestion( $_GET['quiz_id'] ); break; case 'copy_question': $this->copyQuestion( $_GET['quiz_id'] ); break; } } private function addEditQuestion( $quizId ) { $questionId = isset( $_GET['questionId'] ) ? (int) $_GET['questionId'] : 0; if ( $questionId ) { if ( ! current_user_can( 'wpProQuiz_edit_quiz' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'learndash' ) ); } } else { if ( ! current_user_can( 'wpProQuiz_add_quiz' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'learndash' ) ); } } $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $cateoryMapper = new WpProQuiz_Model_CategoryMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); if ( $questionId && $questionMapper->existsAndWritable( $questionId ) == 0 ) { WpProQuiz_View_View::admin_notices( esc_html__( 'Question not found', 'learndash' ), 'error' ); return; } $question = new WpProQuiz_Model_Question(); if ( isset( $this->_post['template'] ) || ( isset( $this->_post['templateLoad'] ) && isset( $this->_post['templateLoadId'] ) ) ) { if ( isset( $this->_post['template'] ) ) { $template = $this->saveTemplate(); } else { $template = $templateMapper->fetchById( $this->_post['templateLoadId'] ); } $data = $template->getData(); if ( $data !== null ) { $question = $data['question']; $question->setId( $questionId ); $question->setQuizId( $quizId ); } } else if ( isset( $this->_post['submit'] ) ) { $add_new_question_url = admin_url( "admin.php?page=ldAdvQuiz&module=question&action=addEdit&quiz_id=" . $quizId . "&post_id=" . @$_REQUEST["post_id"] ); $add_new_question = "<a href='" . $add_new_question_url . "'>" . esc_html__( "Click here to add another question.", 'learndash' ) . "</a>"; //if ( $questionId ) { // WpProQuiz_View_View::admin_notices( esc_html__( 'Question edited', 'learndash' ) . ". " . $add_new_question, 'info' ); //} else { // WpProQuiz_View_View::admin_notices( esc_html__( 'Question added', 'learndash' ) . ". " . $add_new_question, 'info' ); //} $question = $questionMapper->save( $this->getPostQuestionModel( $quizId, $questionId ), true ); $questionId = $question->getId(); } else { if ( $questionId ) { $question = $questionMapper->fetch( $questionId ); } } $this->view = new WpProQuiz_View_QuestionEdit(); $this->view->categories = $cateoryMapper->fetchAll(); $this->view->quiz = $quizMapper->fetch( $quizId ); $this->view->templates = $templateMapper->fetchAll( WpProQuiz_Model_Template::TEMPLATE_TYPE_QUESTION, false ); $this->view->question = $question; $this->view->data = $this->setAnswerObject( $question ); $this->view->header = $questionId ? esc_html__( 'Edit question', 'learndash' ) : esc_html__( 'New question', 'learndash' ); if ( $this->view->question->isAnswerPointsActivated() ) { $this->view->question->setPoints( 1 ); } $this->view->show(); } private function saveTemplate() { $questionModel = $this->getPostQuestionModel( 0, 0 ); $templateMapper = new WpProQuiz_Model_TemplateMapper(); $template = new WpProQuiz_Model_Template(); if ( $this->_post['templateSaveList'] == '0' ) { $template->setName( trim( $this->_post['templateName'] ) ); } else { $template = $templateMapper->fetchById( $this->_post['templateSaveList'], false ); } $template->setType( WpProQuiz_Model_Template::TEMPLATE_TYPE_QUESTION ); $template->setData( array( 'question' => $questionModel ) ); return $templateMapper->save( $template ); } public function getPostQuestionModel( $quizId, $questionId ) { $questionMapper = new WpProQuiz_Model_QuestionMapper(); $post = WpProQuiz_Controller_Request::getPost(); $post['id'] = $questionId; $post['quizId'] = $quizId; $post['title'] = isset( $post['title'] ) ? trim( $post['title'] ) : ''; $post['sort'] = $questionMapper->getSort($questionId); $clearPost = $this->clearPost( $post ); $post['answerData'] = $clearPost['answerData']; if ( ( isset( $post['title'] ) ) && ( empty( $post['title'] ) ) ) { $count = $questionMapper->count( $quizId ); $post['title'] = sprintf( esc_html_x( 'Question: %d', 'placeholder: question count' , 'learndash' ), $count + 1 ); } if ( ( isset( $post['answerType'] ) ) && ( $post['answerType'] === 'assessment_answer' ) ) { $post['answerPointsActivated'] = 1; } if ( ( isset( $post['answerType'] ) ) && ( $post['answerType'] === 'essay' ) ) { $post['answerPointsActivated'] = 0; } if ( isset( $post['answerPointsActivated'] ) ) { if ( isset( $post['answerPointsDiffModusActivated'] ) ) { $post['points'] = $clearPost['maxPoints']; } else { $post['points'] = $clearPost['points']; } } if ( isset( $post['category'] ) ) { $post['categoryId'] = $post['category'] > 0 ? $post['category'] : 0; } else { $post['categoryId'] = 0; } return new WpProQuiz_Model_Question( $post ); } public function copyQuestion( $quizId ) { if ( ! current_user_can( 'wpProQuiz_edit_quiz' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'learndash' ) ); } $m = new WpProQuiz_Model_QuestionMapper(); $questions = $m->fetchById( $this->_post['copyIds'] ); foreach ( $questions as $question ) { $question->setId( 0 ); $question->setQuizId( $quizId ); $m->save( $question ); } //WpProQuiz_View_View::admin_notices( esc_html__( 'questions copied', 'learndash' ), 'info' ); $this->showAction(); } public function loadQuestion( $quizId ) { if ( ! current_user_can( 'wpProQuiz_edit_quiz' ) ) { echo json_encode( array() ); exit; } $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $data = array(); $quiz = $quizMapper->fetchAll(); foreach ( $quiz as $qz ) { if ( $qz->getId() == $quizId ) { continue; } $question = $questionMapper->fetchAll( $qz->getId() ); $questionArray = array(); foreach ( $question as $qu ) { $questionArray[] = array( 'name' => $qu->getTitle(), 'id' => $qu->getId() ); } $data[] = array( 'name' => $qz->getName(), 'id' => $qz->getId(), 'question' => $questionArray ); } echo json_encode( $data ); exit; } public function saveSort() { if ( ! current_user_can( 'wpProQuiz_edit_quiz' ) ) { exit; } $mapper = new WpProQuiz_Model_QuestionMapper(); $map = $this->_post['sort']; foreach ( $map as $k => $v ) { $mapper->updateSort( $v, $k ); } exit; } public function deleteAction( $id ) { if ( ! current_user_can( 'wpProQuiz_delete_quiz' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'learndash' ) ); } $mapper = new WpProQuiz_Model_QuestionMapper(); $mapper->setOnlineOff( $id ); $this->showAction(); } /** * @deprecated */ public function editAction( $id ) { if ( ! current_user_can( 'wpProQuiz_edit_quiz' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'learndash' ) ); } $questionMapper = new WpProQuiz_Model_QuestionMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $cateoryMapper = new WpProQuiz_Model_CategoryMapper(); $this->view = new WpProQuiz_View_QuestionEdit(); $this->view->quiz = $quizMapper->fetch( $id ); $this->view->question = $questionMapper->fetch( $id ); $this->view->data = $this->setAnswerObject( $this->view->question ); $this->view->categories = $cateoryMapper->fetchAll(); $this->view->header = esc_html__( 'Edit question', 'learndash' ); if ( $this->view->question->isAnswerPointsActivated() ) { $this->view->question->setPoints( 1 ); } $this->view->show(); } /** * @deprecated */ public function editPostAction( $id ) { $mapper = new WpProQuiz_Model_QuestionMapper(); if ( isset( $this->_post['submit'] ) && $mapper->existsAndWritable( $id ) ) { $post = $this->_post; $post['id'] = $id; $post['title'] = isset( $post['title'] ) ? trim( $post['title'] ) : ''; $clearPost = $this->clearPost( $post ); $post['answerData'] = $clearPost['answerData']; if ( empty( $post['title'] ) ) { $question = $mapper->fetch( $id ); $post['title'] = sprintf( esc_html__( 'Question: %d', 'learndash' ), $question->getSort() + 1 ); } if ( $post['answerType'] === 'assessment_answer' ) { $post['answerPointsActivated'] = 1; } if ( $post['answerType'] === 'essay' ) { $post['answerPointsActivated'] = 0; } if ( isset( $post['answerPointsActivated'] ) ) { if ( isset( $post['answerPointsDiffModusActivated'] ) ) { $post['points'] = $clearPost['maxPoints']; } else { $post['points'] = $clearPost['points']; } } $post['categoryId'] = $post['category'] > 0 ? $post['category'] : 0; $mapper->save( new WpProQuiz_Model_Question( $post ), true ); //WpProQuiz_View_View::admin_notices( esc_html__( 'Question edited', 'learndash' ), 'info' ); } } /** * @deprecated */ public function createAction() { if ( ! current_user_can( 'wpProQuiz_add_quiz' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'learndash' ) ); } $quizMapper = new WpProQuiz_Model_QuizMapper(); $cateoryMapper = new WpProQuiz_Model_CategoryMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); $this->view = new WpProQuiz_View_QuestionEdit(); $this->view->question = new WpProQuiz_Model_Question(); $this->view->categories = $cateoryMapper->fetchAll(); $this->view->quiz = $quizMapper->fetch( $this->_quizId ); $this->view->data = $this->setAnswerObject(); $this->view->templates = $templateMapper->fetchAll( WpProQuiz_Model_Template::TEMPLATE_TYPE_QUESTION, false ); $this->view->header = esc_html__( 'New question', 'learndash' ); if ( $this->view->question->isAnswerPointsActivated() ) { $this->view->question->setPoints( 1 ); } $this->view->show(); } public function setAnswerObject( WpProQuiz_Model_Question $question = null ) { //Defaults $data = array( 'sort_answer' => array( new WpProQuiz_Model_AnswerTypes() ), 'classic_answer' => array( new WpProQuiz_Model_AnswerTypes() ), 'matrix_sort_answer' => array( new WpProQuiz_Model_AnswerTypes() ), 'cloze_answer' => array( new WpProQuiz_Model_AnswerTypes() ), 'free_answer' => array( new WpProQuiz_Model_AnswerTypes() ), 'assessment_answer' => array( new WpProQuiz_Model_AnswerTypes() ), 'essay' => array( new WpProQuiz_Model_AnswerTypes() ), ); if ( $question !== null ) { $type = $question->getAnswerType(); $type = ( $type == 'single' || $type == 'multiple' ) ? 'classic_answer' : $type; $answerData = $question->getAnswerData(); if ( ( isset( $data[ $type ] ) ) && ( $answerData !== null ) && ( !empty( $answerData ) ) ) { $data[ $type ] = $question->getAnswerData(); } } return $data; } public function clearPost( $post ) { if ( ( isset( $post['answerType'] ) ) && ( $post['answerType'] == 'cloze_answer' ) && ( isset( $post['answerData']['cloze'] ) ) ) { preg_match_all( '#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', $post['answerData']['cloze']['answer'], $matches ); $points = 0; $maxPoints = 0; foreach ( $matches[2] as $match ) { if ( empty( $match ) ) { $match = 1; } $points += $match; $maxPoints = max( $maxPoints, $match ); } return array( 'points' => $points, 'maxPoints' => $maxPoints, 'answerData' => array( new WpProQuiz_Model_AnswerTypes( $post['answerData']['cloze'] ) ) ); } if ( ( isset( $post['answerType'] ) ) && ( $post['answerType'] == 'assessment_answer' ) && ( isset( $post['answerData']['assessment'] ) ) ) { preg_match_all( '#\{(.*?)\}#im', $post['answerData']['assessment']['answer'], $matches ); $points = 0; $maxPoints = 0; foreach ( $matches[1] as $match ) { preg_match_all( '#\[([^\|\]]+)(?:\|(\d+))?\]#im', $match, $ms ); $points += count( $ms[1] ); $maxPoints = max( $maxPoints, count( $ms[1] ) ); } return array( 'points' => $points, 'maxPoints' => $maxPoints, 'answerData' => array( new WpProQuiz_Model_AnswerTypes( $post['answerData']['assessment'] ) ) ); } if ( ( isset( $post['answerType'] ) ) && ( $post['answerType'] == 'essay' ) && ( isset( $post['answerData']['essay'] ) ) ) { $answerType = new WpProQuiz_Model_AnswerTypes( $post['answerData']['essay'] ); $answerType->setPoints( $post['points'] ); $answerType->setGraded( true ); $answerType->setGradedType( $post['answerData']['essay']['type'] ); $answerType->setGradingProgression( $post['answerData']['essay']['progression'] ); $points = $post['points']; return array( 'points' => $points, 'maxPoints' => $points, 'answerData' => array( $answerType ) ); } if ( isset( $post['answerData']['cloze'] ) ) { unset( $post['answerData']['cloze'] ); } if ( isset( $post['answerData']['assessment'] ) ) { unset( $post['answerData']['assessment'] ); } if ( isset( $post['answerData']['none'] ) ) { unset( $post['answerData']['none'] ); } $answerData = array(); $points = 0; $maxPoints = 0; if ( isset( $post['answerData'] ) ) { foreach ( $post['answerData'] as $k => $v ) { if ( ( isset( $v['answer'] ) ) && ( trim( $v['answer'] ) == '' ) ) { if ( $post['answerType'] != 'matrix_sort_answer' ) { continue; } else { if ( ( !isset( $v['sort_string'] ) ) || ( trim( $v['sort_string'] ) == '' ) ) { continue; } } } $answerType = new WpProQuiz_Model_AnswerTypes( $v ); if ( ( $post['answerType'] == 'matrix_sort_answer' ) || ( $post['answerType'] == 'sort_answer' ) ) { $points += $answerType->getPoints(); $maxPoints = max( $maxPoints, $answerType->getPoints() ); } else if ( $answerType->isCorrect() ) { $points += $answerType->getPoints(); $maxPoints = max( $maxPoints, $answerType->getPoints() ); } $answerData[] = $answerType; } } return array( 'points' => $points, 'maxPoints' => $maxPoints, 'answerData' => $answerData ); } public function clear( $a ) { foreach ( $a as $k => $v ) { if ( is_array( $v ) ) { $a[ $k ] = $this->clear( $a[ $k ] ); } if ( is_string( $a[ $k ] ) ) { $a[ $k ] = trim( $a[ $k ] ); if ( $a[ $k ] != '' ) { continue; } } if ( empty( $a[ $k ] ) ) { unset( $a[ $k ] ); } } return $a; } public function showAction() { if ( ! current_user_can( 'wpProQuiz_show' ) ) { wp_die( esc_html__( 'You do not have sufficient permissions to access this page.', 'learndash' ) ); } $m = new WpProQuiz_Model_QuizMapper(); $mm = new WpProQuiz_Model_QuestionMapper(); $this->view = new WpProQuiz_View_QuestionOverall(); $this->view->quiz = $m->fetch( $this->_quizId ); //if ( isset( $_GET['post_id'] ) ) { // $quiz_post_id = absint( $_GET['post_id'] ); // if ( $quiz_post_id !== absint( $this->view->quiz->getPostId() ) ) { // $this->view->quiz->setPostId( $quiz_post_id ); // } //} //$this->view->question = $mm->fetchAll( $this->view->quiz ); $this->view->question = $mm->fetchAll( $this->_quizId ); $this->view->show(); } } lib/controller/WpProQuiz_Controller_GlobalSettings.php 0000666 00000004536 15214236625 0017354 0 ustar 00 <?php class WpProQuiz_Controller_GlobalSettings extends WpProQuiz_Controller_Controller { public function route() { $this->edit(); } private function edit() { if(!current_user_can('wpProQuiz_change_settings')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $mapper = new WpProQuiz_Model_GlobalSettingsMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $templateMapper = new WpProQuiz_Model_TemplateMapper(); $view = new WpProQuiz_View_GobalSettings(); if(isset($this->_post['submit'])) { $mapper->save(new WpProQuiz_Model_GlobalSettings($this->_post)); //WpProQuiz_View_View::admin_notices(__('Settings saved', 'learndash'), 'info'); $toplistDateFormat = $this->_post['toplist_date_format']; if($toplistDateFormat == 'custom') { $toplistDateFormat = trim($this->_post['toplist_date_format_custom']); } $statisticTimeFormat = $this->_post['statisticTimeFormat']; if(add_option('wpProQuiz_toplistDataFormat', $toplistDateFormat) === false) { update_option('wpProQuiz_toplistDataFormat', $toplistDateFormat); } if(add_option('wpProQuiz_statisticTimeFormat', $statisticTimeFormat, '', 'no') === false) { update_option('wpProQuiz_statisticTimeFormat', $statisticTimeFormat); } //Email $mapper->saveEmailSettiongs($this->_post['email']); $mapper->saveUserEmailSettiongs($this->_post['userEmail']); } else if(isset($this->_post['databaseFix'])) { //WpProQuiz_View_View::admin_notices(__('Database repaired', 'learndash'), 'info'); $DbUpgradeHelper = new WpProQuiz_Helper_DbUpgrade(); $DbUpgradeHelper->databaseDelta(); } $view->settings = $mapper->fetchAll(); $view->isRaw = !preg_match('[raw]', apply_filters('the_content', '[raw]a[/raw]')); $view->category = $categoryMapper->fetchAll(); $view->email = $mapper->getEmailSettings(); $view->userEmail = $mapper->getUserEmailSettings(); $view->templateQuiz = $templateMapper->fetchAll(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUIZ, false); $view->templateQuestion = $templateMapper->fetchAll(WpProQuiz_Model_Template::TEMPLATE_TYPE_QUESTION, false); $view->toplistDataFormat = get_option('wpProQuiz_toplistDataFormat', 'Y/m/d g:i A'); $view->statisticTimeFormat = get_option('wpProQuiz_statisticTimeFormat', 'Y/m/d g:i A'); $view->show(); } } lib/controller/WpProQuiz_Controller_StyleManager.php 0000666 00000002020 15214236625 0017010 0 ustar 00 <?php class WpProQuiz_Controller_StyleManager extends WpProQuiz_Controller_Controller { public function route() { $this->show(); } private function show() { global $learndash_assets_loaded; //wp_enqueue_style( // 'wpProQuiz_front_style', // plugins_url('css/wpProQuiz_front'. leardash_min_asset() .'.css', WPPROQUIZ_FILE), // array(), // LEARNDASH_SCRIPT_VERSION_TOKEN //); //wp_style_add_data( 'wpProQuiz_front_style', 'rtl', 'replace' ); //$learndash_assets_loaded['styles']['wpProQuiz_front_style'] = __FUNCTION__; $filepath = SFWD_LMS::get_template( 'learndash_quiz_front.css', null, null, true ); if ( !empty( $filepath ) ) { wp_enqueue_style( 'learndash_quiz_front_css', learndash_template_url_from_path( $filepath ), array(), LEARNDASH_SCRIPT_VERSION_TOKEN ); wp_style_add_data( 'learndash_quiz_front_css', 'rtl', 'replace' ); $learndash_assets_loaded['styles']['learndash_quiz_front_css'] = __FUNCTION__; } $view = new WpProQuiz_View_StyleManager(); $view->show(); } } lib/controller/WpProQuiz_Controller_Front.php 0000666 00000023602 15214236625 0015516 0 ustar 00 <?php class WpProQuiz_Controller_Front { /** * @var WpProQuiz_Model_GlobalSettings */ private $_settings = null; public function __construct() { $this->loadSettings(); add_action('wp_enqueue_scripts', array($this, 'loadDefaultScripts')); add_shortcode('LDAdvQuiz', array($this, 'shortcode')); add_shortcode('LDAdvQuiz_toplist', array($this, 'shortcodeToplist')); } public function loadDefaultScripts() { global $learndash_assets_loaded; wp_enqueue_script('jquery'); //wp_enqueue_style( // 'wpProQuiz_front_style', // plugins_url('css/wpProQuiz_front' . leardash_min_asset() .'.css', WPPROQUIZ_FILE), // array(), // LEARNDASH_SCRIPT_VERSION_TOKEN //); //wp_style_add_data( 'wpProQuiz_front_style', 'rtl', 'replace' ); //$learndash_assets_loaded['styles']['wpProQuiz_front_style'] = __FUNCTION__; $filepath = SFWD_LMS::get_template( 'learndash_quiz_front.css', null, null, true ); if ( !empty( $filepath ) ) { wp_enqueue_style( 'learndash_quiz_front_css', learndash_template_url_from_path( $filepath ), array(), LEARNDASH_SCRIPT_VERSION_TOKEN ); wp_style_add_data( 'learndash_quiz_front_css', 'rtl', 'replace' ); $learndash_assets_loaded['styles']['learndash_quiz_front_css'] = __FUNCTION__; } if($this->_settings->isJsLoadInHead()) { $this->loadJsScripts(false, true, true); } } private function loadJsScripts($footer = true, $quiz = true, $toplist = false) { global $learndash_assets_loaded; if ($quiz) { wp_enqueue_script( 'wpProQuiz_front_javascript', plugins_url('js/wpProQuiz_front' . leardash_min_asset() .'.js', WPPROQUIZ_FILE), array('jquery', 'jquery-ui-sortable'), LEARNDASH_SCRIPT_VERSION_TOKEN, $footer ); $learndash_assets_loaded['scripts']['wpProQuiz_front_javascript'] = __FUNCTION__; wp_localize_script('wpProQuiz_front_javascript', 'WpProQuizGlobal', array( 'ajaxurl' => str_replace(array("http:", "https:"), array("",""), admin_url('admin-ajax.php')), 'loadData' => esc_html__('Loading', 'learndash'), 'questionNotSolved' => esc_html__('You must answer this question.', 'learndash'), 'questionsNotSolved' => sprintf( esc_html_x('You must answer all questions before you can complete the %s.', 'You must answer all questions before you can complete the quiz.', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ), 'fieldsNotFilled' => esc_html__('All fields have to be filled.', 'learndash') )); wp_enqueue_script( 'jquery-cookie', plugins_url('js/jquery.cookie' . leardash_min_asset() .'.js', WPPROQUIZ_FILE), array('jquery', 'jquery-ui-sortable'), '1.4.0', $footer ); $learndash_assets_loaded['scripts']['jquery-cookie'] = __FUNCTION__; } if ($toplist) { wp_enqueue_script( 'wpProQuiz_front_javascript_toplist', plugins_url('js/wpProQuiz_toplist'. leardash_min_asset() .'.js', WPPROQUIZ_FILE), array('jquery', 'jquery-ui-sortable'), LEARNDASH_SCRIPT_VERSION_TOKEN, $footer ); $learndash_assets_loaded['scripts']['wpProQuiz_front_javascript_toplist'] = __FUNCTION__; if (!wp_script_is('wpProQuiz_front_javascript') ) { wp_localize_script( 'wpProQuiz_front_javascript_toplist', 'WpProQuizGlobal', array( 'ajaxurl' => str_replace(array("http:", "https:"), array("",""), admin_url('admin-ajax.php')), 'loadData' => esc_html__('Loading', 'learndash'), 'questionNotSolved' => esc_html__('You must answer this question.', 'learndash'), 'questionsNotSolved' => sprintf( esc_html_x('You must answer all questions before you can complete the %s.', 'You must answer all questions before you can complete the quiz.', 'learndash'), learndash_get_custom_label_lower( 'quiz' )), 'fieldsNotFilled' => esc_html__('All fields have to be filled.', 'learndash') ) ); } } if(!$this->_settings->isTouchLibraryDeactivate()) { wp_enqueue_script( 'jquery-ui-touch-punch', plugins_url('js/jquery.ui.touch-punch.min.js', WPPROQUIZ_FILE), array('jquery', 'jquery-ui-sortable'), '0.2.2', $footer ); $learndash_assets_loaded['scripts']['jquery-ui-touch-punch'] = __FUNCTION__; } } public function shortcode($attr = array(), $content = '' ) { global $learndash_shortcode_used, $learndash_shortcode_atts; $learndash_shortcode_used = true; if ( ( isset( $attr[0] ) ) && ( ! empty( $attr[0] ) ) ) { if ( ! isset( $attr['quiz_pro_id'] ) ) { $attr['quiz_pro_id'] = intval( $attr[0] ); unset( $attr[0] ); } } $attr = shortcode_atts( array( 'quiz_id' => 0, 'course_id' => 0, 'lesson_id' => 0, 'topic_id' => 0, 'quiz_pro_id' => 0, ), $attr ); // Just to ensure compliance. $attr['quiz_id'] = absint( $attr['quiz_id'] ); $attr['course_id'] = absint( $attr['course_id'] ); $attr['lesson_id'] = absint( $attr['lesson_id'] ); $attr['topic_id'] = absint( $attr['topic_id'] ); $attr['quiz_pro_id'] = absint( $attr['quiz_pro_id'] ); if ( ! $this->_settings->isJsLoadInHead() ) { $this->loadJsScripts(); } if ( ! empty( $attr['quiz_pro_id'] ) ) { ob_start(); $learndash_shortcode_atts['LDAdvQuiz'] = $attr; $this->handleShortCode( $attr ); $content = ob_get_contents(); ob_end_clean(); } if($this->_settings->isAddRawShortcode()) { return '[raw]'.$content.'[/raw]'; } return $content; } public function handleShortCode( $atts = array() ) { $atts = shortcode_atts( array( 'quiz_id' => 0, 'course_id' => 0, 'lesson_id' => 0, 'topic_id' => 0, 'quiz_pro_id' => 0, ), $atts ); // Just to ensure compliance. $atts['quiz_id'] = absint( $atts['quiz_id'] ); $atts['course_id'] = absint( $atts['course_id'] ); $atts['lesson_id'] = absint( $atts['lesson_id'] ); $atts['topic_id'] = absint( $atts['topic_id'] ); $atts['quiz_pro_id'] = absint( $atts['quiz_pro_id'] ); $view = new WpProQuiz_View_FrontQuiz(); $view->set_shortcode_atts( $atts ); $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $quiz = $quizMapper->fetch( $atts['quiz_pro_id'] ); $quiz_post_id = $quiz->getPostId(); if ( ( ! empty( $atts['quiz_id'] ) ) && ( intval( $quiz_post_id ) !== intval( $atts['quiz_id'] ) ) ) { $quiz->setPostId( intval( $atts['quiz_id'] ) ); } $maxQuestion = false; if ( ( $quiz->isShowMaxQuestion() ) && ( $quiz->getShowMaxQuestionValue() > 0 ) ) { $value = $quiz->getShowMaxQuestionValue(); if ( $quiz->isShowMaxQuestionPercent() ) { $count = $questionMapper->count( $atts['quiz_pro_id'] ); $value = ceil( $count * $value / 100 ); } //$question = $questionMapper->fetchAll( $atts['quiz_pro_id'], true, $value ); $question = $questionMapper->fetchAll( $quiz, true, $value ); $maxQuestion = true; } else { //$question = $questionMapper->fetchAll( $atts['quiz_pro_id'] ); $question = $questionMapper->fetchAll( $quiz ); } if ( ( empty( $quiz ) ) || ( empty( $question ) ) ) { echo ''; return; } $view->quiz = $quiz; $view->question = $question; $view->category = $categoryMapper->fetchByQuiz( $quiz ); $view->forms = $formMapper->fetch( $atts['quiz_pro_id'] ); if ( $maxQuestion ) { $view->showMaxQuestion(); } else { $view->show(); } } public function shortcodeToplist($attr) { global $learndash_shortcode_used; $learndash_shortcode_used = true; $id = $attr[0]; $content = ''; if(!$this->_settings->isJsLoadInHead()) { $this->loadJsScripts(true, false, true); } if(is_numeric($id)) { ob_start(); $this->handleShortCodeToplist($id, isset($attr['q'])); $content = ob_get_contents(); ob_end_clean(); } if($this->_settings->isAddRawShortcode() && !isset($attr['q'])) { return '[raw]'.$content.'[/raw]'; } return $content; } private function handleShortCodeToplist($quizId, $inQuiz = false) { $quizMapper = new WpProQuiz_Model_QuizMapper(); $view = new WpProQuiz_View_FrontToplist(); $quiz = $quizMapper->fetch($quizId); if($quiz->getId() <= 0 || !$quiz->isToplistActivated()) { echo ''; return; } $view->quiz = $quiz; $view->points = $quizMapper->sumQuestionPoints($quizId); $view->inQuiz = $inQuiz; $view->show(); } private function loadSettings() { $mapper = new WpProQuiz_Model_GlobalSettingsMapper(); $this->_settings = $mapper->fetchAll(); } public static function ajaxQuizLoadData($data, $func) { if (is_user_logged_in() ) $user_id = get_current_user_id(); else $user_id = 0; if ( isset( $data['quizId'] ) ) $id = $data['quizId']; else $id = 0; if ( isset( $data['quiz'] ) ) $quiz_post_id = $data['quiz']; else $quiz_post_id = 0; if ( ( !isset( $data['quiz_nonce'] ) ) || ( !wp_verify_nonce( $data['quiz_nonce'], 'sfwd-quiz-nonce-' . $quiz_post_id . '-'. $id .'-'. $user_id ) ) ) { //wp_send_json_error(); die(); } $view = new WpProQuiz_View_FrontQuiz(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $quiz = $quizMapper->fetch($id); $quiz->setPostId( absint( $quiz_post_id ) ); if ( $quiz->isShowMaxQuestion() && $quiz->getShowMaxQuestionValue() > 0) { $value = $quiz->getShowMaxQuestionValue(); if($quiz->isShowMaxQuestionPercent()) { $count = $questionMapper->count($id); $value = ceil($count * $value / 100); } $question = $questionMapper->fetchAll( $quiz, true, $value ); } else { $question = $questionMapper->fetchAll($quiz); } if(empty($quiz) || empty($question)) { return null; } $view->quiz = $quiz; $view->question = $question; $view->category = $categoryMapper->fetchByQuiz( $quiz ); $view->forms = $formMapper->fetch($quiz->getId()); return json_encode($view->getQuizData()); } } lib/controller/WpProQuiz_Controller_Template.php 0000666 00000001406 15214236625 0016177 0 ustar 00 <?php class WpProQuiz_Controller_Template { public static function ajaxEditTemplate($data, $func) { if(!current_user_can('wpProQuiz_edit_quiz')) { return json_encode(array()); } $templateMapper = new WpProQuiz_Model_TemplateMapper(); $template = new WpProQuiz_Model_Template($data); $templateMapper->updateName($template->getTemplateId(), $template->getName()); return json_encode(array()); } public static function ajaxDeleteTemplate($data, $func) { if(!current_user_can('wpProQuiz_edit_quiz')) { return json_encode(array()); } $templateMapper = new WpProQuiz_Model_TemplateMapper(); $template = new WpProQuiz_Model_Template($data); $templateMapper->delete($template->getTemplateId()); return json_encode(array()); } } lib/controller/WpProQuiz_Controller_Admin.php 0000666 00000024065 15214236625 0015462 0 ustar 00 <?php class WpProQuiz_Controller_Admin { protected $_ajax; public function __construct() { $this->_ajax = new WpProQuiz_Controller_Ajax(); $this->_ajax->init(); //deprecated - use WpProQuiz_Controller_Ajax add_action('wp_ajax_wp_pro_quiz_update_sort', array($this, 'updateSort')); add_action('wp_ajax_wp_pro_quiz_load_question', array($this, 'updateSort')); add_action('wp_ajax_wp_pro_quiz_reset_lock', array($this, 'resetLock')); add_action('wp_ajax_wp_pro_quiz_load_toplist', array($this, 'adminToplist')); add_action('wp_ajax_wp_pro_quiz_completed_quiz', array($this, 'completedQuiz')); add_action('wp_ajax_nopriv_wp_pro_quiz_completed_quiz', array($this, 'completedQuiz')); add_action('wp_ajax_wp_pro_quiz_check_lock', array($this, 'quizCheckLock')); add_action('wp_ajax_nopriv_wp_pro_quiz_check_lock', array($this, 'quizCheckLock')); //0.19 add_action('wp_ajax_wp_pro_quiz_add_toplist', array($this, 'addInToplist')); add_action('wp_ajax_nopriv_wp_pro_quiz_add_toplist', array($this, 'addInToplist')); add_action('wp_ajax_wp_pro_quiz_show_front_toplist', array($this, 'showFrontToplist')); add_action('wp_ajax_nopriv_wp_pro_quiz_show_front_toplist', array($this, 'showFrontToplist')); add_action('wp_ajax_wp_pro_quiz_load_quiz_data', array($this, 'loadQuizData')); add_action('wp_ajax_nopriv_wp_pro_quiz_load_quiz_data', array($this, 'loadQuizData')); add_action('admin_menu', array($this, 'register_page')); } public function loadQuizData() { $q = new WpProQuiz_Controller_Quiz(); echo json_encode($q->loadQuizData()); exit; } public function adminToplist() { $t = new WpProQuiz_Controller_Toplist(); $t->route(); exit; } public function showFrontToplist() { $t = new WpProQuiz_Controller_Toplist(); $t->showFrontToplist(); exit; } public function addInToplist() { $t = new WpProQuiz_Controller_Toplist(); $t->addInToplist(); exit; } public function resetLock() { if ( ( isset( $_GET['post'] ) ) && ( !isset( $_GET['id'] ) ) ) { $_GET['id'] = get_post_meta( $_GET['post'], 'quiz_pro_id', true ); } $c = new WpProQuiz_Controller_Quiz(); $c->route(); } public function quizCheckLock() { $quizController = new WpProQuiz_Controller_Quiz(); echo json_encode($quizController->isLockQuiz($_POST['quizId'])); exit; } public function updateSort() { $c = new WpProQuiz_Controller_Question(); $c->route(); } public function completedQuiz() { // First we unpack the $_POST['results'] string if ( ( isset( $_POST['results'] ) ) && ( !empty( $_POST['results'] ) ) && ( is_string( $_POST['results'] ) ) ) { $_POST['results'] = json_decode(stripslashes($_POST['results']), true); } if ( is_user_logged_in() ) $user_id = get_current_user_id(); else $user_id = 0; if ( isset( $_POST['quizId'] ) ) $id = $_POST['quizId']; else $id = 0; if ( isset( $_POST['quiz'] ) ) $quiz_post_id = $_POST['quiz']; else $quiz_post_id = 0; // LD 2.4.3 - Change in logic. Instead of accepting the values for points, correct etc from JS we now pass the 'results' array on the complete quiz // AJAX action. This now let's us verify the points, correct answers etc. as each have a unique nonce. $total_awarded_points = 0; $total_correct = 0; // If the results is not present then abort. if ( !isset( $_POST['results'] ) ) { return array('text' => esc_html__('An error has occurred.', 'learndash'), 'clear' => true); } // Loop over the 'results' items. We verify and tally the points+correct counts as well as the student response 'data'. When we get to the 'comp' results element // we set the award points and correct as well as determine the total possible points. // @TODO Need to test how this works with variabel question quizzes. foreach( $_POST['results'] as $r_idx => $result ) { if ( $r_idx == 'comp' ) { $_POST['results'][$r_idx]['points'] = intval( $total_awarded_points ); $_POST['results'][$r_idx]['correctQuestions'] = intval( $total_correct ); //$quizMapper = new WpProQuiz_Model_QuizMapper(); //$total_possible_points = $quizMapper->sumQuestionPoints( $id ); //$_POST['results'][$r_idx]['possiblePoints'] = intval( $total_possible_points ); //$_POST['results'][$r_idx]['result'] = round( intval( $_POST['results'][$r_idx]['points'] ) / intval( $_POST['results'][$r_idx]['possiblePoints'] ) * 100, 2 ); continue; } $points_array = array( 'points' => intval( $result['points'] ), 'correct' => intval( $result['correct'] ), 'possiblePoints' => intval( $result['possiblePoints'] ) ); if ( $points_array['correct'] === false ) $points_array['correct'] = 0; else if ( $points_array['correct'] === true ) $points_array['correct'] = 1; $points_str = maybe_serialize( $points_array ); if ( !wp_verify_nonce( $result['p_nonce'], 'ld_quiz_pnonce'. $user_id .'_'. $id .'_'. $quiz_post_id .'_'. $r_idx .'_'. $points_str ) ) { $_POST['results'][$r_idx]['points'] = 0; $_POST['results'][$r_idx]['correct'] = 0; $_POST['results'][$r_idx]['possiblePoints'] = 0; } $total_awarded_points += intval( $_POST['results'][$r_idx]['points'] ); $total_correct += $_POST['results'][$r_idx]['correct']; $response_str = maybe_serialize( $result['data'] ); if ( !wp_verify_nonce( $result['a_nonce'], 'ld_quiz_anonce'. $user_id .'_'. $id .'_'. $quiz_post_id .'_'. $r_idx .'_'. $response_str ) ) { $_POST['results'][$r_idx]['data'] = array(); } } $quiz = new WpProQuiz_Controller_Quiz(); $quiz->completedQuiz(); } private function localizeScript() { global $wp_locale; $isRtl = isset($wp_locale->is_rtl) ? $wp_locale->is_rtl : false; $translation_array = array( 'delete_msg' => sprintf( esc_html_x('Do you really want to delete the %s/question?', 'Do you really want to delete the quiz/question?', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ), 'no_title_msg' => esc_html__('Title is not filled!', 'learndash'), 'no_question_msg' => esc_html__('No question deposited!', 'learndash'), 'no_correct_msg' => esc_html__('Correct answer was not selected!', 'learndash'), 'no_answer_msg' => esc_html__('No answer deposited!', 'learndash'), 'no_quiz_start_msg' => sprintf( esc_html_x('No %s description filled!', 'No quiz description filled!', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ), 'fail_grade_result' => esc_html__('The percent values in result text are incorrect.', 'learndash'), 'no_nummber_points' => esc_html__('No number in the field "Points" or less than 1', 'learndash'), 'no_nummber_points_new' => esc_html__('No number in the field "Points" or less than 0', 'learndash'), 'no_selected_quiz' => sprintf( esc_html_x('No %s selected', 'No quiz selected', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ), 'reset_statistics_msg' => esc_html__('Do you really want to reset the statistic?', 'learndash'), 'no_data_available' => esc_html__('No data available', 'learndash'), 'no_sort_element_criterion' => esc_html__('No sort element in the criterion', 'learndash'), 'dif_points' => esc_html__('"Different points for every answer" is not possible at "Free" choice', 'learndash'), 'category_no_name' => esc_html__('You must specify a name.', 'learndash'), 'confirm_delete_entry' => esc_html__('This entry should really be deleted?', 'learndash'), 'not_all_fields_completed' => esc_html__('Not all fields completed.', 'learndash'), 'temploate_no_name' => esc_html__('You must specify a template name.', 'learndash'), 'no_delete_answer' => esc_html__('Cannot delete only answer', 'learndash'), 'closeText' => esc_html__('Close', 'learndash'), 'currentText' => esc_html__('Today', 'learndash'), 'monthNames' => array_values($wp_locale->month), 'monthNamesShort' => array_values($wp_locale->month_abbrev), 'dayNames' => array_values($wp_locale->weekday), 'dayNamesShort' => array_values($wp_locale->weekday_abbrev), 'dayNamesMin' => array_values($wp_locale->weekday_initial), 'dateFormat' => WpProQuiz_Helper_Until::convertPHPDateFormatToJS(get_option('date_format', 'm/d/Y')), 'firstDay' => get_option('start_of_week'), 'isRTL' => $isRtl ); wp_localize_script('wpProQuiz_admin_javascript', 'wpProQuizLocalize', $translation_array); } public function enqueueScript() { global $learndash_assets_loaded; wp_enqueue_script( 'wpProQuiz_admin_javascript', plugins_url('js/wpProQuiz_admin'. leardash_min_asset() .'.js', WPPROQUIZ_FILE), array('jquery', 'jquery-ui-sortable', 'jquery-ui-datepicker'), LEARNDASH_SCRIPT_VERSION_TOKEN ); $learndash_assets_loaded['scripts']['wpProQuiz_admin_javascript'] = __FUNCTION__; $this->localizeScript(); } public function register_page() { $quiz_title = sprintf( esc_html_x('Advanced %s', 'Advanced Quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); $page = add_submenu_page( "edit.php?post_type=sfwd-quiz", $quiz_title, $quiz_title, "wpProQuiz_show", "ldAdvQuiz", array($this, 'route') ); add_action('admin_print_scripts-'.$page, array($this, 'enqueueScript')); } public function route() { $module = isset($_GET['module']) ? $_GET['module'] : 'overallView'; $c = null; switch ($module) { case 'overallView': $c = new WpProQuiz_Controller_Quiz(); break; case 'question': $c = new WpProQuiz_Controller_Question(); break; case 'preview': $c = new WpProQuiz_Controller_Preview(); break; case 'statistics': $c = new WpProQuiz_Controller_Statistics(); break; case 'importExport': $c = new WpProQuiz_Controller_ImportExport(); break; case 'globalSettings': $c = new WpProQuiz_Controller_GlobalSettings(); break; case 'styleManager': $c = new WpProQuiz_Controller_StyleManager(); break; case 'toplist': $c = new WpProQuiz_Controller_Toplist(); break; case 'wpq_support': $c = new WpProQuiz_Controller_WpqSupport(); break; } if($c !== null) { $c->route(); } } } lib/controller/WpProQuiz_Controller_Controller.php 0000666 00000000541 15214236625 0016546 0 ustar 00 <?php class WpProQuiz_Controller_Controller { protected $_post = null; protected $_cookie = null; /** * @deprecated */ public function __construct() { if($this->_post === null) { $this->_post = stripslashes_deep($_POST); } if($this->_cookie === null && $_COOKIE !== null) { $this->_cookie = stripslashes_deep($_COOKIE); } } } lib/controller/WpProQuiz_Controller_Category.php 0000666 00000002253 15214236625 0016202 0 ustar 00 <?php class WpProQuiz_Controller_Category { public static function ajaxAddCategory($data, $func) { if(!current_user_can('wpProQuiz_edit_quiz')) { return json_encode( array() ); } $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $category = new WpProQuiz_Model_Category( $data ); $categoryMapper->save( $category ); return json_encode( array( 'categoryId' => $category->getCategoryId(), 'categoryName' => stripslashes( $category->getCategoryName() ), ) ); } public static function ajaxEditCategory($data, $func) { if(!current_user_can('wpProQuiz_edit_quiz')) { return json_encode(array()); } $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $category = new WpProQuiz_Model_Category($data); $categoryMapper->save($category); return json_encode(array()); } public static function ajaxDeleteCategory($data, $func) { if(!current_user_can('wpProQuiz_edit_quiz')) { return json_encode(array()); } $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $category = new WpProQuiz_Model_Category($data); $categoryMapper->delete($category->getCategoryId()); return json_encode(array()); } } lib/controller/WpProQuiz_Controller_Preview.php 0000666 00000005424 15214236625 0016051 0 ustar 00 <?php class WpProQuiz_Controller_Preview extends WpProQuiz_Controller_Controller { public function route() { global $learndash_assets_loaded; wp_enqueue_script( 'wpProQuiz_front_javascript', plugins_url('js/wpProQuiz_front'. leardash_min_asset() .'.js', WPPROQUIZ_FILE), array('jquery', 'jquery-ui-sortable'), LEARNDASH_SCRIPT_VERSION_TOKEN ); $learndash_assets_loaded['scripts']['wpProQuiz_front_javascript'] = __FUNCTION__; wp_localize_script('wpProQuiz_front_javascript', 'WpProQuizGlobal', array( 'ajaxurl' => str_replace(array("http:", "https:"), array("",""), admin_url('admin-ajax.php')), 'loadData' => esc_html__('Loading', 'learndash'), 'questionNotSolved' => esc_html__('You must answer this question.', 'learndash'), 'questionsNotSolved' => sprintf( esc_html_x('You must answer all questions before you can complete the %s.', 'You must answer all questions before you can complete the quiz.', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ), 'fieldsNotFilled' => esc_html__('All fields have to be filled.', 'learndash') )); //wp_enqueue_style( // 'wpProQuiz_front_style', // plugins_url('css/wpProQuiz_front'. leardash_min_asset() .'.css', WPPROQUIZ_FILE), // array(), // LEARNDASH_SCRIPT_VERSION_TOKEN //); //wp_style_add_data( 'wpProQuiz_front_style', 'rtl', 'replace' ); //$learndash_assets_loaded['styles']['wpProQuiz_front_style'] = __FUNCTION__; $filepath = SFWD_LMS::get_template( 'learndash_quiz_front.css', null, null, true ); if ( !empty( $filepath ) ) { wp_enqueue_style( 'learndash_quiz_front_css', learndash_template_url_from_path( $filepath ), array(), LEARNDASH_SCRIPT_VERSION_TOKEN ); wp_style_add_data( 'learndash_quiz_front_css', 'rtl', 'replace' ); $learndash_assets_loaded['styles']['learndash_quiz_front_css'] = __FUNCTION__; } $this->showAction($_GET['id']); } public function showAction($id) { $view = new WpProQuiz_View_FrontQuiz(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $quiz = $quizMapper->fetch($id); if($quiz->isShowMaxQuestion() && $quiz->getShowMaxQuestionValue() > 0) { $value = $quiz->getShowMaxQuestionValue(); if($quiz->isShowMaxQuestionPercent()) { $count = $questionMapper->count($id); $value = ceil($count * $value / 100); } $question = $questionMapper->fetchAll($quiz, true, $value); } else { $question = $questionMapper->fetchAll($id); } $view->quiz = $quiz; $view->question = $question; $view->category = $categoryMapper->fetchByQuiz( $quiz ); $view->forms = $formMapper->fetch($quiz->getId()); $view->show(true); } } lib/controller/WpProQuiz_Controller_QuizCompleted.php 0000666 00000022567 15214236625 0017224 0 ustar 00 <?php class WpProQuiz_Controller_QuizCompleted { private $data = array(); public function __construct($data) { $this->data = $data; } public static function ajaxQuizCompleted($data, $func) { $completed = new WpProQuiz_Controller_QuizCompleted($data); return $completed->quizCompleted(); } public function quizCompleted() { $lockMapper = new WpProQuiz_Model_LockMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $statistics = new WpProQuiz_Controller_Statistics(); $quiz = $quizMapper->fetch($this->data['quizId']); if($quiz === null || $quiz->getId() <= 0) { return; } $categories = $categoryMapper->fetchByQuiz( $quiz ); $userId = get_current_user_id(); $resultInPercent = floor($this->data['results']['comp']['result']); $this->setResultCookie($quiz); $this->emailNote($quiz, $this->data['results']['comp'], $categories); if(!$this->isPreLockQuiz($quiz)) { $statistics->save(); do_action('wp_pro_quiz_completed_quiz'); do_action('wp_pro_quiz_completed_quiz_'.$resultInPercent.'_percent'); return; } $lockMapper->deleteOldLock(60*60*24*7, $this->_post['quizId'], time(), WpProQuiz_Model_Lock::TYPE_QUIZ, 0); $lockIp = $lockMapper->isLock($this->_post['quizId'], $this->getIp(), get_current_user_id(), WpProQuiz_Model_Lock::TYPE_QUIZ); $lockCookie = false; $cookieTime = $quiz->getQuizRunOnceTime(); $cookieJson = null; if(isset($this->_cookie['wpProQuiz_lock']) && get_current_user_id() == 0 && $quiz->isQuizRunOnceCookie()) { $cookieJson = json_decode($this->_cookie['wpProQuiz_lock'], true); if($cookieJson !== false) { if(isset($cookieJson[$this->_post['quizId']]) && $cookieJson[$this->_post['quizId']] == $cookieTime) { $lockCookie = true; } } } if(!$lockIp && !$lockCookie) { $statistics->save(); do_action('wp_pro_quiz_completed_quiz'); do_action('wp_pro_quiz_completed_quiz_'.$resultInPercent.'_percent'); if(get_current_user_id() == 0 && $quiz->isQuizRunOnceCookie()) { $cookieData = array(); if($cookieJson !== null || $cookieJson !== false) { $cookieData = $cookieJson; } $cookieData[$this->_post['quizId']] = $quiz->getQuizRunOnceTime(); $url = parse_url(get_bloginfo( 'url' )); setcookie('wpProQuiz_lock', json_encode($cookieData), time() + 60*60*24*60, empty($url['path']) ? '/' : $url['path']); } $lock = new WpProQuiz_Model_Lock(); $lock->setUserId(get_current_user_id()); $lock->setQuizId($this->_post['quizId']); $lock->setLockDate(time()); $lock->setLockIp($this->getIp()); $lock->setLockType(WpProQuiz_Model_Lock::TYPE_QUIZ); $lockMapper->insert($lock); } return; } private function setResultCookie(WpProQuiz_Model_Quiz $quiz) { $prerequisite = new WpProQuiz_Model_PrerequisiteMapper(); if(get_current_user_id() == 0 && $prerequisite->isQuizId($quiz->getId())) { $cookieData = array(); if(isset($this->_cookie['wpProQuiz_result'])) { $d = json_decode($this->_cookie['wpProQuiz_result'], true); if($d !== null && is_array($d)) { $cookieData = $d; } } $cookieData[$quiz->getId()] = 1; $url = parse_url(get_bloginfo( 'url' )); setcookie('wpProQuiz_result', json_encode($cookieData), time() + 60*60*24*300, empty($url['path']) ? '/' : $url['path']); } } private function emailNote(WpProQuiz_Model_Quiz $quiz, $result, $categories) { $globalMapper = new WpProQuiz_Model_GlobalSettingsMapper(); $adminEmail = $globalMapper->getEmailSettings(); $userEmail = $globalMapper->getUserEmailSettings(); $user = wp_get_current_user(); $r = array( '$userId' => $user->ID, '$username' => $user->display_name, '$quizname' => $quiz->getName(), '$result' => $result['result'].'%', '$points' => $result['points'], '$ip' => filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP), '$categories' => empty($result['cats']) ? '' : $this->setCategoryOverview($result['cats'], $categories) ); if($user->ID == 0) { $r['$username'] = $r['$ip']; } if($quiz->isUserEmailNotification()) { $msg = str_replace(array_keys($r), $r, $userEmail['message']); $headers = ''; //if(!empty($userEmail['from'])) { // $headers = 'From: '.$userEmail['from']; //} if ( ( isset( $userEmail['from'] ) ) && ( !empty( $userEmail['from'] ) ) && ( is_email( $userEmail['from'] ) ) ) { if ( ( !isset( $userEmail['from_name'] ) ) || ( empty( $userEmail['from_name'] ) ) ) { $userEmail['from_name'] = ''; $email_user = get_user_by('emal', $userEmail['from'] ); if ( ( $email_user ) && ( $email_user instanceof WP_User ) ) { $userEmail['from_name'] = $email_user->display_name; } } $headers .= 'From: '; if ( ( isset( $userEmail['from_name'] ) ) && ( !empty( $userEmail['from_name'] ) ) ) { $headers .= $userEmail['from_name'] .' <'. $userEmail['from'] .'>'; } else { $headers .= $userEmail['from']; } } if($userEmail['html']) add_filter('wp_mail_content_type', array($this, 'htmlEmailContent')); $email_params = array( "email" => $user->user_email, "subject" => $userEmail['subject'], "msg" => $msg, "headers" => $headers ); $email_params = apply_filters("learndash_quiz_completed_email", $email_params, $quiz); wp_mail($email_params["email"], $email_params["subject"], $email_params["msg"], $email_params["headers"]); if($userEmail['html']) remove_filter('wp_mail_content_type', array($this, 'htmlEmailContent')); } if($quiz->getEmailNotification() == WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_ALL || (get_current_user_id() > 0 && $quiz->getEmailNotification() == WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_REG_USER)) { $msg = str_replace(array_keys($r), $r, $adminEmail['message']); $headers = ''; //if(!empty($adminEmail['from'])) { // $headers = 'From: '.$adminEmail['from']; //} if ( ( !isset( $adminEmail['from'] ) ) || ( empty( $adminEmail['from'] ) ) || ( !is_email( $adminEmail['from'] ) ) ) { $adminEmail['from'] = get_option( 'admin_email' ); } if ( ( !isset( $adminEmail['from_name'] ) ) || ( empty( $adminEmail['from_name'] ) ) ) { $adminEmail['from_name'] = ''; if ( !empty( $adminEmail['from'] ) ) { $email_user = get_user_by('emal', $adminEmail['from'] ); if ( ( $email_user ) && ( $email_user instanceof WP_User ) ) { $adminEmail['from_name'] = $email_user->display_name; } } } if ( !empty( $adminEmail['from'] ) ) { $headers .= 'From: '; if ( ( isset( $adminEmail['from_name'] ) ) && ( !empty( $adminEmail['from_name'] ) ) ) { $headers .= $adminEmail['from_name'] .' <'. $adminEmail['from'] .'>'; } else { $headers .= $adminEmail['from']; } } if(isset($adminEmail['html']) && $adminEmail['html']) add_filter('wp_mail_content_type', array($this, 'htmlEmailContent')); $email_params = array( "email" => $adminEmail['to'], "subject" => $adminEmail['subject'], "msg" => $msg, "headers" => $headers ); $email_params = apply_filters("learndash_quiz_completed_email_admin", $email_params, $quiz); wp_mail($email_params["email"], $email_params["subject"], $email_params["msg"], $email_params["headers"]); //wp_mail($adminEmail['to'], $adminEmail['subject'], $msg, $headers); if(isset($adminEmail['html']) && $adminEmail['html']) remove_filter('wp_mail_content_type', array($this, 'htmlEmailContent')); } } public function htmlEmailContent($contentType) { return 'text/html'; } private function setCategoryOverview( $category_scores = array() , $question_cats = array() ) { if ( ( ! empty( $category_scores ) ) && ( ! empty( $question_cats ) ) ) { $question_categories = array(); foreach ( $question_cats as $cat ) { if ( ! $cat->getCategoryId() ) { $cat->setCategoryName( esc_html__( 'Not categorized', 'learndash' ) ); } $question_categories[ $cat->getCategoryId() ] = $cat->getCategoryName(); } } $output = SFWD_LMS::get_template( 'quiz_result_categories_email.php', array( 'question_categories' => $question_categories, 'category_scores' => $category_scores, ) ); return $output; //$cats = array(); // //foreach($categories as $cat) { // /* @var $cat WpProQuiz_Model_Category */ // // if(!$cat->getCategoryId()) { // $cat->setCategoryName(__('Not categorized', 'learndash')); // } // // $cats[$cat->getCategoryId()] = $cat->getCategoryName(); //} // //$a = esc_html__('Categories', 'learndash').":\n"; // //foreach($catArray as $id => $value) { // if(!isset($cats[$id])) // continue; // // $a .= '* '.str_pad($cats[$id], 35, '.').((float)$value)."%\n"; //} // //return $a; } private function isPreLockQuiz(WpProQuiz_Model_Quiz $quiz) { $userId = get_current_user_id(); if($quiz->isQuizRunOnce()) { switch ($quiz->getQuizRunOnceType()) { case WpProQuiz_Model_Quiz::QUIZ_RUN_ONCE_TYPE_ALL: return true; case WpProQuiz_Model_Quiz::QUIZ_RUN_ONCE_TYPE_ONLY_USER: return $userId > 0; case WpProQuiz_Model_Quiz::QUIZ_RUN_ONCE_TYPE_ONLY_ANONYM: return $userId == 0; } } return false; } private function getIp() { if(get_current_user_id() > 0) return '0'; else return filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP); } } lib/controller/WpProQuiz_Controller_Ajax.php 0000666 00000004614 15214236625 0015313 0 ustar 00 <?php /** * @since 0.23 */ class WpProQuiz_Controller_Ajax { private $_adminCallbacks = array(); private $_frontCallbacks = array(); public function init() { $this->initCallbacks(); add_action('wp_ajax_wp_pro_quiz_admin_ajax', array($this, 'adminAjaxCallback')); add_action('wp_ajax_nopriv_wp_pro_quiz_admin_ajax', array($this, 'frontAjaxCallback')); } public function adminAjaxCallback() { $this->ajaxCallbackHandler(true); } public function frontAjaxCallback() { $this->ajaxCallbackHandler(false); } private function ajaxCallbackHandler($admin) { $func = isset($_POST['func']) ? $_POST['func'] : ''; $data = isset($_POST['data']) ? $_POST['data'] : null; $calls = $admin ? $this->_adminCallbacks : $this->_frontCallbacks; if(isset($calls[$func])) { $r = call_user_func($calls[$func], $data, $func); if($r !== null) echo $r; } exit; } private function initCallbacks() { $this->_adminCallbacks = array( 'categoryAdd' => array('WpProQuiz_Controller_Category', 'ajaxAddCategory'), 'categoryDelete' => array('WpProQuiz_Controller_Category', 'ajaxDeleteCategory'), 'categoryEdit' => array('WpProQuiz_Controller_Category', 'ajaxEditCategory'), 'statisticLoad' => array('WpProQuiz_Controller_Statistics', 'ajaxLoadStatistic'), /** @deprecated **/ 'statisticLoadOverview' => array('WpProQuiz_Controller_Statistics', 'ajaxLoadStatsticOverview'), /** @deprecated **/ 'statisticReset' => array('WpProQuiz_Controller_Statistics', 'ajaxReset'), /** @deprecated **/ 'statisticLoadFormOverview' => array('WpProQuiz_Controller_Statistics', 'ajaxLoadFormOverview'), /** @deprecated **/ 'statisticLoadHistory' => array('WpProQuiz_Controller_Statistics', 'ajaxLoadHistory'), 'statisticLoadUser' => array('WpProQuiz_Controller_Statistics', 'ajaxLoadStatisticUser'), 'statisticResetNew' => array('WpProQuiz_Controller_Statistics', 'ajaxRestStatistic'), 'statisticLoadOverviewNew' => array('WpProQuiz_Controller_Statistics', 'ajaxLoadStatsticOverviewNew'), 'templateEdit' => array('WpProQuiz_Controller_Template', 'ajaxEditTemplate'), 'templateDelete' => array('WpProQuiz_Controller_Template', 'ajaxDeleteTemplate'), 'quizLoadData' => array('WpProQuiz_Controller_Front', 'ajaxQuizLoadData') ); //nopriv $this->_frontCallbacks = array( 'quizLoadData' => array('WpProQuiz_Controller_Front', 'ajaxQuizLoadData') ); } } lib/controller/WpProQuiz_Controller_Statistics.php 0000666 00000065702 15214236625 0016567 0 ustar 00 <?php class WpProQuiz_Controller_Statistics extends WpProQuiz_Controller_Controller { public function route() { $action = (isset($_GET['action'])) ? $_GET['action'] : 'show'; switch ($action) { case 'show': default: $this->show($_GET['id']); } } public function getAverageResult($quizId) { $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); // $quizMapper = new WpProQuiz_Model_QuizMapper(); // $r = $statisticRefMapper->fetchByQuiz($quizId); // $maxPoints = $quizMapper->sumQuestionPoints($quizId); // $sumQuestion = $quizMapper->countQuestion($quizId); // if($r['count'] > 0) { // return round((100 * $r['points'] / ($r['count'] * $maxPoints / $sumQuestion)), 2); // } $result = $statisticRefMapper->fetchFrontAvg($quizId); if(isset($result['g_points']) && $result['g_points']) return round(100 * $result['points'] / $result['g_points'], 2); return 0; } /** * @deprecated */ private function show($quizId) { if(!current_user_can('wpProQuiz_show_statistics')) { wp_die(__('You do not have sufficient permissions to access this page.')); } $this->showNew($quizId); return; $view = new WpProQuiz_View_Statistics(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $quiz = $quizMapper->fetch($quizId); $questions = $questionMapper->fetchAll($quiz); $category = $categoryMapper->fetchAll(); $categoryEmpty = new WpProQuiz_Model_Category(); $categoryEmpty->setCategoryName(__('No category', 'learndash')); $list = array(); $cats = array(); foreach($category as $c) { $cats[$c->getCategoryId()] = $c; } $cats[0] = $categoryEmpty; foreach($questions as $q) { $list[$q->getCategoryId()][] = $q; } $view->quiz = $quizMapper->fetch($quizId); $view->questionList = $list; $view->categoryList = $cats; $view->forms = $formMapper->fetch($quizId); if(has_action('pre_user_query', 'ure_exclude_administrators')) { remove_action('pre_user_query', 'ure_exclude_administrators'); $users = get_users(array('fields' => array('ID','user_login','display_name'))); add_action('pre_user_query', 'ure_exclude_administrators'); } else { $users = get_users(array('fields' => array('ID','user_login','display_name'))); } array_unshift($users, (object)array('ID' => 0)); $view->users = $users; $view->show(); } private function showNew($quizId) { $view = new WpProQuiz_View_StatisticsNew(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $quiz = $quizMapper->fetch($quizId); if(has_action('pre_user_query', 'ure_exclude_administrators')) { remove_action('pre_user_query', 'ure_exclude_administrators'); $users = get_users(array('fields' => array('ID','user_login','display_name'))); add_action('pre_user_query', 'ure_exclude_administrators'); } else { $users = get_users(array('fields' => array('ID','user_login','display_name'))); } $view->quiz = $quiz; $view->users = $users; $view->show(); } /** * * @param WpProQuiz_Model_Quiz $quiz * @return void|boolean */ public function save($quiz = null) { $quizId = $this->_post['quizId']; $array = $this->_post['results']; $lockIp = $this->getIp(); $userId = get_current_user_id(); if($lockIp === false) return false; if($quiz === null) { $quizMapper = new WpProQuiz_Model_QuizMapper(); $quiz = $quizMapper->fetch($quizId); } if(!$quiz->isStatisticsOn()) return false; $values = $this->makeDataList($quiz, $array, $userId, $quiz->getQuizModus()); $formValues = $this->makeFormData($quiz, $userId, isset($this->_post['forms']) ? $this->_post['forms'] : null); if($values === false) return; if($quiz->getStatisticsIpLock() > 0) { $lockMapper = new WpProQuiz_Model_LockMapper(); $lockTime = $quiz->getStatisticsIpLock() * 60; $lockMapper->deleteOldLock($lockTime, $quiz->getId(), time(), WpProQuiz_Model_Lock::TYPE_STATISTIC); if($lockMapper->isLock($quizId, $lockIp, $userId, WpProQuiz_Model_Lock::TYPE_STATISTIC)) return false; $lock = new WpProQuiz_Model_Lock(); $lock ->setQuizId($quizId) ->setLockIp($lockIp) ->setUserId($userId) ->setLockType(WpProQuiz_Model_Lock::TYPE_STATISTIC) ->setLockDate(time()); $lockMapper->insert($lock); } $statisticRefModel = new WpProQuiz_Model_StatisticRefModel(); $statisticRefModel->setCreateTime(time()); $statisticRefModel->setUserId($userId); $statisticRefModel->setQuizId($quizId); $statisticRefModel->setFormData($formValues); $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $statisticRefMapper_id = $statisticRefMapper->statisticSave($statisticRefModel, $values); return $statisticRefMapper_id; } /** * @param WpProQuiz_Model_Quiz $quiz * @param int $userId */ private function makeFormData($quiz, $userId, $data) { if(!$quiz->isFormActivated() || empty($data)) return null; $formMapper = new WpProQuiz_Model_FormMapper(); $forms = $formMapper->fetch($quiz->getId()); if(empty($forms)) return null; $formArray = array(); foreach($forms as $form) { if($form->getType() != WpProQuiz_Model_Form::FORM_TYPE_DATE) { $str = isset($data[$form->getFormId()]) ? $data[$form->getFormId()] : ''; if(WpProQuiz_Helper_Form::valid($form, $str) === false) return null; $formArray[$form->getFormId()] = trim($str); } else { $date = isset($data[$form->getFormId()]) ? $data[$form->getFormId()] : array(); $dateStr = WpProQuiz_Helper_Form::validData($form, $date); if($dateStr === null) return null; $formArray[$form->getFormId()] = $dateStr; } } return $formArray; } private function makeDataList($quiz, $array, $userId, $modus) { $questionMapper = new WpProQuiz_Model_QuestionMapper(); $question = $questionMapper->fetchAllList($quiz, array('id', 'points')); $ids = array(); foreach($question as $q) { if(!isset($array[$q['id']])) continue; $ids[] = $q['id']; $v = $array[$q['id']]; if(!isset($v) || $v['points'] > $q['points'] || $v['points'] < 0) { return false; } } $avgTime = null; if($modus == WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE) { $avgTime = ceil($array['comp']['quizTime'] / count($question)); } unset($array['comp']); $ak = array_keys($array); if(array_diff($ids, $ak) !== array_diff($ak, $ids)) return false; $values = array(); foreach($array as $k => $v) { $s = new WpProQuiz_Model_Statistic(); $s->setQuizId($quiz->getId()); $s->setQuestionId($k); $s->setUserId($userId); $s->setHintCount(isset($v['tip']) ? 1 : 0); $s->setCorrectCount($v['correct'] ? 1 : 0); $s->setIncorrectCount($v['correct'] ? 0 : 1); $s->setPoints($v['points']); $s->setQuestionTime($avgTime === null ? $v['time'] : $avgTime); $s->setAnswerData(isset($v['data']) ? $v['data'] : null); $values[] = $s; } return $values; } private function getIp() { if(get_current_user_id() > 0) return '0'; else return filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP); } /** * @deprecated */ public static function ajaxLoadStatistic($data, $func) { if(!current_user_can('wpProQuiz_show_statistics')) { return json_encode(array()); } $userId = $data['userId']; $quizId = $data['quizId']; $testId = $data['testId']; $maxPoints = 0; $sumQuestion = 0; $inTest = false; $category = array(); $categoryList = array(); $testJson = array(); $formData = null; $statisticMapper = new WpProQuiz_Model_StatisticMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $tests = $statisticRefMapper->fetchAll($quizId, $userId, $testId); $i = 1; foreach($tests as $test) { if($testId == $test->getStatisticRefId()) $inTest = true; $testJson[] = array( 'id' => $test->getStatisticRefId(), 'date' => '#'.$i++.' '.WpProQuiz_Helper_Until::convertTime( $test->getCreateTime(), LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'statistics_time_format' ) //get_option('wpProQuiz_statisticTimeFormat', 'Y/m/d g:i A') ) ); } if(!$inTest) { $data['testId'] = $testId = 0; } if(!$testId) { $statistics = $statisticRefMapper->fetchAvg($quizId, $userId); } else { $statistics = $statisticMapper->fetchAllByRef($testId); $refModel = $statisticRefMapper->fetchByRefId($testId); $formData = $refModel->getFormData(); } $questionData = $questionMapper->fetchAllList($quizId, array('id', 'category_id', 'points')); $empty = array( 'questionId' => 0, 'correct' => 0, 'incorrect' => 0, 'hint' => 0, 'points' => 0, 'result' => 0, 'questionTime' => 0 ); $ca = $sa = array(); $ga = $empty; foreach($questionData as $cc) { $categoryList[$cc['id']] = $cc['category_id']; $c = &$category[$cc['category_id']]; if(empty($c)) { $c = $cc; $c['sum'] = 1; } else { $c['points'] += $cc['points']; $c['sum']++; } $maxPoints += $cc['points']; $sumQuestion++; $sa[$cc['id']] = self::calcTotal($empty); $sa[$cc['id']]['questionId'] = $cc['id']; $ca[$cc['category_id']] = self::calcTotal($empty); } foreach($statistics as $statistic) { $s = $statistic->getCorrectCount() + $statistic->getIncorrectCount(); if($s > 0) { $correct = $statistic->getCorrectCount().' ('.round((100 * $statistic->getCorrectCount() / $s), 2).'%)'; $incorrect = $statistic->getIncorrectCount().' ('.round((100 * $statistic->getIncorrectCount() / $s), 2).'%)'; } else { $incorrect = $correct = '0 (0%)'; } $ga['correct'] += $statistic->getCorrectCount(); $ga['incorrect'] += $statistic->getIncorrectCount(); $ga['hint'] += $statistic->getHintCount(); $ga['points'] += $statistic->getPoints(); $ga['questionTime'] += $statistic->getQuestionTime(); $cats = &$ca[$categoryList[$statistic->getQuestionId()]]; if(!is_array($cats)) { $cats = $empty; } $cats['correct'] += $statistic->getCorrectCount(); $cats['incorrect'] += $statistic->getIncorrectCount(); $cats['hint'] += $statistic->getHintCount(); $cats['points'] += $statistic->getPoints(); $cats['questionTime'] += $statistic->getQuestionTime(); $sa[$statistic->getQuestionId()] = array( 'questionId' => $statistic->getQuestionId(), 'correct' => $correct, 'incorrect' => $incorrect, 'hint' => $statistic->getHintCount(), 'points' => $statistic->getPoints(), 'questionTime' => self::convertToTimeString($statistic->getQuestionTime()) ); } foreach($ca as $catIndex => $cat) { $ca[$catIndex] = self::calcTotal($cat, $category[$catIndex]['points'], $category[$catIndex]['sum']); } $sa[0] = self::calcTotal($ga, $maxPoints, $sumQuestion); return json_encode(array( 'question' => $sa, 'category' => $ca, 'tests' => $testJson, 'testId' => $data['testId'], 'formData' => $formData )); } /** * @deprecated */ public static function ajaxReset($data, $func) { if(!current_user_can('wpProQuiz_reset_statistics')) { return; } $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $quizId = $data['quizId']; $userId = $data['userId']; $testId = $data['testId']; switch ($data['type']) { case 0: $statisticRefMapper->deleteUserTest($quizId, $userId, $testId); break; case 1: $statisticRefMapper->deleteUser($quizId, $userId); break; case 2: $statisticRefMapper->deleteAll($quizId); break; } } /** * @deprecated */ public static function ajaxLoadStatsticOverview($data, $func) { if(!current_user_can('wpProQuiz_show_statistics')) { return json_encode(array()); } $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $quizId = $data['quizId']; $page = (isset($data['page']) && $data['page'] > 0) ? $data['page'] : 1; $limit = $data['pageLimit']; $start = $limit * ($page - 1); $statistics = $statisticRefMapper->fetchOverview($quizId, (bool)$data['onlyCompleted'], $start, $limit); $d = array('items' => array()); $maxPoints = $quizMapper->sumQuestionPoints($quizId); $sumQuestion = $quizMapper->countQuestion($quizId); foreach($statistics as $statistic) { $sum = $statistic->getCorrectCount() + $statistic->getIncorrectCount(); if($sum > 0) { $correct = $statistic->getCorrectCount().' ('.round((100 * $statistic->getCorrectCount() / $sum), 2).'%)'; $incorrect = $statistic->getIncorrectCount().' ('.round((100 * $statistic->getIncorrectCount() / $sum), 2).'%)'; $hint = $statistic->getHintCount(); $result = round((100 * $statistic->getPoints() / ($sum * $maxPoints / $sumQuestion)), 2).'%'; $points = $statistic->getPoints(); $questionTime = self::convertToTimeString($statistic->getQuestionTime()); } else { $questionTime = $points = $result = $hint = $correct = $incorrect = '---'; } $d['items'][] = array( 'userId' => $statistic->getUserId(), 'userName' => $statistic->getUserName(), 'points' => $points, 'correct' => $correct, 'incorrect' => $incorrect, 'hint' => $hint, 'result' => $result, 'questionTime' => $questionTime ); } if(isset($data['nav']) && $data['nav']) { $count = $statisticRefMapper->countOverview($quizId, (bool)$data['onlyCompleted']); $d['page'] = ceil(($count > 0 ? $count : 1) / $limit); } return json_encode($d); } /** * @deprecated */ private static function calcTotal($a, $maxPoints = null, $sumQuestion = null) { $s = $a['correct'] + $a['incorrect']; if($s > 0) { $a['correct'] = $a['correct'].' ('.round((100 * $a['correct'] / $s), 2).'%)'; $a['incorrect'] = $a['incorrect'].' ('.round((100 * $a['incorrect'] / $s), 2).'%)'; if($maxPoints !== null) $a['result'] = round((100 * $a['points'] / ($s * $maxPoints / $sumQuestion)), 2).'%'; } else { $a['result'] = $a['correct'] = $a['incorrect'] = '0 (0%)'; } $a['questionTime'] = self::convertToTimeString($a['questionTime']); return $a; } /** * @deprecated */ private static function convertToTimeString($s) { $h = floor($s / 3600); $s -= $h * 3600; $m = floor($s / 60); $s -= $m * 60; return sprintf("%02d:%02d:%02d", $h, $m, $s); } /** * @deprecated */ public static function ajaxLoadFormOverview($data, $func) { if(!current_user_can('wpProQuiz_show_statistics')) { return json_encode(array()); } $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $quizId = $data['quizId']; $page = (isset($data['page']) && $data['page'] > 0) ? $data['page'] : 1; $limit = $data['pageLimit']; $start = $limit * ($page - 1); $statisticModel = $statisticRefMapper->fetchFormOverview($quizId, $start, $limit, $data['onlyUser']); $items = array(); $maxPoints = $quizMapper->sumQuestionPoints($quizId); $sumQuestion = $quizMapper->countQuestion($quizId); foreach($statisticModel as $model) { /*@var $model WpProQuiz_Model_StatisticFormOverview */ if(!$model->getUserId()) $model->setUserName(__('Anonymous', 'learndash')); $sum = $model->getCorrectCount() + $model->getIncorrectCount(); $result = round((100 * $model->getPoints() / ($sum * $maxPoints / $sumQuestion)), 2).'%'; $items[] = array( 'userName' => $model->getUserName(), 'userId' => $model->getUserId(), 'testId' => $model->getStatisticRefId(), 'date' => WpProQuiz_Helper_Until::convertTime( $model->getCreateTime(), LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'statistics_time_format' ) //get_option('wpProQuiz_statisticTimeFormat', 'Y/m/d g:i A') ), 'result' => $result ); } $d = array('items' => $items); if(isset($data['nav']) && $data['nav']) { $count = $statisticRefMapper->countFormOverview($quizId, $data['onlyUser']); $d['page'] = ceil(($count > 0 ? $count : 1) / $limit); } return json_encode($d); } public static function ajaxLoadHistory($data, $func) { if(!current_user_can('wpProQuiz_show_statistics')) { return json_encode(array()); } $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $quizId = $data['quizId']; $page = (isset($data['page']) && $data['page'] > 0) ? $data['page'] : 1; $limit = $data['pageLimit']; $start = $limit * ($page - 1); $startTime = (int)$data['dateFrom']; $endTime = (int)$data['dateTo'] ? $data['dateTo'] + 86400 : 0; $statisticModel = $statisticRefMapper->fetchHistory($quizId, $start, $limit, $data['users'], $startTime, $endTime); foreach($statisticModel as $model) { /*@var $model WpProQuiz_Model_StatisticHistory */ if(!$model->getUserId()) $model->setUserName(__('Anonymous', 'learndash')); else if($model->getUserName() == '') $model->setUserName(__('Deleted user', 'learndash')); $sum = $model->getCorrectCount() + $model->getIncorrectCount(); $result = round(100 * $model->getPoints() / $model->getGPoints(), 2).'%'; $model->setResult($result); $model->setFormatTime(WpProQuiz_Helper_Until::convertTime( $model->getCreateTime(), LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'statistics_time_format' ) //get_option('wpProQuiz_statisticTimeFormat', 'Y/m/d g:i A') )); $model->setFormatCorrect($model->getCorrectCount().' ('.round(100 * $model->getCorrectCount() / $sum, 2).'%)'); $model->setFormatIncorrect($model->getIncorrectCount().' ('.round(100 * $model->getIncorrectCount() / $sum, 2).'%)'); } $view = new WpProQuiz_View_StatisticsAjax(); $view->historyModel = $statisticModel; $html = $view->getHistoryTable(); $navi = null; if(isset($data['generateNav']) && $data['generateNav']) { $count = $statisticRefMapper->countHistory($quizId, $data['users'], $startTime, $endTime); $navi = ceil(($count > 0 ? $count : 1) / $limit); } return json_encode(array( 'html' => $html, 'navi' => $navi )); } public static function ajaxLoadStatisticUser($data, $func) { // The userId is not passed into this data payload. so for now we set to zero. We will load it via the $statisticRefMapper shortly after $userId = 0; // intval($data['userId']); if ( ( isset( $data['statistic_nonce'] ) ) && ( !empty( $data['statistic_nonce'] ) ) ) { if ( ( isset( $data['userId'] ) ) && ( !empty( $data['userId'] ) ) ) $userId = intval( $data['userId'] ); if ( !wp_verify_nonce( $data['statistic_nonce'], 'statistic_nonce_'. $data['refId'] .'_'. get_current_user_id() .'_'. $userId ) ) { return json_encode(array()); } } else if ( !current_user_can( 'wpProQuiz_show_statistics' ) ) { return json_encode(array()); } $quizId = $data['quizId']; $refId = $data['refId']; $avg = (bool)$data['avg']; $refIdUserId = $avg ? $userId : $refId; $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $statisticModel = $statisticRefMapper->fetchByRefId($refIdUserId, $quizId); if ( $statisticModel instanceof WpProQuiz_Model_StatisticRefModel ) { $userId = $statisticModel->getUserId(); } $statisticUserMapper = new WpProQuiz_Model_StatisticUserMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $statisticUsers = $statisticUserMapper->fetchUserStatistic($refIdUserId, $quizId, $avg); $output = array(); foreach($statisticUsers as $statistic) { if(!isset($output[$statistic->getCategoryId()])) { $output[$statistic->getCategoryId()] = array( 'questions' => array(), 'categoryId' => $statistic->getCategoryId(), 'categoryName' => $statistic->getCategoryId() ? $statistic->getCategoryName() : esc_html__('No category', 'learndash') ); } $o = &$output[$statistic->getCategoryId()]; $question_item = array( 'correct' => $statistic->getCorrectCount(), 'incorrect' => $statistic->getIncorrectCount(), 'hintCount' => $statistic->getHintCount(), 'time' => $statistic->getQuestionTime(), 'points' => $statistic->getPoints(), 'gPoints' => $statistic->getGPoints(), 'statistcAnswerData' => $statistic->getStatisticAnswerData(), 'questionName' => $statistic->getQuestionName(), 'questionAnswerData' => $statistic->getQuestionAnswerData(), 'answerType' => $statistic->getAnswerType(), 'questionId' => $statistic->getQuestionId() ); $questionId = $statistic->getQuestionId(); if ( !empty( $questionId ) ) { $questionMapper = new WpProQuiz_Model_QuestionMapper(); $question = $questionMapper->fetchById( intval( $questionId ) ); if ( ( !empty( $question ) ) && ( $question instanceof WpProQuiz_Model_Question ) ) { $question_item['questionCorrectMsg'] = $question->getCorrectMsg(); $question_item['questionIncorrectMsg'] = $question->getIncorrectMsg(); } } // For the sort_answer items. This worked correctly with LD 2.0.6.8. But in 2.1.x there was a change where // the stored value for 'statistcAnswerData' was not simply keys to match 'questionAnswerData' but md5 value. // This causes a mis-match when viewing statistics data. To complicate things we will have a mix of LD 2.0.6.8 // quiz values and 2.1.x quiz values. if (($question_item['answerType'] == 'sort_answer') || ($question_item['answerType'] == 'matrix_sort_answer')) { if ((isset($question_item['questionAnswerData'])) && (!empty($question_item['questionAnswerData'])) && (isset($question_item['statistcAnswerData'])) && (!empty($question_item['statistcAnswerData']))) { // So first we check the value of the first item from 'statistcAnswerData'. If the value // is a simple int then we can move on. If not, then we have some work to do. $statistcAnswerData_item = $question_item['statistcAnswerData'][0]; if (($statistcAnswerData_item == -1 ) || (strcmp($statistcAnswerData_item, intval($statistcAnswerData_item)) !== 0)) { $questionId = $statistic->getQuestionId(); // Next we loop over the 'questionAnswerData' items. foreach($question_item['questionAnswerData'] as $q_k => $q_v) { // Take the item key and encode it. //$datapos = LD_QuizPro::datapos($questionId, intval($q_k)); // We can't call LD_QuizPro::datapos because is uses current_user which will NOT match the statistic user. $datapos = md5( intval($userId) . $questionId . intval($q_k) ); // If we find that encoded value in the 'statistcAnswerData' we update the value. $s_pos = array_search($datapos, $question_item['statistcAnswerData'], true); if ($s_pos !== false) { $question_item['statistcAnswerData'][$s_pos] = intval($q_k); } } } } } $question_item['result'] = ''; // For essay type questions if the related post (graded_id) is still in the 'not_graded post_status we clear out the incorrect value. // The reason for this is within the statistics logic either the correct or incorrect field is set. In the case of not graded essays // the result is the incorrect field will be set to 1. See LEARNDASH-212 if ( $question_item['answerType'] == 'essay' ) { if ( ( isset( $question_item['statistcAnswerData']['graded_id'] ) ) && ( !empty( $question_item['statistcAnswerData']['graded_id'] ) ) ) { $graded_post = get_post( $question_item['statistcAnswerData']['graded_id'] ); if ( ( $graded_post ) && ( is_a( $graded_post, 'WP_Post') ) ) { $graded_data = learndash_get_submitted_essay_data( $data['quizId'], $question_item['questionId'], $graded_post ); if ( isset( $graded_data['status'] ) ) { if ( 'graded' === $graded_data['status'] ) { if ( isset( $graded_data['points_awarded'] ) ) { $question_item['correct'] = absint( $graded_data['points_awarded'] ); $question_item['points'] = absint( $graded_data['points_awarded'] ); $question_item['incorrect'] = absint( $question_item['gPoints'] ) - $question_item['correct']; $question_item['result'] = esc_html__( 'Graded', 'learndash' ); } } else { $question_item['result'] = esc_html__( 'Ungraded', 'learndash' ); } } } } } /** * Allow filter of the new 'Result' column output. This is pretty free-form and was not used prior to v2.4 * @since v2.4 */ $question_item['result'] = apply_filters( 'learndash-quiz-statistics-result', $question_item['result'], $question_item ); $o['questions'][] = $question_item; } $view = new WpProQuiz_View_StatisticsAjax(); $view->avg = $avg; $view->statisticModel = $statisticRefMapper->fetchByRefId($refIdUserId, $quizId, $avg); $view->userName = esc_html__('Anonymous', 'learndash'); if($view->statisticModel->getUserId()) { $userInfo = get_userdata($view->statisticModel->getUserId()); if($userInfo !== false) $view->userName = $userInfo->user_login.' ('.$userInfo->display_name.')'; else $view->userName = esc_html__('Deleted user', 'learndash'); } if(!$avg) { $view->forms = $formMapper->fetch($quizId); } $view->userStatistic = $output; $html = $view->getUserTable(); return json_encode(array( 'html' => $html )); } public static function ajaxRestStatistic($data, $func) { if(!current_user_can('wpProQuiz_reset_statistics')) { return; } $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); switch ($data['type']) { case 0: //RefId or UserId if($data['refId']) $statisticRefMapper->deleteByRefId($data['refId']); else if($data['userId'] != '') $statisticRefMapper->deleteByUserIdQuizId($data['userId'], $data['quizId']); break; case 1: //alles $statisticRefMapper->deleteAll($data['quizId']); break; } } public static function ajaxLoadStatsticOverviewNew($data, $func) { if(!current_user_can('wpProQuiz_show_statistics')) { return json_encode(array()); } $statisticRefMapper = new WpProQuiz_Model_StatisticRefMapper(); $quizMapper = new WpProQuiz_Model_QuizMapper(); $quizId = $data['quizId']; $page = (isset($data['page']) && $data['page'] > 0) ? $data['page'] : 1; $limit = $data['pageLimit']; $start = $limit * ($page - 1); $statisticModel = $statisticRefMapper->fetchStatisticOverview($quizId, $data['onlyCompleted'], $start, $limit); $view = new WpProQuiz_View_StatisticsAjax(); $view->statisticModel = $statisticModel; $navi = null; if(isset($data['generateNav']) && $data['generateNav']) { $count = $statisticRefMapper->countOverviewNew($quizId, $data['onlyCompleted']); $navi = ceil(($count > 0 ? $count : 1) / $limit); } return json_encode(array( 'navi' => $navi, 'html' => $view->getOverviewTable() )); } } lib/view/WpProQuiz_View_FrontToplist.php 0000666 00000002631 15214236625 0014452 0 ustar 00 <?php class WpProQuiz_View_FrontToplist extends WpProQuiz_View_View { public function show() { ?> <div style="margin-bottom: 30px; margin-top: 10px;" class="wpProQuiz_toplist" data-quiz_id="<?php echo $this->quiz->getId(); ?>"> <?php if(!$this->inQuiz) { ?> <h2><?php esc_html_e('Leaderboard', 'learndash'); ?>: <?php echo $this->quiz->getName(); ?></h2> <?php } ?> <table class="wpProQuiz_toplistTable"> <caption><?php printf(__('maximum of %s points', 'learndash'), '<span class="wpProQuiz_max_points">'. $this->points .'</span>'); ?></caption> <thead> <tr> <th class="col-pos"><?php esc_html_e('Pos.', 'learndash'); ?></th> <th class="col-name"><?php esc_html_e('Name', 'learndash'); ?></th> <th class="col-date"><?php esc_html_e('Entered on', 'learndash'); ?></th> <th class="col-points"><?php esc_html_e('Points', 'learndash'); ?></th> <th class="col-results"><?php esc_html_e('Result', 'learndash'); ?></th> </tr> </thead> <tbody> <tr> <td colspan="5"><?php esc_html_e('Table is loading', 'learndash'); ?></td> </tr> <tr style="display: none;"> <td colspan="5"><?php esc_html_e('No data available', 'learndash'); ?></td> </tr> <tr style="display: none;"> <td class="col-pos"></td> <td class="col-name"></td> <td class="col-date"></td> <td class="col-points"></td> <td class="col-results"></td> </tr> </tbody> </table> </div> <?php } } lib/view/WpProQuiz_View_Import.php 0000666 00000006206 15214236625 0013257 0 ustar 00 <?php class WpProQuiz_View_Import extends WpProQuiz_View_View { public function show() { ?> <style> .wpProQuiz_importList { list-style: none; margin: 0; padding: 0; } .wpProQuiz_importList li { float: left; padding: 5px; border: 1px solid #B3B3B3; margin-right: 5px; background-color: #DAECFF; } </style> <div class="wrap wpProQuiz_importOverall"> <h2><?php esc_html_e('Import', 'learndash'); ?></h2> <br> <?php if($this->error) { ?> <div style="padding: 10px; background-color: rgb(255, 199, 199); margin-top: 20px; border: 1px dotted;"> <h3 style="margin-top: 0;"><?php esc_html_e('Error', 'learndash'); ?></h3> <div> <?php echo $this->error; ?> </div> </div> <?php } else if($this->finish) { ?> <div style="padding: 10px; background-color: #C7E4FF; margin-top: 20px; border: 1px dotted;"> <h3 style="margin-top: 0;"><?php esc_html_e('Successfully', 'learndash'); ?></h3> <div> <?php $edit_link = ''; if ( $this->import_post_id ) { $edit_link = '<a href="'. get_edit_post_link( $this->import_post_id ) .'">' . sprintf( // translators: placeholder: Quiz Title. esc_html_x('%s', 'placeholder: Quiz Title', 'learndash'), get_the_title( $this->import_post_id ) ) . '</a>'; } echo wpautop( sprintf( // translators: placeholder: link to Imported Quiz esc_html_x( 'Import completed successfully: %s', 'placeholder: link to Imported Quiz.', 'learndash' ), $edit_link ) ); ?> </div> </div> <?php /* echo wpautop( '<a href="'. admin_url( 'admin.php?page=ldAdvQuiz' ) .'">' . sprintf( // translators: placeholder: Quiz. esc_html_x( 'Return to %s Import/Export.', 'placeholder: Quiz', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) . '</a>' ); */ ?> <?php } else { ?> <form method="post"> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col" width="30px"></th> <th scope="col" width="40%"><?php echo sprintf( esc_html_x('%s name', 'Quiz name', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )); ?></th> <th scope="col"><?php esc_html_e('Questions', 'learndash'); ?></th> </tr> </thead> <tbody> <?php foreach($this->import['master'] as $master) { ?> <tr> <th> <input type="checkbox" name="importItems[]" value="<?php echo $master->getId(); ?>" checked="checked"> </th> <th><?php echo $master->getName(); ?></th> <th> <ul class="wpProQuiz_importList"> <?php if(isset($this->import['question'][$master->getId()])) { ?> <?php foreach($this->import['question'][$master->getId()] as $question) { ?> <li><?php echo $question->getTitle(); ?></li> <?php } } ?> </ul> <div style="clear: both;"></div> </th> </tr> <?php } ?> </tbody> </table> <input name="importData" value="<?php echo $this->importData; ?>" type="hidden"> <input name="importType" value="<?php echo $this->importType; ?>" type="hidden"> <input style="margin-top: 20px;" class="button-primary" name="importSave" value="<?php esc_html_e('Start import', 'learndash'); ?>" type="submit"> </form> <?php } ?> </div> <?php } } lib/view/WpProQuiz_View_QuestionEdit.php 0000666 00000074336 15214236625 0014433 0 ustar 00 <?php class WpProQuiz_View_QuestionEdit extends WpProQuiz_View_View { /** * @var WpProQuiz_Model_Category */ public $categories; /** * @var WpProQuiz_Model_Question; */ public $question; public function show() { wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); ?> <div class="wrap wpProQuiz_questionEdit"> <h2 style="margin-bottom: 10px;"><?php echo $this->header; ?></h2> <!-- <form action="admin.php?page=wpProQuiz&module=question&action=show&quiz_id=<?php echo $this->quiz->getId(); ?>" method="POST"> --> <form action="admin.php?page=ldAdvQuiz&module=question&action=addEdit&quiz_id=<?php echo $this->quiz->getId(); ?>&questionId=<?php echo $this->question->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>" method="POST"> <a style="float: left;" class="button-secondary" href="admin.php?page=ldAdvQuiz&module=question&action=show&quiz_id=<?php echo $this->quiz->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>"><?php esc_html_e('Return to Questions Overview', 'learndash'); ?></a> <div style="float: right;"> <select name="templateLoadId"> <?php foreach($this->templates as $template) { echo '<option value="', $template->getTemplateId(), '">', esc_html($template->getName()), '</option>'; } ?> </select> <input type="submit" name="templateLoad" value="<?php esc_html_e('load template', 'learndash'); ?>" class="button-primary"> </div> <div style="clear: both;"></div> <!-- <input type="hidden" value="edit" name="hidden_action"> <input type="hidden" value="<?php echo $this->question->getId(); ?>" name="questionId">--> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Title', 'learndash'); ?> <?php esc_html_e('(optional)', 'learndash'); ?></h3> <div class="inside"> <p class="description"> <?php echo sprintf( esc_html_x('The title is used for overview, it is not visible in %s. If you leave the title field empty, a title will be generated.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> <input name="title" class="regular-text" value="<?php echo $this->question->getTitle(); ?>" type="text"> </div> </div> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Points', 'learndash'); ?> <?php esc_html_e('(required)', 'learndash'); ?></h3> <div class="inside"> <div id="wpProQuiz_questionPoints> <p class="description"> <?php esc_html_e('Points for this question (Standard is 1 point)', 'learndash'); ?> </p> <label> <input name="points" class="small-text" value="<?php echo $this->question->getPoints(); ?>" type="number" min="1"> <?php esc_html_e('Points', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('This points will be rewarded, only if the user closes the question correctly.', 'learndash'); ?> </p> </div> <div style="margin-top: 10px;" id="wpProQuiz_answerPointsActivated"> <label> <input name="answerPointsActivated" type="checkbox" value="1" <?php echo $this->question->isAnswerPointsActivated() ? 'checked="checked"' : '' ?>> <?php esc_html_e('Different points for each answer', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, you can enter different points for every answer.', 'learndash'); ?> </p> </div> <div style="margin-top: 10px; display: none;" id="wpProQuiz_showPointsBox"> <label> <input name="showPointsInBox" value="1" type="checkbox" <?php echo $this->question->isShowPointsInBox() ? 'checked="checked"' : '' ?>> <?php esc_html_e('Show reached points in the correct- and incorrect message?', 'learndash'); ?> </label> </div> </div> </div> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Category', 'learndash'); ?> <?php esc_html_e('(optional)', 'learndash'); ?></h3> <div class="inside"> <p class="description"> <?php esc_html_e('You can assign classify category for a question. Categories are e.g. visible in statistics function.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('You can manage categories in global settings.', 'learndash'); ?> </p> <div> <select name="category"> <option value="-1">--- <?php esc_html_e('Create new category', 'learndash'); ?> ----</option> <option value="0" <?php echo $this->question->getCategoryId() == 0 ? 'selected="selected"' : ''; ?>>--- <?php esc_html_e('No category', 'learndash'); ?> ---</option> <?php foreach($this->categories as $cat) { echo '<option '.($this->question->getCategoryId() == $cat->getCategoryId() ? 'selected="selected"' : '').' value="'.$cat->getCategoryId().'">'. stripslashes($cat->getCategoryName()) .'</option>'; } ?> </select> </div> <div style="display: none;" id="categoryAddBox"> <h4><?php esc_html_e('Create new category', 'learndash'); ?></h4> <input type="text" name="categoryAdd" value=""> <input type="button" class="button-secondary" name="" id="categoryAddBtn" value="<?php esc_html_e('Create', 'learndash'); ?>"> </div> <div id="categoryMsgBox" style="display:none; padding: 5px; border: 1px solid rgb(160, 160, 160); background-color: rgb(255, 255, 168); font-weight: bold; margin: 5px; "> Kategorie gespeichert </div> </div> </div> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Question', 'learndash'); ?> <?php esc_html_e('(required)', 'learndash'); ?></h3> <div class="inside"> <?php wp_editor($this->question->getQuestion(), "question", array('textarea_rows' => 5)); ?> </div> </div> <div class="postbox" style="<?php echo $this->quiz->isHideAnswerMessageBox() ? '' : 'display: none;'; ?>"> <h3 class="hndle"><?php esc_html_e('Message with the correct / incorrect answer', 'learndash'); ?></h3> <div class="inside"> <?php echo sprintf( esc_html_x('Deactivated in %s settings.', 'Deactivated in quiz settings.', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </div> </div> <div style="<?php echo $this->quiz->isHideAnswerMessageBox() ? 'display: none;' : ''; ?>"> <div class="postbox" id="wpProQuiz_correctMessageBox"> <h3 class="hndle"><?php esc_html_e('Message with the correct answer', 'learndash'); ?> <?php esc_html_e('(optional)', 'learndash'); ?></h3> <div class="inside"> <p class="description"> <?php esc_html_e('This text will be visible if answered correctly. It can be used as explanation for complex questions. The message "Right" or "Wrong" is always displayed automatically.', 'learndash'); ?> </p> <div style="padding-top: 10px; padding-bottom: 10px;"> <label for="wpProQuiz_correctSameText"> <?php esc_html_e('Same text for correct- and incorrect-message?', 'learndash'); ?> <input type="checkbox" name="correctSameText" id="wpProQuiz_correctSameText" value="1" <?php echo $this->question->isCorrectSameText() ? 'checked="checked"' : '' ?>> </label> </div> <?php wp_editor($this->question->getCorrectMsg(), "correctMsg", array('textarea_rows' => 3)); ?> </div> </div> <div class="postbox" id="wpProQuiz_incorrectMassageBox"> <h3 class="hndle"><?php esc_html_e('Message with the incorrect answer', 'learndash'); ?> <?php esc_html_e('(optional)', 'learndash'); ?></h3> <div class="inside"> <p class="description"> <?php esc_html_e('This text will be visible if answered incorrectly. It can be used as explanation for complex questions. The message "Right" or "Wrong" is always displayed automatically.', 'learndash'); ?> </p> <?php wp_editor($this->question->getIncorrectMsg(), "incorrectMsg", array('textarea_rows' => 3)); ?> </div> </div> </div> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Hint', 'learndash'); ?> <?php esc_html_e('(optional)', 'learndash'); ?></h3> <div class="inside"> <p class="description"> <?php esc_html_e('Here you can enter solution hint.', 'learndash'); ?> </p> <div style="padding-top: 10px; padding-bottom: 10px;"> <label for="wpProQuiz_tip"> <?php esc_html_e('Activate hint for this question?', 'learndash'); ?> <input type="checkbox" name="tipEnabled" id="wpProQuiz_tip" value="1" <?php echo $this->question->isTipEnabled() ? 'checked="checked"' : '' ?>> </label> </div> <div id="wpProQuiz_tipBox"> <?php wp_editor($this->question->getTipMsg(), 'tipMsg', array('textarea_rows' => 3)); ?> </div> </div> </div> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Answer type', 'learndash'); ?></h3> <div class="inside"> <?php $type = $this->question->getAnswerType(); $type = $type === null ? 'single' : $type; ?> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="single" <?php echo ($type === 'single') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Single choice', 'learndash'); ?> </label> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="multiple" <?php echo ($type === 'multiple') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Multiple choice', 'learndash'); ?> </label> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="free_answer" <?php echo ($type === 'free_answer') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('"Free" choice', 'learndash'); ?> </label> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="sort_answer" <?php echo ($type === 'sort_answer') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('"Sorting" choice', 'learndash'); ?> </label> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="matrix_sort_answer" <?php echo ($type === 'matrix_sort_answer') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('"Matrix Sorting" choice', 'learndash'); ?> </label> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="cloze_answer" <?php echo ($type === 'cloze_answer') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Fill in the blank', 'learndash'); ?> </label> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="assessment_answer" <?php echo ($type === 'assessment_answer') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Assessment', 'learndash'); ?> </label> <label style="padding-right: 10px;"> <input type="radio" name="answerType" value="essay" <?php echo ($type === 'essay') ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Essay / Open Answer', 'learndash'); ?> </label> </div> </div> <?php $this->singleChoiceOptions($this->data['classic_answer']); ?> <div class="postbox" id="wpProQuiz_answers"> <h3 class="hndle"><?php esc_html_e('Answers', 'learndash'); ?> <?php esc_html_e('(required)', 'learndash'); ?></h3> <div class="inside answer_felder"> <div class="free_answer"> <?php $this->freeChoice($this->data['free_answer']); ?> </div> <div class="sort_answer"> <p class="description"> <?php esc_html_e('Please sort the answers in right order with the "Move" - Button. The answers will be displayed randomly.', 'learndash'); ?> </p> <ul class="answerList"> <?php $this->sortingChoice($this->data['sort_answer']); ?> </ul> <input type="button" class="button-primary addAnswer" data-default-value="<?php echo LEARNDASH_LMS_DEFAULT_ANSWER_POINTS ?>" value="<?php esc_html_e('Add new answer', 'learndash'); ?>"> </div> <div class="classic_answer"> <ul class="answerList"> <?php $this->singleMultiCoice($this->data['classic_answer']); ?> </ul> <input type="button" class="button-primary addAnswer" data-default-value="<?php echo LEARNDASH_LMS_DEFAULT_ANSWER_POINTS ?>" value="<?php esc_html_e('Add new answer', 'learndash'); ?>"> </div> <div class="matrix_sort_answer"> <p class="description"> <?php esc_html_e('In this mode, Sort Elements must be assigned to their corresponding Criterion.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('Each Sort Element must be unique, and only one-to-one associations are supported.', 'learndash'); ?> </p> <br> <label> <?php esc_html_e('Percentage width of criteria table column:', 'learndash'); ?> <?php $msacwValue = $this->question->getMatrixSortAnswerCriteriaWidth() > 0 ? $this->question->getMatrixSortAnswerCriteriaWidth() : 20; ?> <input type="number" min="1" max="99" step="1" name="matrixSortAnswerCriteriaWidth" value="<?php echo $msacwValue; ?>">% </label> <p class="description"> <?php esc_html_e('Allows adjustment of the left column\'s width, and the right column will auto-fill the rest of the available space. Increase this to allow accommodate longer criterion text. Defaults to 20%.', 'learndash'); ?> </p> <br> <ul class="answerList"> <?php $this->matrixSortingChoice($this->data['matrix_sort_answer']); ?> </ul> <input type="button" class="button-primary addAnswer" data-default-value="<?php echo LEARNDASH_LMS_DEFAULT_ANSWER_POINTS ?>" value="<?php esc_html_e('Add new answer', 'learndash'); ?>"> </div> <div class="cloze_answer"> <?php $this->clozeChoice($this->data['cloze_answer']); ?> </div> <div class="assessment_answer"> <?php $this->assessmentChoice($this->data['assessment_answer']); ?> </div> <div class="essay"> <?php $this->essayChoice($this->data['essay']); ?> </div> </div> </div> <div style="float: left;"> <input type="submit" name="submit" id="saveQuestion" class="button-primary" value="<?php esc_html_e('Save', 'learndash'); ?>"> </div> <div style="float: right;"> <input type="text" placeholder="<?php esc_html_e('template name', 'learndash'); ?>" class="regular-text" name="templateName" style="border: 1px solid rgb(255, 134, 134);"> <select name="templateSaveList"> <option value="0">=== <?php esc_html_e('Create new template', 'learndash'); ?> === </option> <?php foreach($this->templates as $template) { echo '<option value="', $template->getTemplateId(), '">', esc_html($template->getName()), '</option>'; } ?> </select> <input type="submit" name="template" class="button-primary" id="wpProQuiz_saveTemplate" value="<?php esc_html_e('Save as template', 'learndash'); ?>"> </div> <div style="clear: both;"></div> </div> </form> </div> <?php } public function singleMultiCoice($data) { foreach($data as $d) { ?> <li style="border-bottom:1px dotted #ccc; padding-bottom: 5px; background-color: whiteSmoke;" id="TEST"> <table style="width: 100%;border: 1px solid #9E9E9E;border-collapse: collapse; margin-bottom: 20px;"> <thead> <tr> <th width="160px" style=" border-right: 1px solid #9E9E9E; padding: 5px; "><?php esc_html_e('Options', 'learndash'); ?></th> <th style="padding: 5px;"><?php esc_html_e('Answer', 'learndash'); ?></th> </tr> </thead> <tbody> <tr> <td style="border-right: 1px solid #9E9E9E; padding: 5px; vertical-align: top;"> <div> <label> <input type="checkbox" class="wpProQuiz_classCorrect wpProQuiz_checkbox" name="answerData[][correct]" value="1" <?php $this->checked($d->isCorrect()); ?>> <?php esc_html_e('Correct', 'learndash'); ?> </label> </div> <div style="padding-top: 5px;"> <label> <input type="checkbox" class="wpProQuiz_checkbox" name="answerData[][html]" value="1" <?php $this->checked($d->isHtml()); ?>> <?php esc_html_e('Allow HTML', 'learndash'); ?> </label> </div> <div style="padding-top: 5px;" class="wpProQuiz_answerPoints"> <label> <input type="number" min="0" class="small-text wpProQuiz_points" name="answerData[][points]" value="<?php echo $d->getPoints(); ?>"> <?php esc_html_e('Points', 'learndash'); ?> </label> </div> </td> <td style="padding: 5px; vertical-align: top;"> <textarea rows="2" cols="50" class="large-text wpProQuiz_text" name="answerData[][answer]" style="resize:vertical;"><?php echo $d->getAnswer(); ?></textarea> </td> </tr> </tbody> </table> <input type="button" name="submit" class="button-primary deleteAnswer" value="<?php esc_html_e('Delete answer', 'learndash'); ?>"> <input type="button" class="button-secondary addMedia" value="<?php esc_html_e('Add Media', 'learndash'); ?>"> <a href="#" class="button-secondary wpProQuiz_move" style="cursor: move;"><?php esc_html_e('Move', 'learndash'); ?></a> </li> <?php } } public function matrixSortingChoice($data) { foreach($data as $d) { ?> <li style="border-bottom:1px dotted #ccc; padding-bottom: 5px; background-color: whiteSmoke;"> <table style="width: 100%;border: 1px solid #9E9E9E;border-collapse: collapse; margin-bottom: 20px;"> <thead> <tr> <th width="130px" style=" border-right: 1px solid #9E9E9E; padding: 5px; "><?php esc_html_e('Options', 'learndash'); ?></th> <th style=" border-right: 1px solid #9E9E9E; padding: 5px; "><?php esc_html_e('Criterion', 'learndash'); ?></th> <th style="padding: 5px;"><?php esc_html_e('Sort elements', 'learndash'); ?></th> </tr> </thead> <tbody> <tr> <td style="border-right: 1px solid #9E9E9E; padding: 5px; vertical-align: top;"> <label class="wpProQuiz_answerPoints"> <input type="number" min="0" class="small-text wpProQuiz_points" name="answerData[][points]" value="<?php echo $d->getPoints(); ?>"> <?php esc_html_e('Points', 'learndash'); ?> </label> </td> <td style="border-right: 1px solid #9E9E9E; padding: 5px; vertical-align: top;"> <textarea rows="4" name="answerData[][answer]" class="wpProQuiz_text" style="width: 100%; resize:vertical;"><?php echo $d->getAnswer(); ?></textarea> </td> <td style="padding: 5px; vertical-align: top;"> <textarea rows="4" name="answerData[][sort_string]" class="wpProQuiz_text" style="width: 100%; resize:vertical;"><?php echo $d->getSortString(); ?></textarea> </td> </tr> <tr> <td style="border-right: 1px solid #9E9E9E; padding: 5px; vertical-align: top;"></td> <td style="border-right: 1px solid #9E9E9E; padding: 5px; vertical-align: top;"> <label> <input type="checkbox" class="wpProQuiz_checkbox" name="answerData[][html]" value="1" <?php $this->checked($d->isHtml()); ?>> <?php esc_html_e('Allow HTML', 'learndash'); ?> </label> </td> <td style="padding: 5px; vertical-align: top;"> <label> <input type="checkbox" class="wpProQuiz_checkbox" name="answerData[][sort_string_html]" value="1" <?php $this->checked($d->isSortStringHtml()); ?>> <?php esc_html_e('Allow HTML', 'learndash'); ?> </label> </td> </tr> </tbody> </table> <input type="button" name="submit" class="button-primary deleteAnswer" value="<?php esc_html_e('Delete answer', 'learndash'); ?>"> <input type="button" class="button-secondary addMedia" value="<?php esc_html_e('Add Media', 'learndash'); ?>"> <a href="#" class="button-secondary wpProQuiz_move" style="cursor: move;"><?php esc_html_e('Move', 'learndash'); ?></a> </li> <?php } } public function sortingChoice($data) { foreach($data as $d) { ?> <li style="border-bottom:1px dotted #ccc; padding-bottom: 5px; background-color: whiteSmoke;"> <table style="width: 100%;border: 1px solid #9E9E9E;border-collapse: collapse;margin-bottom: 20px;"> <thead> <tr> <th width="160px" style=" border-right: 1px solid #9E9E9E; padding: 5px; "><?php esc_html_e('Options', 'learndash'); ?></th> <th style="padding: 5px;"><?php esc_html_e('Answer', 'learndash'); ?></th> </tr> </thead> <tbody> <tr> <td style="border-right: 1px solid #9E9E9E; padding: 5px; vertical-align: top;"> <div> <label> <input type="checkbox" class="wpProQuiz_checkbox" name="answerData[][html]" value="1" <?php $this->checked($d->isHtml()); ?>> <?php esc_html_e('Allow HTML', 'learndash'); ?> </label> </div> <div style="padding-top: 5px;" class="wpProQuiz_answerPoints"> <label> <input type="number" min="0" class="small-text wpProQuiz_points" name="answerData[][points]" value="<?php echo $d->getPoints(); ?>"> <?php esc_html_e('Points', 'learndash'); ?> </label> </div> </td> <td style="padding: 5px; vertical-align: top;"> <textarea rows="2" cols="100" class="large-text wpProQuiz_text" name="answerData[][answer]" style="resize:vertical;"><?php echo $d->getAnswer(); ?></textarea> </td> </tr> </tbody> </table> <input type="button" name="submit" class="button-primary deleteAnswer" value="<?php esc_html_e('Delete answer', 'learndash'); ?>"> <input type="button" class="button-secondary addMedia" value="<?php esc_html_e('Add Media', 'learndash'); ?>"> <a href="#" class="button-secondary wpProQuiz_move" style="cursor: move;"><?php esc_html_e('Move', 'learndash'); ?></a> </li> <?php } } public function freeChoice($data) { $single = $data[0]; ?> <div class="answerList"> <p class="description"> <?php esc_html_e('correct answers (one per line) (answers will be converted to lower case)', 'learndash'); ?> </p> <p style="border-bottom:1px dotted #ccc;"> <textarea rows="6" cols="100" class="large-text" name="answerData[][answer]"><?php echo $single->getAnswer(); ?></textarea> </p> </div> <?php } public function clozeChoice($data) { $single = $data[0]; ?> <p class="description"> <?php esc_html_e('Enclose the searched words with { } e.g. "I {play} soccer". Capital and small letters will be ignored.', 'learndash'); ?> </p> <p class="description"> <?php wp_kses_post ( _e( 'You can specify multiple options for a search word. Enclose the word with [ ] e.g. <span style="font-style: normal; letter-spacing: 2px;"> "I {[play][love][hate]} soccer" </span>. In this case answers play, love OR hate are correct.', 'learndash') ); ?> </p> <p class="description" style="margin-top: 10px;"> <?php esc_html_e('If mode "Different points for every answer" is activated, you can assign points with |POINTS. Otherwise 1 point will be awarded for every answer.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('e.g. "I {play} soccer, with a {ball|3}" - "play" gives 1 point and "ball" 3 points.', 'learndash'); ?> </p> <?php wp_editor($single->getAnswer(), 'cloze', array('textarea_rows' => 10, 'textarea_name' => 'answerData[cloze][answer]')); ?> <?php } public function assessmentChoice($data) { $single = $data[0]; ?> <p class="description"> <?php esc_html_e('Here you can create an assessment question.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('Enclose a assesment with {}. The individual assessments are marked with [].', 'learndash'); ?> <br> <?php esc_html_e('The number of options in the maximum score.', 'learndash'); ?> </p> <p> <?php esc_html_e('Examples:', 'learndash'); ?> <br> * <?php esc_html_e('less true { [1] [2] [3] [4] [5] } more true', 'learndash'); ?> </p> <p> * <?php esc_html_e('less true { [a] [b] [c] } more true', 'learndash'); ?> </p> <p></p> <?php wp_editor($single->getAnswer(), 'assessment', array('textarea_rows' => 10, 'textarea_name' => 'answerData[assessment][answer]')); ?> <?php } public function essayChoice( $data ) { $data = array_shift( $data ); if ( is_a( $data, 'WpProQuiz_Model_AnswerTypes' ) ) { ?> <p class="description"><?php esc_html_e( 'How should the user submit their answer?', 'learndash' ); ?></p> <select name="answerData[essay][type]" id="essay-type"> <option value="text" <?php selected( $data->getGradedType(), 'text' ); ?>><?php esc_html_e('Text Box', 'learndash') ?></option> <option value="upload" <?php selected( $data->getGradedType(), 'upload' ); ?>><?php esc_html_e('Upload', 'learndash') ?></option> </select> <p class="description" style="margin-top: 10px"> <?php echo sprintf( esc_html_x( 'This is a question that can be graded and potentially prevent a user from progressing to the next step of the %s.', 'placeholders: course', 'learndash' ), learndash_get_custom_label_lower( 'course' ) ) ?><br /> <?php esc_html_e( 'The user can only progress if the essay is marked as "Graded" and if the user has enough points to move on.', 'learndash' ) ?><br /> <?php echo sprintf( esc_html_x( 'How should the answer to this question be marked and graded upon %s submission?', 'placeholders: quiz', 'learndash' ), learndash_get_custom_label_lower( 'quiz' ) ); ?><br /> </p> <select name="answerData[essay][progression]" id="essay-progression"> <option value=""><?php esc_html_e('-- Select --', 'learndash') ?></option> <option value="not-graded-none" <?php selected( $data->getGradingProgression(), 'not-graded-none' ); ?>><?php esc_html_e('Not Graded, No Points Awarded', 'learndash') ?></option> <option value="not-graded-full" <?php selected( $data->getGradingProgression(), 'not-graded-full' ); ?>><?php esc_html_e('Not Graded, Full Points Awarded', 'learndash') ?></option> <option value="graded-full" <?php selected( $data->getGradingProgression(), 'graded-full' ); ?>><?php esc_html_e('Graded, Full Points Awarded', 'learndash') ?></option> </select> <input type="hidden" id="essay" name="answerData[essay][answer]"> <?php } } public function singleChoiceOptions($data) { ?> <div class="postbox" id="singleChoiceOptions"> <h3 class="hndle"><?php esc_html_e('Single choice options', 'learndash'); ?></h3> <div class="inside"> <p class="description"> <?php echo wp_kses_post( __('If "Different points for each answer" is activated, you can activate a special mode.<br> This changes the calculation of the points', 'learndash') ); ?> </p> <label> <input type="checkbox" name="answerPointsDiffModusActivated" value="1" <?php $this->checked($this->question->isAnswerPointsDiffModusActivated()); ?>> <?php esc_html_e('Different points - modus 2 activate', 'learndash'); ?> </label> <br><br> <p class="description"> <?php esc_html_e('Disables the distinction between correct and incorrect.', 'learndash'); ?><br> </p> <label> <input type="checkbox" name=disableCorrect value="1" <?php $this->checked($this->question->isDisableCorrect()); ?>> <?php esc_html_e('Disable correct and incorrect', 'learndash'); ?> </label> <div style="padding-top: 20px;"> <a href="#" id="clickPointDia"><?php esc_html_e('Explanation of points calculation', 'learndash'); ?></a> <?php $this->answerPointDia(); ?> </div> </div> </div> <?php } private function answerPointDia() { ?> <style> .pointDia td { border: 1px solid #9E9E9E; padding: 8px; } </style> <table style="border-collapse: collapse; display: none; margin-top: 10px;" class="pointDia"> <tr> <th> <?php esc_html_e('"Different points for each answer" enabled', 'learndash'); ?> <br> <?php esc_html_e('"Different points - mode 2" disable', 'learndash'); ?> </th> <th> <?php esc_html_e('"Different points for each answer" enabled', 'learndash'); ?> <br> <?php esc_html_e('"Different points - mode 2" enabled', 'learndash'); ?> </th> </tr> <tr> <td> <?php echo nl2br('Question - Single Choice - 3 Answers - Diff points mode A=3 Points [correct] B=2 Points [incorrect] C=1 Point [incorrect] = 6 Points '); ?> </td> <td> <?php echo nl2br('Question - Single Choice - 3 Answers - Modus 2 A=3 Points [correct] B=2 Points [incorrect] C=1 Point [incorrect] = 3 Points '); ?> </td> </tr> <tr> <td> <?php echo nl2br('~~~ User 1: ~~~ A=checked B=unchecked C=unchecked Result: A=correct and checked (correct) = 3 Points B=incorrect and unchecked (correct) = 2 Points C=incorrect and unchecked (correct) = 1 Points = 6 / 6 Points 100% '); ?> </td> <td> <?php echo nl2br('~~~ User 1: ~~~ A=checked B=unchecked C=unchecked Result: A=checked = 3 Points B=unchecked = 0 Points C=unchecked = 0 Points = 3 / 3 Points 100%'); ?> </td> </tr> <tr> <td> <?php echo nl2br('~~~ User 2: ~~~ A=unchecked B=checked C=unchecked Result: A=correct and unchecked (incorrect) = 0 Points B=incorrect and checked (incorrect) = 0 Points C=incorrect and uncecked (correct) = 1 Points = 1 / 6 Points 16.67% '); ?> </td> <td> <?php echo nl2br('~~~ User 2: ~~~ A=unchecked B=checked C=unchecked Result: A=unchecked = 0 Points B=checked = 2 Points C=uncecked = 0 Points = 2 / 3 Points 66,67%'); ?> </td> </tr> <tr> <td> <?php echo nl2br('~~~ User 3: ~~~ A=unchecked B=unchecked C=checked Result: A=correct and unchecked (incorrect) = 0 Points B=incorrect and unchecked (correct) = 2 Points C=incorrect and checked (incorrect) = 0 Points = 2 / 6 Points 33.33% '); ?> </td> <td> <?php echo nl2br('~~~ User 3: ~~~ A=unchecked B=unchecked C=checked Result: A=unchecked = 0 Points B=unchecked = 0 Points C=checked = 1 Points = 1 / 3 Points 33,33%'); ?> </td> </tr> <tr> <td> <?php echo nl2br('~~~ User 4: ~~~ A=unchecked B=unchecked C=unchecked Result: A=correct and unchecked (incorrect) = 0 Points B=incorrect and unchecked (correct) = 2 Points C=incorrect and unchecked (correct) = 1 Points = 3 / 6 Points 50% '); ?> </td> <td> <?php echo nl2br('~~~ User 4: ~~~ A=unchecked B=unchecked C=unchecked Result: A=unchecked = 0 Points B=unchecked = 0 Points C=unchecked = 0 Points = 0 / 3 Points 0%'); ?> </td> </tr> </table> <?php } } lib/view/WpProQuiz_View_Statistics.php 0000666 00000033073 15214236625 0014141 0 ustar 00 <?php class WpProQuiz_View_Statistics extends WpProQuiz_View_View { /** * @var WpProQuiz_Model_Quiz */ public $quiz; public function show() { ?> <style> .wpProQuiz_blueBox { padding: 20px; background-color: rgb(223, 238, 255); border: 1px dotted; margin-top: 10px; } .categoryTr th { background-color: #F1F1F1; } </style> <div class="wrap wpProQuiz_statistics"> <input type="hidden" id="quizId" value="<?php echo $this->quiz->getId(); ?>" name="quizId"> <h2><?php echo sprintf( esc_html_x('%1$s: %2$s - Statistics', 'placeholders: Quiz, Quiz Name/Title', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), $this->quiz->getName() ); ?></h2> <p><a class="button-secondary" href="admin.php?page=ldAdvQuiz"><?php esc_html_e('back to overview', 'learndash'); ?></a></p> <?php if(!$this->quiz->isStatisticsOn()) { ?> <p style="padding: 30px; background: #F7E4E4; border: 1px dotted; width: 300px;"> <span style="font-weight: bold; padding-right: 10px;"><?php esc_html_e('Stats not enabled', 'learndash'); ?></span> <a class="button-secondary" href="admin.php?page=ldAdvQuiz&action=addEdit&quizId=<?php echo $this->quiz->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>"><?php esc_html_e('Activate statistics', 'learndash'); ?></a> </p> <?php return; } ?> <div style="padding: 10px 0px;"> <a class="button-primary wpProQuiz_tab" id="wpProQuiz_typeUser" href="#"><?php esc_html_e('Users', 'learndash'); ?></a> <a class="button-secondary wpProQuiz_tab" id="wpProQuiz_typeOverview" href="#"><?php esc_html_e('Overview', 'learndash'); ?></a> <a class="button-secondary wpProQuiz_tab" id="wpProQuiz_typeForm" href="#"><?php esc_html_e('Custom fields', 'learndash'); ?></a> </div> <div id="wpProQuiz_loadData" class="wpProQuiz_blueBox" style="background-color: #F8F5A8; display: none;"> <img alt="load" src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" /> <?php esc_html_e('Loading', 'learndash'); ?> </div> <div id="wpProQuiz_content" style="display: none;"> <?php $this->tabUser(); ?> <?php $this->tabOverview(); ?> <?php $this->tabForms(); ?> </div> </div> <?php } private function tabUser() { ?> <div id="wpProQuiz_tabUsers" class="wpProQuiz_tabContent"> <div class="wpProQuiz_blueBox" id="wpProQuiz_userBox" style="margin-bottom: 20px;"> <div style="float: left;"> <div style="padding-top: 6px;"> <?php esc_html_e('Please select user name:', 'learndash'); ?> </div> <div style="padding-top: 6px;"> <?php esc_html_e('Select a test:', 'learndash'); ?> </div> </div> <div style="float: left;"> <div> <select name="userSelect" id="userSelect"> <?php foreach($this->users as $user) { if($user->ID == 0) echo '<option value="0">=== ', esc_html__('Anonymous user', 'learndash'),' ===</option>'; else echo '<option value="', $user->ID, '">', $user->user_login, ' (', $user->display_name, ')</option>'; } ?> </select> </div> <div> <select id="testSelect"> <option value="0">=== <?php esc_html_e('average', 'learndash'); ?> ===</option> </select> </div> </div> <div style="clear: both;"></div> </div> <?php $this->formTable(); ?> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col" style="width: 50px;"></th> <th scope="col"><?php esc_html_e('Question', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Points', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Correct', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Incorrect', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Hints used', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Time', 'learndash'); ?> <span style="font-size: x-small;">(hh:mm:ss)</span></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Points scored', 'learndash'); ?></th> <th scope="col" style="width: 60px;"><?php esc_html_e('Results', 'learndash'); ?></th> </tr> </thead> <tbody> <?php $gPoints = 0; foreach($this->questionList as $k => $ql) { $index = 1; $cPoints = 0; ?> <tr class="categoryTr"> <th colspan="9"> <span><?php esc_html_e('Category', 'learndash'); ?>:</span> <span style="font-weight: bold;"><?php echo $this->categoryList[$k]->getCategoryName(); ?></span> </th> </tr> <?php foreach($ql as $q) { $gPoints += $q->getPoints(); $cPoints += $q->getPoints(); ?> <tr id="wpProQuiz_tr_<?php echo $q->getId(); ?>"> <th><?php echo $index++; ?></th> <th><?php echo $q->getTitle(); ?></th> <th class="wpProQuiz_points"><?php echo $q->getPoints(); ?></th> <th class="wpProQuiz_cCorrect" style="color: green;"></th> <th class="wpProQuiz_cIncorrect" style="color: red;"></th> <th class="wpProQuiz_cTip"></th> <th class="wpProQuiz_cTime"></th> <th class="wpProQuiz_cPoints"></th> <th></th> </tr> <?php } ?> <tr class="categoryTr" id="wpProQuiz_ctr_<?php echo $k; ?>"> <th colspan="2"> <span><?php esc_html_e('Sub-Total: ', 'learndash'); ?></span> </th> <th class="wpProQuiz_points"><?php echo $cPoints; ?></th> <th class="wpProQuiz_cCorrect" style="color: green;"></th> <th class="wpProQuiz_cIncorrect" style="color: red;"></th> <th class="wpProQuiz_cTip"></th> <th class="wpProQuiz_cTime"></th> <th class="wpProQuiz_cPoints"></th> <th class="wpProQuiz_cResult" style="font-weight: bold;"></th> </tr> <tr> <th colspan="9"></th> </tr> <?php } ?> </tbody> <tfoot> <tr id="wpProQuiz_tr_0"> <th></th> <th><?php esc_html_e('Total', 'learndash'); ?></th> <th class="wpProQuiz_points"><?php echo $gPoints; ?></th> <th class="wpProQuiz_cCorrect" style="color: green;"></th> <th class="wpProQuiz_cIncorrect" style="color: red;"></th> <th class="wpProQuiz_cTip"></th> <th class="wpProQuiz_cTime"></th> <th class="wpProQuiz_cPoints"></th> <th class="wpProQuiz_cResult" style="font-weight: bold;"></th> </tr> </tfoot> </table> <div style="margin-top: 10px;"> <div style="float: left;"> <a class="button-secondary wpProQuiz_update" href="#"><?php esc_html_e('Refresh', 'learndash'); ?></a> </div> <div style="float: right;"> <?php if(current_user_can('wpProQuiz_reset_statistics')) { ?> <a class="button-secondary" href="#" id="wpProQuiz_reset"><?php esc_html_e('Reset statistics', 'learndash'); ?></a> <a class="button-secondary" href="#" id="wpProQuiz_resetUser"><?php esc_html_e('Reset user statistics', 'learndash'); ?></a> <a class="button-secondary wpProQuiz_resetComplete" href="#"><?php esc_html_e('Reset entire statistic', 'learndash'); ?></a> <?php } ?> </div> <div style="clear: both;"></div> </div> </div> <?php } private function tabOverview() { ?> <div id="wpProQuiz_tabOverview" class="wpProQuiz_tabContent" style="display: none;"> <input type="hidden" value="<?php echo 0; ?>" name="gPoints" id="wpProQuiz_gPoints"> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Filter', 'learndash'); ?></h3> <div class="inside"> <ul> <li> <label> <?php echo sprintf( esc_html_x('Show only users, who solved the %s:', 'Show only users, who solved the quiz:', 'learndash'), learndash_get_custom_label_lower( 'quiz' )); ?> <input type="checkbox" value="1" id="wpProQuiz_onlyCompleted"> </label> </li> <li> <label> <?php esc_html_e('How many entries should be shown on one page:', 'learndash'); ?> <select id="wpProQuiz_pageLimit"> <option>1</option> <option>10</option> <option>50</option> <option selected="selected">100</option> <option>500</option> <option>1000</option> </select> </label> </li> </ul> </div> </div> </div> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col"><?php esc_html_e('User', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Points', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Correct', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Incorrect', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Hints used', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Time', 'learndash'); ?> <span style="font-size: x-small;">(hh:mm:ss)</span></th> <th scope="col" style="width: 60px;"><?php esc_html_e('Results', 'learndash'); ?></th> </tr> </thead> <tbody id="wpProQuiz_statistics_overview_data"> <tr style="display: none;"> <th><a href="#"></a></th> <th class="wpProQuiz_cPoints"></th> <th class="wpProQuiz_cCorrect" style="color: green;"></th> <th class="wpProQuiz_cIncorrect" style="color: red;"></th> <th class="wpProQuiz_cTip"></th> <th class="wpProQuiz_cTime"></th> <th class="wpProQuiz_cResult" style="font-weight: bold;"></th> </tr> </tbody> </table> <div style="margin-top: 10px;"> <div style="float: left;"> <input style="font-weight: bold;" class="button-secondary" value="<" type="button" id="wpProQuiz_pageLeft"> <select id="wpProQuiz_currentPage"><option value="1">1</option></select> <input style="font-weight: bold;" class="button-secondary"value=">" type="button" id="wpProQuiz_pageRight"> </div> <div style="float: right;"> <a class="button-secondary wpProQuiz_update" href="#"><?php esc_html_e('Refresh', 'learndash'); ?></a> <?php if(current_user_can('wpProQuiz_reset_statistics')) { ?> <a class="button-secondary wpProQuiz_resetComplete" href="#"><?php esc_html_e('Reset entire statistic', 'learndash'); ?></a> <?php } ?> </div> <div style="clear: both;"></div> </div> </div> <?php } private function tabForms() { ?> <div id="wpProQuiz_tabFormOverview" class="wpProQuiz_tabContent" style="display: none;"> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Filter', 'learndash'); ?></h3> <div class="inside"> <ul> <li> <label> <?php esc_html_e('Which users should be displayed:', 'learndash'); ?> <select id="wpProQuiz_formUser"> <option value="0"><?php esc_html_e('all', 'learndash'); ?></option> <option value="1"><?php esc_html_e('only registered users', 'learndash'); ?></option> <option value="2"><?php esc_html_e('only anonymous users', 'learndash'); ?></option> </select> </label> </li> <li> <label> <?php esc_html_e('How many entries should be shown on one page:', 'learndash'); ?> <select id="wpProQuiz_fromPageLimit"> <option>1</option> <option>10</option> <option>50</option> <option selected="selected">100</option> <option>500</option> <option>1000</option> </select> </label> </li> </ul> </div> </div> </div> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col"><?php esc_html_e('Username', 'learndash'); ?></th> <th scope="col" style="width: 200px;"><?php esc_html_e('Date', 'learndash'); ?></th> <th scope="col" style="width: 60px;"><?php esc_html_e('Results', 'learndash'); ?></th> </tr> </thead> <tbody id="wpProQuiz_statistics_form_data"> <tr style="display: none;"> <th><a href="#" class="wpProQuiz_cUsername"></a></th> <th class="wpProQuiz_cCreateTime"></th> <th class="wpProQuiz_cResult" style="font-weight: bold;"></th> </tr> </tbody> </table> <div style="margin-top: 10px;"> <div style="float: left;"> <input style="font-weight: bold;" class="button-secondary" value="<" type="button" id="wpProQuiz_formPageLeft"> <select id="wpProQuiz_formCurrentPage"><option value="1">1</option></select> <input style="font-weight: bold;" class="button-secondary"value=">" type="button" id="wpProQuiz_formPageRight"> </div> <div style="float: right;"> <a class="button-secondary wpProQuiz_update" href="#"><?php esc_html_e('Refresh', 'learndash'); ?></a> <?php if(current_user_can('wpProQuiz_reset_statistics')) { ?> <a class="button-secondary wpProQuiz_resetComplete" href="#"><?php esc_html_e('Reset entire statistic', 'learndash'); ?></a> <?php } ?> </div> <div style="clear: both;"></div> </div> </div> <?php } private function formTable() { if(!$this->quiz->isFormActivated()) return; ?> <div id="wpProQuiz_form_box"> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Custom fields', 'learndash'); ?></h3> <div class="inside"> <table> <tbody> <?php foreach($this->forms as $form) { /* @var $form WpProQuiz_Model_Form */ ?> <tr> <td style="padding: 5px;"><?php echo esc_html($form->getFieldname()); ?></td> <td id="form_id_<?php echo $form->getFormId();?>">asdfffffffffffffffffffffsadfsdfa sf asd fas</td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <?php } } lib/view/WpProQuiz_View_View.php 0000666 00000002133 15214236625 0012712 0 ustar 00 <?php class WpProQuiz_View_View { private $data = array(); public function __set($name, $value) { $this->data[$name] = $value; } public function __get($name) { if(isset($this->data[$name])) return $this->data[$name]; } public static function admin_notices($msg, $type = 'error') { if($type === 'info') echo '<div class="updated"><p><strong>'.$msg.'</strong></p></div>'; else echo '<div class="error"><p><strong>'.$msg.'</strong></p></div>'; } public function redirect($url) { } public function checked($v, $check = true, $echo = true) { $r = ($v == $check) ? 'checked="checked"' : ''; if($echo) { echo $r; } else { return $r; } } public function selected($v, $check = true, $echo = true) { $r = ($v == $check) ? 'selected="selected"' : ''; if($echo) { echo $r; } else { return $r; } } public function selectedArray($v, $check) { $a = array(); foreach($check as $c) $a[] = ($v == $c) ? 'selected="selected"' : ''; return $a; } public function isDisplayNone($v) { echo $v ? '' : 'style="display:none;"'; } } lib/view/WpProQuiz_View_AdminToplist.php 0000666 00000011417 15214236625 0014414 0 ustar 00 <?php class WpProQuiz_View_AdminToplist extends WpProQuiz_View_View { public function show() { ?> <div class="wrap wpProQuiz_toplist"> <?php /* ?><h2><?php esc_html_e('Leaderboard', 'learndash'); echo ': ', $this->quiz->getName(); ?></h2><?php */ ?> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Filter', 'learndash'); ?></h3> <div class="inside"> <ul> <li> <label> <?php esc_html_e('Sort by:', 'learndash'); ?> <select id="wpProQuiz_sorting"> <option value="<?php echo WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SORT_BEST; ?>"><?php esc_html_e('best user', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SORT_NEW; ?>"><?php esc_html_e('newest entry', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SORT_OLD; ?>"><?php esc_html_e('oldest entry', 'learndash'); ?></option> </select> </label> </li> <li> <label> <?php esc_html_e('How many entries should be shown on one page:', 'learndash'); ?> <select id="wpProQuiz_pageLimit"> <option>1</option> <option>10</option> <option>50</option> <option selected="selected">100</option> <option>500</option> <option>1000</option> </select> </label> </li> <li> <span style="font-weight: bold;"><?php esc_html_e('Type', 'learndash'); ?>:</span> <?php esc_html_e('UR = unregistered user, R = registered user', 'learndash'); ?> </li> </ul> </div> </div> </div> <div id="wpProQuiz_loadData" class="wpProQuiz_blueBox" style="background-color: #F8F5A8;padding: 20px;border: 1px dotted;margin-top: 10px;"> <img alt="load" src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" /> <?php esc_html_e('Loading', 'learndash'); ?> </div> <div id="wpProQuiz_content"> <table class="wp-list-table widefat" id="wpProQuiz_toplistTable"> <thead> <tr> <th scope="col" width="20px"><input style="margin: 0;" type="checkbox" value="0" id="wpProQuiz_checkedAll"></th> <th scope="col"><?php esc_html_e('User', 'learndash'); ?></th> <th scope="col"><?php esc_html_e('E-Mail', 'learndash'); ?></th> <th scope="col" width="50px"><?php esc_html_e('Type', 'learndash'); ?></th> <th scope="col" width="150px"><?php esc_html_e('Entered on', 'learndash'); ?></th> <th scope="col" width="70px"><?php esc_html_e('Points', 'learndash'); ?></th> <th scope="col" width="100px"><?php esc_html_e('Results', 'learndash'); ?></th> </tr> </thead> <tbody id=""> <tr style="display: none;"> <td><input type="checkbox" name="checkedData[]"></td> <td> <strong class="wpProQuiz_username"></strong> <input name="inline_editUsername" class="inline_editUsername" type="text" value="" style="display: none;"> <div class="row-actions"> <span style="display: none;"> <a class="wpProQuiz_edit" href="#"><?php esc_html_e('Edit', 'learndash'); ?></a> | </span> <span> <a style="color: red;" class="wpProQuiz_delete" href="#"><?php esc_html_e('Delete', 'learndash'); ?></a> </span> </div> <div class="inline-edit" style="margin-top: 10px; display: none;"> <input type="button" value="<?php esc_html_e('save', 'learndash'); ?>" class="button-secondary inline_editSave"> <input type="button" value="<?php esc_html_e('cancel', 'learndash'); ?>" class="button-secondary inline_editCancel"> </div> </td> <td> <span class="wpProQuiz_email"></span> <input name="inline_editEmail" class="inline_editEmail" value="" type="text" style="display: none;"> </td> <td></td> <td></td> <td></td> <td style="font-weight: bold;"></td> </tr> </tbody> </table> <div style="margin-top: 10px;"> <div style="float: left;"> <select id="wpProQuiz_actionName"> <option value="0" selected="selected"><?php esc_html_e('Action', 'learndash'); ?></option> <option value="delete" ><?php esc_html_e('Delete', 'learndash'); ?></option> </select> <input class="button-secondary" type="button" value="<?php esc_html_e('Apply', 'learndash'); ?>" id="wpProQuiz_action"> <input class="button-secondary" type="button" value="<?php esc_html_e('Delete all entries', 'learndash'); ?>" id="wpProQuiz_deleteAll"> </div> <div style="float: right;"> <input style="font-weight: bold;" class="button-secondary" value="<" type="button" id="wpProQuiz_pageLeft"> <select id="wpProQuiz_currentPage"><option value="1">1</option></select> <input style="font-weight: bold;" class="button-secondary"value=">" type="button" id="wpProQuiz_pageRight"> </div> <div style="clear: both;"></div> </div> </div> </div> <?php } } lib/view/WpProQuiz_View_QuestionOverall.php 0000666 00000014320 15214236625 0015135 0 ustar 00 <?php class WpProQuiz_View_QuestionOverall extends WpProQuiz_View_View { public function show() { global $learndash_question_types; ?> <style> .wpProQuiz_questionCopy { padding: 20px; background-color: rgb(223, 238, 255); border: 1px dotted; margin-top: 10px; display: none; } </style> <div class="wrap wpProQuiz_questionOverall"> <h1><?php echo LearnDash_Custom_Label::get_label( 'quiz' ) ?>: <?php echo $this->quiz->getName(); ?></h1> <div id="sortMsg" class="updated" style="display: none;"><p><strong><?php printf( // translators: placeholder: Questions. esc_html_x( '%s sorted', 'placeholder: Questions', 'learndash' ), LearnDash_Custom_Label::get_label( 'questions' ) ); ?></strong></p></div> <br> <p> <?php if(current_user_can('wpProQuiz_edit_quiz')) { ?> <a class="button-secondary" href="admin.php?page=ldAdvQuiz&module=question&action=addEdit&quiz_id=<?php echo $this->quiz->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>"><?php printf( // translators: placeholder: Question. esc_html_x( 'Add %s', 'placeholder: Question', 'learndash' ), LearnDash_Custom_Label::get_label( 'questions' ) ); ?></a> <?php } ?> </p> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col" style="width: 50px;"></th> <th scope="col"><?php esc_html_e('Name', 'learndash'); ?></th> <th scope="col"><?php esc_html_e('Type', 'learndash'); ?></th> <th scope="col"><?php esc_html_e('Category', 'learndash'); ?></th> <th scope="col"><?php esc_html_e('Points', 'learndash'); ?></th> </tr> </thead> <tbody> <?php $index = 1; $points = 0; if(count($this->question)) { foreach ($this->question as $question) { $points += $question->getPoints(); ?> <tr id="wpProQuiz_questionId_<?php echo $question->getId(); ?>"> <th><?php echo $index++; ?></th> <td> <strong><?php if ( current_user_can( 'wpProQuiz_edit_quiz' ) ) { $edit_link = add_query_arg( array( 'page' => 'ldAdvQuiz', 'module' => 'question', 'action' => 'addEdit', 'quiz_id' => $this->quiz->getId(), 'questionId' => $question->getId(), 'post_id' => @$_GET['post_id'] ), admin_url('admin.php') ); ?><a href="<?php echo $edit_link ?>"><?php } ?><?php echo $question->getTitle(); ?><?php if ( current_user_can( 'wpProQuiz_edit_quiz' ) ) { ?></a><?php } ?></strong> <div class="row-actions"> <?php if ( current_user_can( 'wpProQuiz_edit_quiz' ) ) { ?> <span><a href="admin.php?page=ldAdvQuiz&module=question&action=addEdit&quiz_id=<?php echo $this->quiz->getId(); ?>&questionId=<?php echo $question->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>"><?php esc_html_e('Edit', 'learndash'); ?></a> | </span> <?php } if(current_user_can('wpProQuiz_delete_quiz')) { ?> <span> <a style="color: red;" class="wpProQuiz_delete" href="admin.php?page=ldAdvQuiz&module=question&action=delete&quiz_id=<?php echo $this->quiz->getId(); ?>&id=<?php echo $question->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>"><?php esc_html_e('Delete', 'learndash'); ?></a> | </span> <?php } if(current_user_can('wpProQuiz_edit_quiz')) { ?> <span> <a class="wpProQuiz_move" href="#" style="cursor:move;"><?php esc_html_e('Move', 'learndash'); ?></a> </span> <?php } ?> </div> </td> <td> <?php $question_type = $question->getAnswerType(); if (isset($learndash_question_types[$question_type])) { echo $learndash_question_types[$question_type]; } ?> </td> <td> <?php echo $question->getCategoryName(); ?> </td> <td><?php echo $question->getPoints(); ?></td> </tr> <?php } } else { ?> <tr> <td colspan="5" style="text-align: center; font-weight: bold; padding: 10px;"><?php esc_html_e('No data available', 'learndash'); ?></td> </tr> <?php } ?> </tbody> <tfoot> <tr> <th></th> <th style="font-weight: bold;"><?php esc_html_e('Total', 'learndash'); ?></th> <th></th> <th></th> <th style="font-weight: bold;"><?php echo $points; ?></th> </tr> </tfoot> </table> <p> <?php do_action( 'learndash_questions_buttons_before' ); ?> <?php if(current_user_can('wpProQuiz_edit_quiz')) { ?> <a class="button-secondary" href="admin.php?page=ldAdvQuiz&module=question&action=addEdit&quiz_id=<?php echo $this->quiz->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>"><?php esc_html_e('Add question', 'learndash'); ?></a> <a class="button-secondary" href="#" id="wpProQuiz_saveSort"><?php esc_html_e('Save order', 'learndash'); ?></a> <a class="button-secondary" href="#" id="wpProQuiz_questionCopy"><?php echo sprintf( esc_html_x('Copy questions from another %s', 'Copy questions from another Quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?></a> <?php } ?> <?php do_action( 'learndash_questions_buttons_after' ); ?> </p> <?php do_action( 'learndash_questions_toolbox_before' ); ?> <div class="wpProQuiz_questionCopy"> <form action="admin.php?page=ldAdvQuiz&module=question&quiz_id=<?php echo $this->quiz->getId(); ?>&action=copy_question" method="POST"> <h2 style="margin-top: 0;"><?php echo sprintf( esc_html_x('Copy questions from another %s', 'Copy questions from another Quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?></h2> <p><?php echo sprintf( esc_html_x('Here you can copy questions from another %s into this %s. (Multiple selection enabled)', 'placeholders: quiz, quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); ?></p> <div style="padding: 20px; display: none;" id="loadDataImg"> <img alt="load" src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" /> <?php esc_html_e('Loading', 'learndash'); ?> </div> <div style="padding: 10px;"> <select name="copyIds[]" size="15" multiple="multiple" style="min-width: 200px; display: none;" id="questionCopySelect"> </select> </div> <input class="button-primary" name="questionCopy" value="<?php esc_html_e('Copy questions', 'learndash'); ?>" type="submit"> </form> </div> </div> <?php } } lib/view/WpProQuiz_View_QuizOverall.php 0000666 00000016403 15214236625 0014262 0 ustar 00 <?php class WpProQuiz_View_QuizOverall extends WpProQuiz_View_View { public function show() { ?> <style> .wpProQuiz_exportList ul { list-style: none; margin: 0; padding: 0; } .wpProQuiz_exportList li { float: left; padding: 3px; border: 1px solid #B3B3B3; margin-right: 5px; background-color: #F3F3F3; } .wpProQuiz_exportList, .wpProQuiz_importList { padding: 20px; background-color: rgb(223, 238, 255); border: 1px dotted; margin-top: 10px; display: none; } .wpProQuiz_exportCheck { display: none; } .learndash-pager a { font-size: 110%; padding: 3px } </style> <div class="wrap wpProQuiz_quizOverall" style="position: relative;"> <h1><?php echo sprintf( // translators: placeholder: Quiz. esc_html_x( '%s Import/Export', 'placeholder: Quiz', 'learndash' ), learndash_get_custom_label( 'quiz' ) ); ?></h1> <?php $quiz_page = 1; if ( ( isset( $_GET['paged'] ) ) && ( ! empty( $_GET['paged'] ) ) ) { $quiz_page = absint( $_GET['paged'] ); } if ( empty( $quiz_page ) ) { $quiz_page = 1; } $quiz_per_page = LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Section_General_Per_Page', 'quiz_num' ); $search_value = ''; if ( ( isset( $_GET['s'] ) ) && ( ! empty( $_GET['s'] ) ) ) { $search_value = esc_attr( $_GET['s'] ); } $quiz_query_args = array( 'post_type' => learndash_get_post_type_slug( 'quiz' ), 'post_status' => 'any', 'posts_per_page' => $quiz_per_page, 'paged' => $quiz_page, 'orderby' => 'title', 'order' => 'ASC', 'fields' => 'ID', 's' => $search_value ); if ( ( empty( $search_value ) ) && ( isset( $_GET['quiz_id'] ) ) && ( ! empty( $_GET['quiz_id'] ) ) ) { $quiz_query_args['post__in'] = array( absint( $_GET['quiz_id'] ) ); } $quiz_query_results = new WP_Query( $quiz_query_args ); ?> <form id="posts-filter" method="get"> <p class="search-box"> <label class="screen-reader-text" for="post-search-input">Search Courses:</label> <input type="hidden" name="page" value="ldAdvQuiz"> <input type="search" id="quiz-search-input" name="s" value="<?php echo $search_value ?>"> <input type="submit" id="search-submit" class="button" value="<?php echo sprintf( // translators: placeholder: Quiz. esc_html( 'Search %s', 'placeholder: Quiz', 'learndash' ), learndash_get_custom_label( 'quiz' ) ); ?>"> </p> </form> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col" width="30px" class="wpProQuiz_exportCheck"><input type="checkbox" name="exportItemsAll" value="0"></th> <th scope="col"><?php esc_html_e( 'Title', 'learndash' ); ?></th> <th scope="col"><?php esc_html_e( 'Settings', 'learndash' ); ?></th> </tr> </thead> <tbody> <?php if ( ( is_a( $quiz_query_results, 'WP_Query' ) ) && ( property_exists( $quiz_query_results, 'posts' ) ) && ( ! empty( $quiz_query_results->posts ) ) ) { foreach( $quiz_query_results->posts as $quiz_post ) { ?> <tr> <th class="wpProQuiz_exportCheck"><input type="checkbox" name="exportItems" value="<?php echo $quiz_post->ID; ?>"></th> <td class="wpProQuiz_quizName"> <strong><?php echo $quiz_post->ID; ?> - <?php echo get_the_title( $quiz_post->ID ); ?></strong> <?php if ( current_user_can( 'wpProQuiz_edit_quiz' ) ) { ?> <div class="row-actions"> <span> <a href="<?php echo get_edit_post_link( $quiz_post->ID ) ?>"><?php esc_html_e( 'edit', 'learndash' ); ?></a> </span> </div> <?php } ?> </td> <td class="wpProQuiz_quizName"> <?php $valid_quiz_pro = false; $quiz_pro_id = learndash_get_setting( $quiz_post->ID, 'quiz_pro' ); $quiz_pro_id = absint( $quiz_pro_id ); if ( ! empty( $quiz_pro_id ) ) { $quiz_mapper = new WpProQuiz_Model_QuizMapper(); $quiz_pro = $quiz_mapper->fetch( $quiz_pro_id ); if ( ( is_a( $quiz_pro, 'WpProQuiz_Model_Quiz' ) ) && ( $quiz_pro_id === $quiz_pro->getId() ) ) { $valid_quiz_pro = true; echo $quiz_pro_id . ' - ' . esc_attr( $quiz_pro->getName() ); } } if ( false === $valid_quiz_pro ) { ?><span class="ld-error"><?php esc_html_e( 'Missing ProQuiz Associated Settings.', 'learndash' ); ?></span><?php } ?> </td> </tr> <?php } } else { ?> <tr> <td colspan="3" style="text-align: center; font-weight: bold; padding: 10px;"><?php esc_html_e( 'No data available', 'learndash' ); ?></td> </tr> <?php } ?> </tbody> </table> <?php if ( is_a( $quiz_query_results, 'WP_Query' ) ) { $pager_results = array( 'paged' => $quiz_page, 'total_items' => absint( $quiz_query_results->found_posts ), 'total_pages' => absint( $quiz_query_results->max_num_pages ), ); echo SFWD_LMS::get_template( 'learndash_pager.php', array( 'href_query_arg' => 'paged', 'pager_results' => $pager_results, 'pager_context' => 'course_list', ) ); } ?> <p> <?php if(current_user_can('wpProQuiz_import')) { ?> <a class="button-secondary wpProQuiz_import" href="#"><?php esc_html_e('Import', 'learndash'); ?></a> <?php } if(current_user_can('wpProQuiz_export') && count($this->quiz)) { ?> <a class="button-secondary wpProQuiz_export" href="#"><?php esc_html_e('Export', 'learndash'); ?></a> <?php } ?> </p> <div class="wpProQuiz_exportList"> <form action="admin.php?page=ldAdvQuiz&module=importExport&action=export&noheader=true" method="POST"> <h3 style="margin-top: 0;"><?php esc_html_e('Export', 'learndash'); ?></h3> <p><?php esc_html_e('Choose the respective Quiz, which you would like to export and press on "Start export"', 'learndash'); ?></p> <div style="clear: both; margin-bottom: 10px;"></div> <div id="exportHidden"></div> <div style="margin-bottom: 15px;"> <?php esc_html_e('Format:', 'learndash'); ?> <label><input type="radio" name="exportType" value="wpq" checked="checked"> <?php esc_html_e('*.wpq', 'learndash'); ?></label> <?php esc_html_e('or', 'learndash'); ?> <label><input type="radio" name="exportType" value="xml"> <?php esc_html_e('*.xml', 'learndash'); ?></label> </div> <input class="button-primary" name="exportStart" id="exportStart" value="<?php esc_html_e('Start export', 'learndash'); ?>" type="submit"> </form> </div> <div class="wpProQuiz_importList"> <form action="admin.php?page=ldAdvQuiz&module=importExport&action=import" method="POST" enctype="multipart/form-data"> <h3 style="margin-top: 0;"><?php esc_html_e('Import', 'learndash'); ?></h3> <p><?php esc_html_e('Import only *.wpq or *.xml files from known and trusted sources.', 'learndash'); ?></p> <div style="margin-bottom: 10px"> <?php $maxUpload = (int)(ini_get('upload_max_filesize')); $maxPost = (int)(ini_get('post_max_size')); $memoryLimit = (int)(ini_get('memory_limit')); $uploadMB = min($maxUpload, $maxPost, $memoryLimit); ?> <input type="file" name="import" accept=".wpq,.xml" required="required"> <?php printf(__('Maximal %d MiB', 'learndash'), $uploadMB); ?> </div> <input class="button-primary" name="exportStart" id="exportStart" value="<?php esc_html_e('Start import', 'learndash'); ?>" type="submit"> </form> </div> </div> <?php } } lib/view/WpProQuiz_View_FrontQuiz.php 0000666 00000224563 15214236625 0013756 0 ustar 00 <?php class WpProQuiz_View_FrontQuiz extends WpProQuiz_View_View { /** * @var WpProQuiz_Model_Quiz */ public $quiz; private $_clozeTemp = array(); private $_assessmetTemp = array(); private $_shortcode_atts = array(); public function set_shortcode_atts( $atts = array() ) { $this->_shortcode_atts = $atts; } private function getFreeCorrect( $data ) { $t = str_replace( "\r\n", "\n", strtolower( $data->getAnswer() ) ); $t = str_replace( "\r", "\n", $t ); $t = explode( "\n", $t ); //return array_values( array_filter( array_map( 'trim', $t ) ) ); // In the consice line above we can't use the array_filter() function as // this will remove answer line values that are considered empty. // So for example if the answr value line is 0 (zero) then array_filter // will consider it as equal to false. // So instead we loop over the array (the hard way) and check for values equal to '' and removed. $t = array_map( 'trim', $t ); foreach( $t as $idx => $item ) { $item = trim($item); if ( $item == '' ) { unset( $t[$idx] ); } } return array_values( $t ); } public function show( $preview = false ) { $question_count = count( $this->question ); $result = $this->quiz->getResultText(); if ( ! $this->quiz->isResultGradeEnabled() ) { $result = array( 'text' => array( $result ), 'prozent' => array( 0 ) ); } $resultsProzent = json_encode( $result['prozent'] ); $quiz_meta = array( 'quiz_pro_id' => $this->quiz->getId(), 'quiz_post_id' => $this->quiz->getPostId(), ); ?> <div class="wpProQuiz_content" id="wpProQuiz_<?php echo $this->quiz->getId(); ?>" data-quiz-meta="<?php echo htmlspecialchars( wp_json_encode( $quiz_meta ) ); ?>"> <div class="wpProQuiz_spinner" style="display:none"> <div></div> </div> <?php if ( ! $this->quiz->isTitleHidden() ) { echo '<h2>', $this->quiz->getName(), '</h2>'; } LD_QuizPro::showQuizContent( $this->quiz->getID() ); $this->showTimeLimitBox(); $this->showCheckPageBox( $question_count ); $this->showInfoPageBox(); $this->showStartQuizBox(); $this->showUserQuizStatisticsBox(); $this->showLockBox(); $this->showLoadQuizBox(); $this->showStartOnlyRegisteredUserBox(); $this->showPrerequisiteBox(); $this->showResultBox( $result, $question_count ); if ( $this->quiz->getToplistDataShowIn() == WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SHOW_IN_BUTTON ) { $this->showToplistInButtonBox(); } $this->showReviewBox( $question_count ); $this->showQuizAnker(); $quizData = $this->showQuizBox( $question_count ); ?> </div> <?php if ( $preview ) { add_action( "admin_footer", array( $this, "script_preview" ) ); } else { //add_action( "wp_footer", array( $this, "script" ) ); add_action( "wp_print_footer_scripts", array( $this, "script" ), 999 ); } } public function script_preview() { $this->script( true ); } public function script( $preview = false ) { if ( ( isset( $this->_shortcode_atts['quiz_id'] ) ) && ( ! empty( $this->_shortcode_atts['quiz_id'] ) ) ) { $post = get_post( absint( $this->_shortcode_atts['quiz_id'] ) ); } else { $post = get_queried_object(); } if ( ( empty( $post ) ) || ( !is_a( $post, 'WP_Post' ) ) ) { return; } $question_count = count( $this->question ); $result = $this->quiz->getResultText(); if ( ! $this->quiz->isResultGradeEnabled() ) { $result = array( 'text' => array( $result ), 'prozent' => array( 0 ) ); } $resultsProzent = json_encode( $result['prozent'] ); ob_start(); $quizData = $this->showQuizBox( $question_count ); ob_get_clean(); foreach ( $quizData['json'] as $key => $value ) { foreach ( array( "points", "correct" ) as $key2 ) { unset( $quizData['json'][ $key ][ $key2 ] ); } } $user_id = get_current_user_id(); $bo = $this->createOption( $preview ); if ( ( isset( $this->_shortcode_atts['quiz_pro_id'] ) ) && ( ! empty( $this->_shortcode_atts['quiz_pro_id'] ) ) ) { $quiz_pro_id = absint( $this->_shortcode_atts['quiz_pro_id'] ); } else { if ( @$post->post_type != "sfwd-quiz" ) { $quiz_pro_id = $this->quiz->getId(); } } if ( ( isset( $this->_shortcode_atts['quiz_id'] ) ) && ( ! empty( $this->_shortcode_atts['quiz_id'] ) ) ) { $quiz_post_id = absint( $this->_shortcode_atts['quiz_id'] ); } else { if ( @$post->post_type != "sfwd-quiz" ) { $quiz_post_id = learndash_get_quiz_id_by_pro_quiz_id( $quiz_pro_id ); } } if ( ( isset( $quiz_post_id ) ) && ( ! empty( $quiz_post_id ) ) ) { $quiz_meta = get_post_meta( $quiz_post_id, '_sfwd-quiz', true ); } else { $quiz_meta = array(); } if ((isset($quiz_meta['sfwd-quiz_passingpercentage'])) && (!empty($quiz_meta['sfwd-quiz_passingpercentage']))){ $quiz_meta_sfwd_quiz_passingpercentage = floatval($quiz_meta['sfwd-quiz_passingpercentage']); } else { $quiz_meta_sfwd_quiz_passingpercentage = 0; } $ld_script_debug = 0; if (isset($_GET['LD_DEBUG'])) { $ld_script_debug = true; } if ( ( isset( $this->_shortcode_atts['course_id'] ) ) && ( ! empty( $this->_shortcode_atts['course_id'] ) ) ) { $course_id = absint( $this->_shortcode_atts['course_id'] ); } else { $course_id = learndash_get_course_id(); } if ( ( empty( $course_id ) ) || ( is_null( $course_id ) ) ) { $course_id = 0; } // Lesson ID if ( ( isset( $this->_shortcode_atts['lesson_id'] ) ) && ( ! empty( $this->_shortcode_atts['lesson_id'] ) ) ) { $lesson_id = absint( $this->_shortcode_atts['lesson_id'] ); } else { $lesson_id = learndash_course_get_single_parent_step( $course_id, $quiz_post_id, 'sfwd-lessons' ); } if (( empty( $lesson_id ) ) || ( is_null( $lesson_id ) )) $lesson_id = 0; // Topic ID if ( ( isset( $this->_shortcode_atts['topic_id'] ) ) && ( ! empty( $this->_shortcode_atts['topic_id'] ) ) ) { $topic_id = absint( $this->_shortcode_atts['topic_id'] ); } else { $topic_id = learndash_course_get_single_parent_step( $course_id, $quiz_post_id, 'sfwd-topic' ); } if ( ( empty( $topic_id ) ) || ( is_null( $topic_id ) ) ) { $topic_id = 0; } $quiz_nonce = ''; if ( !empty( $user_id ) ) { $quiz_nonce = wp_create_nonce( 'sfwd-quiz-nonce-' . $quiz_post_id . '-'. $quiz_pro_id .'-' . $user_id ); } else { $quiz_nonce = wp_create_nonce( 'sfwd-quiz-nonce-' . $quiz_post_id . '-'. $quiz_pro_id .'-0'); } echo " <script type='text/javascript'> function load_wpProQuizFront" . $this->quiz->getId() . "() { jQuery('#wpProQuiz_" . $this->quiz->getId() . "').wpProQuizFront({ course_id: ". $course_id .", lesson_id: ". $lesson_id .", topic_id: ". $topic_id .", quiz: " . $quiz_post_id . ", quizId: " . (int) $this->quiz->getId() . ", mode: " . (int) $this->quiz->getQuizModus() . ", globalPoints: " . (int) $quizData['globalPoints'] . ", timelimit: " . (int) $this->quiz->getTimeLimit() . ", timelimitcookie: " . intval($this->quiz->getTimeLimitCookie()) . ", resultsGrade: " . $resultsProzent . ", bo: " . $bo . ", passingpercentage: ". $quiz_meta_sfwd_quiz_passingpercentage .", user_id: " . $user_id . ", qpp: " . $this->quiz->getQuestionsPerPage() . ", catPoints: " . json_encode( $quizData['catPoints'] ) . ", formPos: " . (int) $this->quiz->getFormShowPosition() . ", essayUploading: '" . SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_uploading', 'message' => esc_html__('Uploading', 'learndash' ) ) ) . "', essaySuccess: '" . SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_success', 'message' => esc_html__('Success', 'learndash' ) ) ) . "', lbn: " . json_encode( ( $this->quiz->isShowReviewQuestion() && ! $this->quiz->isQuizSummaryHide() ) ? SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_summary_button_label', 'message' => sprintf( esc_html_x( '%s Summary', 'Quiz Summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) ) : SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_finish_button_label', 'message' => sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) ) ) . ", json: " . json_encode( $quizData['json'] ) . ", ld_script_debug: ". $ld_script_debug .", quiz_nonce: '". $quiz_nonce ."' }); } var loaded_wpProQuizFront" . $this->quiz->getId() . " = 0; jQuery(document).ready(function($) { load_wpProQuizFront" . $this->quiz->getId() . "(); loaded_wpProQuizFront" . $this->quiz->getId() . " = 1; }); jQuery(window).on('load',function($) { if(loaded_wpProQuizFront" . $this->quiz->getId() . " == 0) load_wpProQuizFront" . $this->quiz->getId() . "(); }); </script> "; } public function max_question_script() { $question_count = count( $this->question ); $result = $this->quiz->getResultText(); if ( ! $this->quiz->isResultGradeEnabled() ) { $result = array( 'text' => array( $result ), 'prozent' => array( 0 ) ); } $resultsProzent = json_encode( $result['prozent'] ); $user_id = get_current_user_id(); $bo = $this->createOption( false ); //global $post; $post = get_queried_object(); if ( @$post->post_type != "sfwd-quiz" ) { $quiz_id = $this->quiz->getId(); $quiz_post_id = learndash_get_quiz_id_by_pro_quiz_id( $quiz_id ); } else { $quiz_post_id = (empty($post->ID))? '0':$post->ID; $quiz_meta = get_post_meta( $quiz_post_id, '_sfwd-quiz', true ); } if ((isset($quiz_meta['sfwd-quiz_passingpercentage'])) && (!empty($quiz_meta['sfwd-quiz_passingpercentage']))){ $quiz_meta_sfwd_quiz_passingpercentage = intval($quiz_meta['sfwd-quiz_passingpercentage']); } else { $quiz_meta_sfwd_quiz_passingpercentage = 0; } // If the Quiz URL contains the query string parameter 'LD_DEBUG' to turn on debug output (console.log()) in the JS $ld_script_debug = 0; if (isset($_GET['LD_DEBUG'])) { $ld_script_debug = true; } $course_id = learndash_get_course_id(); if (( empty( $course_id ) ) || ( is_null( $course_id ) )) $course_id = 0; // Lesson ID $lesson_id = learndash_course_get_single_parent_step( $course_id, $quiz_post_id, 'sfwd-lessons' ); if (( empty( $lesson_id ) ) || ( is_null( $lesson_id ) )) $lesson_id = 0; // Topic ID $topic_id = learndash_course_get_single_parent_step( $course_id, $quiz_post_id, 'sfwd-topic' ); if (( empty( $topic_id ) ) || ( is_null( $topic_id ) )) $topic_id = 0; $quiz_nonce = ''; if ( !empty( $user_id ) ) { $quiz_nonce = wp_create_nonce( 'sfwd-quiz-nonce-' . $quiz_post_id . '-'. $this->quiz->getId() .'-'. $user_id ); } else { $quiz_nonce = wp_create_nonce( 'sfwd-quiz-nonce-' . $quiz_post_id . '-'. $this->quiz->getId() .'-'. '0' ); } // Original // lbn: " . json_encode( ( $this->quiz->isShowReviewQuestion() && ! $this->quiz->isQuizSummaryHide() ) ? sprintf( esc_html_x( '%s-summary', 'Quiz-summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) : sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) . " echo "<script type='text/javascript'> jQuery(document).ready(function($) { $('#wpProQuiz_" . $this->quiz->getId() . "').wpProQuizFront({ course_id: ". $course_id .", lesson_id: ". $lesson_id .", topic_id: ". $topic_id .", quiz: " . $quiz_post_id . ", quizId: " . (int) $this->quiz->getId() . ", mode: " . (int) $this->quiz->getQuizModus() . ", timelimit: " . (int) $this->quiz->getTimeLimit() . ", timelimitcookie: " . intval($this->quiz->getTimeLimitCookie()) . ", resultsGrade: " . $resultsProzent . ", bo: " . $bo . ", passingpercentage: ". $quiz_meta_sfwd_quiz_passingpercentage .", user_id: " . $user_id . ", qpp: " . $this->quiz->getQuestionsPerPage() . ", formPos: " . (int) $this->quiz->getFormShowPosition() . ", ld_script_debug: ". $ld_script_debug .", quiz_nonce: '". $quiz_nonce ."', essayUploading: '" . SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_uploading', 'message' => esc_html__('Uploading', 'learndash' ) ) ) . "', essaySuccess: '" . SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_success', 'message' => esc_html__('Success', 'learndash' ) ) ) . "', lbn: " . json_encode( ( $this->quiz->isShowReviewQuestion() && ! $this->quiz->isQuizSummaryHide() ) ? SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_summary_button_label', 'message' => sprintf( esc_html_x( '%s Summary', 'Quiz Summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) ) : SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_finish_button_label', 'message' => sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) ) ) . " }); }); </script>"; } private function createOption( $preview ) { $bo = 0; $bo |= ( (int) $this->quiz->isAnswerRandom() ) << 0; $bo |= ( (int) $this->quiz->isQuestionRandom() ) << 1; $bo |= ( (int) $this->quiz->isDisabledAnswerMark() ) << 2; $bo |= ( (int) ( $this->quiz->isQuizRunOnce() || $this->quiz->isPrerequisite() || $this->quiz->isStartOnlyRegisteredUser() ) ) << 3; $bo |= ( (int) $preview ) << 4; $bo |= ( (int) get_option( 'wpProQuiz_corsActivated' ) ) << 5; $bo |= ( (int) $this->quiz->isToplistDataAddAutomatic() ) << 6; $bo |= ( (int) $this->quiz->isShowReviewQuestion() ) << 7; $bo |= ( (int) $this->quiz->isQuizSummaryHide() ) << 8; $bo |= ( (int) ( $this->quiz->isSkipQuestion() && $this->quiz->isShowReviewQuestion() ) ) << 9; $bo |= ( (int) $this->quiz->isAutostart() ) << 10; $bo |= ( (int) $this->quiz->isForcingQuestionSolve() ) << 11; $bo |= ( (int) $this->quiz->isHideQuestionPositionOverview() ) << 12; $bo |= ( (int) $this->quiz->isFormActivated() ) << 13; $bo |= ( (int) $this->quiz->isShowMaxQuestion() ) << 14; $bo |= ( (int) $this->quiz->isSortCategories() ) << 15; return $bo; } public function showMaxQuestion() { $question_count = count( $this->question ); $result = $this->quiz->getResultText(); if ( ! $this->quiz->isResultGradeEnabled() ) { $result = array( 'text' => array( $result ), 'prozent' => array( 0 ) ); } $resultsProzent = json_encode( $result['prozent'] ); ?> <div class="wpProQuiz_content" id="wpProQuiz_<?php echo $this->quiz->getId(); ?>"> <?php if ( ! $this->quiz->isTitleHidden() ) { echo '<h2>', $this->quiz->getName(), '</h2>'; } LD_QuizPro::showQuizContent( $this->quiz->getID() ); $this->showTimeLimitBox(); $this->showCheckPageBox( $question_count ); $this->showInfoPageBox(); $this->showStartQuizBox(); $this->showUserQuizStatisticsBox(); $this->showLockBox(); $this->showLoadQuizBox(); $this->showStartOnlyRegisteredUserBox(); $this->showPrerequisiteBox(); $this->showResultBox( $result, $question_count ); if ( $this->quiz->getToplistDataShowIn() == WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SHOW_IN_BUTTON ) { $this->showToplistInButtonBox(); } $this->showReviewBox( $question_count ); $this->showQuizAnker(); ?> </div> <?php add_action( "wp_footer", array( $this, "max_question_script" ), 20 ); } public function getQuizData() { ob_start(); $quizData = $this->showQuizBox( count( $this->question ) ); $quizData['content'] = ob_get_contents(); $quizData['site_url'] = get_site_url(); ob_end_clean(); return $quizData; } private function showQuizAnker() { ?> <div class="wpProQuiz_quizAnker" style="display: none;"></div> <?php } private function showAddToplist() { ?> <div class="wpProQuiz_addToplist" style="display: none;"> <?php /* ?><span style="font-weight: bold;"><?php esc_html_e( 'Your result has been entered into leaderboard', 'learndash' ); ?></span><?php */ ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_toplist_results_message', 'message' => '<span style="font-weight: bold;">'. esc_html__( 'Would you like to submit your quiz result to the leaderboard?', 'learndash' ) .'</span>' ) ); ?> <div style="margin-top: 6px;"> <div class="wpProQuiz_addToplistMessage" style="display: none;"><?php esc_html_e( 'Loading', 'learndash' ); ?></div> <div class="wpProQuiz_addBox"> <div> <span> <label> <?php esc_html_e( 'Name', 'learndash' ); ?>: <input type="text" placeholder="<?php esc_html_e( 'Name', 'learndash' ); ?>" name="wpProQuiz_toplistName" maxlength="15" size="16" style="width: 150px;"> </label> <label> <?php esc_html_e( 'E-Mail', 'learndash' ); ?>: <input type="email" placeholder="<?php esc_html_e( 'E-Mail', 'learndash' ); ?>" name="wpProQuiz_toplistEmail" size="20" style="width: 150px;"> </label> </span> <div style="margin-top: 5px;"> <label> <?php esc_html_e( 'Captcha', 'learndash' ); ?>: <input type="text" name="wpProQuiz_captcha" size="8" style="width: 50px;"> </label> <input type="hidden" name="wpProQuiz_captchaPrefix" value="0"> <img alt="captcha" src="" class="wpProQuiz_captchaImg" style="vertical-align: middle;"> </div> </div> <input class="wpProQuiz_button2" type="submit" value="<?php esc_html_e( 'Send', 'learndash' ); ?>" name="wpProQuiz_toplistAdd"> </div> </div> </div> <?php } private function fetchCloze( $answer_text ) { preg_match_all( '#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', $answer_text, $matches, PREG_SET_ORDER ); $data = array(); foreach ( $matches as $k => $v ) { $text = $v[1]; $points = ! empty( $v[2] ) ? (int) $v[2] : 1; $rowText = $multiTextData = array(); $len = array(); if ( preg_match_all( '#\[(.*?)\]#im', $text, $multiTextMatches ) ) { foreach ( $multiTextMatches[1] as $multiText ) { if ( function_exists( 'mb_strtolower' ) ) $x = mb_strtolower( trim( html_entity_decode( $multiText, ENT_QUOTES ) ) ); else $x = strtolower( trim( html_entity_decode( $multiText, ENT_QUOTES ) ) ); $len[] = strlen( $x ); $multiTextData[] = $x; $rowText[] = $multiText; } } else { if ( function_exists( 'mb_strtolower' ) ) $x = mb_strtolower( trim( html_entity_decode( $text, ENT_QUOTES ) ) ); else $x = strtolower( trim( html_entity_decode( $text, ENT_QUOTES ) ) ); $len[] = strlen( $x ); $multiTextData[] = $x; $rowText[] = $text; } $a = '<span class="wpProQuiz_cloze"><input data-wordlen="' . max( $len ) . '" type="text" value=""> '; $a .= '<span class="wpProQuiz_clozeCorrect" style="display: none;"></span></span>'; $data['correct'][] = $multiTextData; $data['points'][] = $points; $data['data'][] = $a; } $data['replace'] = preg_replace( '#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', '@@wpProQuizCloze@@', $answer_text ); return $data; } private function clozeCallback( $t ) { $a = array_shift( $this->_clozeTemp ); return $a === null ? '' : $a; } private function fetchAssessment( $answerText, $quizId, $questionId ) { $answerText = apply_filters( 'learndash_quiz_question_answer_preprocess', $answerText, 'assessment' ); preg_match_all( '#\{(.*?)\}#im', $answerText, $matches ); $this->_assessmetTemp = array(); $data = array(); for ( $i = 0, $ci = count( $matches[1] ); $i < $ci; $i ++ ) { $match = $matches[1][ $i ]; preg_match_all( '#\[([^\|\]]+)(?:\|(\d+))?\]#im', $match, $ms ); $a = ''; for ( $j = 0, $cj = count( $ms[1] ); $j < $cj; $j ++ ) { $v = $ms[1][ $j ]; $a .= '<label> <input type="radio" value="' . ( $j + 1 ) . '" name="question_' . $quizId . '_' . $questionId . '_' . $i . '" class="wpProQuiz_questionInput" data-index="' . $i . '"> ' . $v . ' </label>'; } $this->_assessmetTemp[] = $a; } $data['replace'] = preg_replace( '#\{(.*?)\}#im', '@@wpProQuizAssessment@@', $answerText ); return $data; } private function assessmentCallback( $t ) { $a = array_shift( $this->_assessmetTemp ); return $a === null ? '' : $a; } private function showFormBox() { $info = '<div class="wpProQuiz_invalidate">' . esc_html__( 'You must fill out this field.', 'learndash' ) . '</div>'; $validateText = array( WpProQuiz_Model_Form::FORM_TYPE_NUMBER => esc_html__( 'You must specify a number.', 'learndash' ), WpProQuiz_Model_Form::FORM_TYPE_TEXT => esc_html__( 'You must specify a text.', 'learndash' ), WpProQuiz_Model_Form::FORM_TYPE_EMAIL => esc_html__( 'You must specify an email address.', 'learndash' ), WpProQuiz_Model_Form::FORM_TYPE_DATE => esc_html__( 'You must specify a date.', 'learndash' ) ); ?> <div class="wpProQuiz_forms"> <table> <tbody> <?php $index = 0; foreach ( $this->forms as $form ) { /* @var $form WpProQuiz_Model_Form */ $id = 'forms_' . $this->quiz->getId() . '_' . $index ++; $name = 'wpProQuiz_field_' . $form->getFormId(); ?> <tr> <td> <?php echo '<label for="' . $id . '">'; echo esc_html( $form->getFieldname() ); echo $form->isRequired() ? '<span class="wpProQuiz_required">*</span>' : ''; echo '</label>'; ?> </td> <td> <?php switch ( $form->getType() ) { case WpProQuiz_Model_Form::FORM_TYPE_TEXT: case WpProQuiz_Model_Form::FORM_TYPE_EMAIL: case WpProQuiz_Model_Form::FORM_TYPE_NUMBER: echo '<input name="' . $name . '" id="' . $id . '" type="text" ', 'data-required="' . (int) $form->isRequired() . '" data-type="' . $form->getType() . '" data-form_id="' . $form->getFormId() . '">'; break; case WpProQuiz_Model_Form::FORM_TYPE_TEXTAREA: echo '<textarea rows="5" cols="20" name="' . $name . '" id="' . $id . '" ', 'data-required="' . (int) $form->isRequired() . '" data-type="' . $form->getType() . '" data-form_id="' . $form->getFormId() . '"></textarea>'; break; case WpProQuiz_Model_Form::FORM_TYPE_CHECKBOX: echo '<input name="' . $name . '" id="' . $id . '" type="checkbox" value="1"', 'data-required="' . (int) $form->isRequired() . '" data-type="' . $form->getType() . '" data-form_id="' . $form->getFormId() . '">'; break; case WpProQuiz_Model_Form::FORM_TYPE_DATE: echo '<div data-required="' . (int) $form->isRequired() . '" data-type="' . $form->getType() . '" class="wpProQuiz_formFields" data-form_id="' . $form->getFormId() . '">'; echo WpProQuiz_Helper_Until::getDatePicker( get_option( 'date_format', 'j. F Y' ), $name ); echo '</div>'; break; case WpProQuiz_Model_Form::FORM_TYPE_RADIO: echo '<div data-required="' . (int) $form->isRequired() . '" data-type="' . $form->getType() . '" class="wpProQuiz_formFields" data-form_id="' . $form->getFormId() . '">'; if ( $form->getData() !== null ) { foreach ( $form->getData() as $data ) { echo '<label>'; echo '<input name="' . $name . '" type="radio" value="' . esc_attr( $data ) . '"> ', esc_html( $data ); echo '</label> '; } } echo '</div>'; break; case WpProQuiz_Model_Form::FORM_TYPE_SELECT: if ( $form->getData() !== null ) { echo '<select name="' . $name . '" id="' . $id . '" ', 'data-required="' . (int) $form->isRequired() . '" data-type="' . $form->getType() . '" data-form_id="' . $form->getFormId() . '">'; echo '<option value=""></option>'; foreach ( $form->getData() as $data ) { echo '<option value="' . esc_attr( $data ) . '">', esc_html( $data ), '</option>'; } echo '</select>'; } break; case WpProQuiz_Model_Form::FORM_TYPE_YES_NO: echo '<div data-required="' . (int) $form->isRequired() . '" data-type="' . $form->getType() . '" class="wpProQuiz_formFields" data-form_id="' . $form->getFormId() . '">'; echo '<label>'; echo '<input name="' . $name . '" type="radio" value="1"> ', esc_html__( 'Yes', 'learndash' ); echo '</label> '; echo '<label>'; echo '<input name="' . $name . '" type="radio" value="0"> ', esc_html__( 'No', 'learndash' ); echo '</label> '; echo '</div>'; break; } if ( isset( $validateText[ $form->getType() ] ) ) { echo '<div class="wpProQuiz_invalidate">' . $validateText[ $form->getType() ] . '</div>'; } else { echo '<div class="wpProQuiz_invalidate">' . esc_html__( 'You must fill out this field.', 'learndash' ) . '</div>'; } ?> </td> </tr> <?php } ?> </tbody> </table> </div> <?php } private function showLockBox() { ?> <div style="display: none;" class="wpProQuiz_lock"> <?php /* ?> <p> <?php echo sprintf( esc_html_x( 'You have already completed the %s before. Hence you can not start it again.', 'You have already completed the quiz before. Hence you can not start it again.', 'learndash' ), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> <?php */ ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_locked_message', 'message' => '<p>'. sprintf( esc_html_x( 'You have already completed the %s before. Hence you can not start it again.', 'You have already completed the quiz before. Hence you can not start it again.', 'learndash' ), learndash_get_custom_label_lower( 'quiz' ) ) .'</p>' ) ); ?> </div> <?php } private function showStartOnlyRegisteredUserBox() { ?> <div style="display: none;" class="wpProQuiz_startOnlyRegisteredUser"> <?php /* ?> <p> <?php echo sprintf( esc_html_x( 'You must sign in or sign up to start the %s.', 'You must sign in or sign up to start the quiz.', 'learndash' ), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> <?php */ ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_only_registered_user_message', 'message' => '<p>'. sprintf( esc_html_x( 'You must sign in or sign up to start the %s.', 'You must sign in or sign up to start the quiz.', 'learndash' ), learndash_get_custom_label_lower( 'quiz' ) ) .'</p>' ) ); ?> </div> <?php } private function showPrerequisiteBox() { ?> <div style="display: none;" class="wpProQuiz_prerequisite"> <?php /* ?> <p> <?php echo sprintf( esc_html_x( "You have to pass the previous Module's %s in order to start this %s", "You have to pass the previous Module's Quiz in order to start this Quiz", 'learndash' ), learndash_get_custom_label_lower( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); ?> <span></span> </p> <?php */ ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_prerequisite_message', 'message' => '<p>'. esc_html__( "You must first complete the following:", 'learndash' ) .' <span></span></p>' ) ); ?> </div> <?php } private function showCheckPageBox( $questionCount ) { ?> <div class="wpProQuiz_checkPage" style="display: none;"> <h4 class="wpProQuiz_header"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_summary_header', 'message' => sprintf( esc_html_x( '%s Summary', 'Quiz Summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) ); ?></h4> <?php /* ?> <p> <?php printf( esc_html__( '%s of %s questions completed', 'learndash' ), '<span>0</span>', $questionCount ); ?> </p> <?php */ ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_checkbox_questions_complete_message', 'message' => '<p>'. sprintf( esc_html_x( '%1$s of %2$s questions completed', 'placeholders: quiz count completed, quiz count total', 'learndash' ), '<span>0</span>', $questionCount ) .'</p>', 'placeholders' => array( '0', $questionCount ) ) ); ?> <p><?php esc_html_e( 'Questions', 'learndash' ); ?>:</p> <div style="margin-bottom: 20px;" class="wpProQuiz_box"> <ol> <?php for ( $xy = 1; $xy <= $questionCount; $xy ++ ) { ?> <li><?php echo $xy; ?></li> <?php } ?> </ol> <div style="clear: both;"></div> </div> <?php if ( $this->quiz->isFormActivated() && $this->quiz->getFormShowPosition() == WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_END && ( $this->quiz->isShowReviewQuestion() && ! $this->quiz->isQuizSummaryHide() ) ) { ?> <h4 class="wpProQuiz_header"><?php esc_html_e( 'Information', 'learndash' ); ?></h4> <?php $this->showFormBox(); } ?> <input type="button" name="endQuizSummary" value="<?php //echo sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ); echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_finish_button_label', 'message' => sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) )); ?>" class="wpProQuiz_button"> </div> <?php } private function showInfoPageBox() { ?> <div class="wpProQuiz_infopage" style="display: none;"> <h4><?php esc_html_e( 'Information', 'learndash' ); ?></h4> <?php if ( $this->quiz->isFormActivated() && $this->quiz->getFormShowPosition() == WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_END && ( ! $this->quiz->isShowReviewQuestion() || $this->quiz->isQuizSummaryHide() ) ) { $this->showFormBox(); } ?> <input type="button" name="endInfopage" value="<?php //echo sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ); echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_finish_button_label', 'message' => sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) )); ?>" class="wpProQuiz_button"> </div> <?php } private function showStartQuizBox() { ?> <div class="wpProQuiz_text"> <?php if ( $this->quiz->isFormActivated() && $this->quiz->getFormShowPosition() == WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_START ) { $this->showFormBox(); } ?> <div> <input class="wpProQuiz_button" type="button" value="<?php //echo sprintf( esc_html_x( 'Start %s', 'Start Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ); echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_start_button_label', 'message' => sprintf( esc_html_x( 'Start %s', 'Start Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) )); ?>" name="startQuiz"> </div> </div> <?php } private function showUserQuizStatisticsBox() { // For now don't use. return; global $post; //error_log('post<pre>'. print_r($post, true) .'</pre>'); if ( current_user_can( 'wpProQuiz_show_statistics' ) ) { $user_quizzes = get_user_meta(get_current_user_id(), '_sfwd-quizzes', true); //error_log('user_quizzes<pre>'. print_r($user_quizzes, true) .'</pre>'); if ( !empty( $user_quizzes ) ) { //krsort($user_quizzes); $user_quizzes = array_reverse($user_quizzes); //error_log('sorted: user_quizzes<pre>'. print_r($user_quizzes, true) .'</pre>'); foreach( $user_quizzes as $user_quiz_idx => $user_quiz ) { if ( ( isset( $user_quiz['quiz'] ) ) && ( $user_quiz['quiz'] == $post->ID ) ) { if ( ( isset( $user_quiz['pro_quizid'] ) ) && ( $user_quiz['pro_quizid'] == $this->quiz->getID() ) ) { if ( ( isset( $user_quiz['statistic_ref_id'] ) ) && ( !empty($user_quiz['statistic_ref_id']) ) ) { //error_log('found idx['. $user_quiz_idx .']'); ?> <div class="wpProQuiz_text"> <div> <input class="wpProQuiz_button" type="button" value="<?php //echo sprintf( esc_html_x( 'View %s Statistics', 'Start Quiz Statistics Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ); echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_view_statistics_button_label', 'message' => sprintf( esc_html_x( 'View %s Statistics', 'Start Quiz Statistics Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) )); ?>" name="viewUserQuizStatistics" data-quiz_id="<?php echo $user_quiz['pro_quizid'] ?>" data-ref_id="<?php echo intval( $user_quiz['statistic_ref_id'] ) ?>" /> </div> </div> <?php LD_QuizPro::showModalWindow(); return; } } } } } } } private function showTimeLimitBox() { ?> <div style="display: none;" class="wpProQuiz_time_limit"> <div class="time"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_time_limit_message', 'message' => esc_html__( 'Time limit', 'learndash' ) .': <span>0</span>' ) ); ?> </div> <div class="wpProQuiz_progress"></div> </div> <?php } private function showReviewBox( $questionCount ) { ?> <div class="wpProQuiz_reviewDiv" style="display: none;"> <div class="wpProQuiz_reviewQuestion"> <ol> <?php for ( $xy = 1; $xy <= $questionCount; $xy ++ ) { ?> <li><?php echo $xy; ?></li> <?php } ?> </ol> <div style="display: none;"></div> </div> <div class="wpProQuiz_reviewLegend"> <ol> <li> <span class="wpProQuiz_reviewColor wpProQuiz_reviewColor_Answer"></span> <span class="wpProQuiz_reviewText"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_answered_message', 'message' => esc_html__( 'Answered', 'learndash' ) ) ); ?></span> </li> <li> <span class="wpProQuiz_reviewColor wpProQuiz_reviewColor_Review"></span> <span class="wpProQuiz_reviewText"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_review_message', 'message' => esc_html__( 'Review', 'learndash' ) ) ); ?></span> </li> </ol> <div style="clear: both;"></div> </div> <div> <?php if ( $this->quiz->getQuizModus() != WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE ) { ?> <input type="button" name="review" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_review_question_button_label', 'message' => esc_html__( 'Review question', 'learndash' ) ) )); ?>" class="wpProQuiz_button2" style="float: left; display: block;"> <?php if ( ! $this->quiz->isQuizSummaryHide() ) { ?> <input type="button" name="quizSummary" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_summary_button_label', 'message' => sprintf( esc_html_x( '%s Summary', 'Quiz Summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) )); ?>" class="wpProQuiz_button2" style="float: right;"> <?php } ?> <div style="clear: both;"></div> <?php } ?> </div> </div> <?php } private function showResultBox( $result, $questionCount ) { ?> <div style="display: none;" class="wpProQuiz_sending"> <h4 class="wpProQuiz_header"><?php esc_html_e( 'Results', 'learndash' ); ?></h4> <p> <div><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_complete_message', 'message' => sprintf( esc_html_x( "%s complete. Results are being recorded.", "Quiz complete. Results are being recorded.", 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ), ) ); ?></div> <div> <dd class="course_progress"> <div class="course_progress_blue sending_progress_bar" style="width: 0%;"> </div> </dd> </div> </p> </div> <div style="display: none;" class="wpProQuiz_results"> <h4 class="wpProQuiz_header"><?php esc_html_e( 'Results', 'learndash' ); ?></h4> <?php if ( ! $this->quiz->isHideResultCorrectQuestion() ) { ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_questions_answered_correctly_message', 'message' => '<p>'. sprintf( esc_html_x( '%1$s of %2$s questions answered correctly', 'placeholder: correct answer, question count', 'learndash' ), '<span class="wpProQuiz_correct_answer">0</span>', '<span>' . $questionCount . '</span>' ) .'</p>', 'placeholders' => array( '0', $questionCount ) ) ); ?> <?php } if ( ! $this->quiz->isHideResultQuizTime() ) { ?> <p class="wpProQuiz_quiz_time"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_your_time_message', 'message' => sprintf( esc_html_x( 'Your time: %s', 'placeholder: quiz time.', 'learndash' ), '<span></span>') ) ); ?> </p> <?php } ?> <p class="wpProQuiz_time_limit_expired" style="display: none;"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_time_has_elapsed_message', 'message' => esc_html__( 'Time has elapsed', 'learndash' ) ) ); ?> </p> <?php if ( ! $this->quiz->isHideResultPoints() ) { ?> <p class="wpProQuiz_points"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_have_reached_points_message', 'message' => sprintf( esc_html_x( 'You have reached %1$s of %2$s point(s), (%3$s)', 'placeholder: points earned, points total', 'learndash' ), '<span>0</span>', '<span>0</span>', '<span>0</span>' ), 'placeholders' => array( '0', '0', '0' ) ) ); ?> </p> <p class="wpProQuiz_graded_points" style="display: none;"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_earned_points_message', 'message' => sprintf( esc_html_x( 'Earned Point(s): %1$s of %2$s, (%3$s)', 'placeholder: points earned, points total, points percentage', 'learndash' ), '<span>0</span>', '<span>0</span>', '<span>0</span>' ), 'placeholders' => array( '0', '0', '0' ) ) ); ?><br /> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_possible_points_message', 'message' => sprintf( esc_html_x( '%1$s Essay(s) Pending (Possible Point(s): %2$s)', 'placeholder: number of essays, possible points ', 'learndash' ), '<span>0</span>', '<span>0</span>' ), 'placeholders' => array( '0', '0' ) ) ); ?><br /> </p> <?php } ?> <?php if ( is_user_logged_in() ) { ?> <p class="wpProQuiz_certificate" style="display: none ;"> <?php echo LD_QuizPro::certificate_link( "", $this->quiz ); ?> </p> <?php echo LD_QuizPro::certificate_details( $this->quiz ); ?> <?php } ?> <?php if ( $this->quiz->isShowAverageResult() ) { ?> <div class="wpProQuiz_resultTable"> <table> <tbody> <tr> <td class="wpProQuiz_resultName"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_average_score_message', 'message' => esc_html__( 'Average score', 'learndash' ) ) ); ?></td> <td class="wpProQuiz_resultValue wpProQuiz_resultValue_AvgScore"> <div class="progress-meter" style="background-color: #6CA54C;"> </div> <span class="progress-number"> </span> </td> </tr> <tr> <td class="wpProQuiz_resultName"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_your_score_message', 'message' => esc_html__( 'Your score', 'learndash' ) ) ); ?></td> <td class="wpProQuiz_resultValue wpProQuiz_resultValue_YourScore"> <div class="progress-meter"> </div> <span class="progress-number"> </span> </td> </tr> </tbody> </table> </div> <?php } ?> <div class="wpProQuiz_catOverview" <?php $this->isDisplayNone( $this->quiz->isShowCategoryScore() ); ?>> <h4><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'learndash_categories_header', 'message' => esc_html__( 'Categories', 'learndash' ) ) ); ?></h4> <div style="margin-top: 10px;"> <ol> <?php foreach ( $this->category as $cat ) { if ( ! $cat->getCategoryId() ) { $cat->setCategoryName( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'learndash_not_categorized_messages', 'message' => esc_html__( 'Not categorized', 'learndash' ) ) ) ); } ?> <li data-category_id="<?php echo $cat->getCategoryId(); ?>"> <span class="wpProQuiz_catName"><?php echo $cat->getCategoryName(); ?></span> <span class="wpProQuiz_catPercent">0%</span> </li> <?php } ?> </ol> </div> </div> <div> <ul class="wpProQuiz_resultsList"> <?php foreach ( $result['text'] as $resultText ) { ?> <li style="display: none;"> <div> <?php echo do_shortcode( apply_filters( 'comment_text', $resultText, null, null ) ); ?> <?php //echo do_shortcode( apply_filters( 'the_content', $resultText, null, null ) ); ?> </div> </li> <?php } ?> </ul> </div> <?php if ( $this->quiz->isToplistActivated() ) { if ( $this->quiz->getToplistDataShowIn() == WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SHOW_IN_NORMAL ) { echo do_shortcode( '[LDAdvQuiz_toplist ' . $this->quiz->getId() . ' q="true"]' ); } $this->showAddToplist(); } ?> <div class="ld-quiz-actions" style="margin: 10px 0px;"> <?php /** * See snippet https://bitbucket.org/snippets/learndash/nMk9a * @since 2.3.0.2 */ $show_quiz_continue_buttom_on_fail = apply_filters( 'show_quiz_continue_buttom_on_fail', false, learndash_get_quiz_id_by_pro_quiz_id( $this->quiz->getId() ) ); ?> <div class='quiz_continue_link<?php if ( $show_quiz_continue_buttom_on_fail == true ) { echo ' show_quiz_continue_buttom_on_fail'; } ?>'> </div> <?php if ( ! $this->quiz->isBtnRestartQuizHidden() ) { ?> <input class="wpProQuiz_button wpProQuiz_button_restartQuiz" type="button" name="restartQuiz" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_restart_button_label', 'message' => sprintf( esc_html_x( 'Restart %s', 'Restart Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) )); ?>"> <?php } if ( ! $this->quiz->isBtnViewQuestionHidden() ) { ?> <input class="wpProQuiz_button wpProQuiz_button_reShowQuestion" type="button" name="reShowQuestion" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_view_questions_button_label', 'message' => sprintf( esc_html_x( 'View %s', 'View Questions Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'questions' ) ) ) )); ?>"> <?php } ?> <?php if ( $this->quiz->isToplistActivated() && $this->quiz->getToplistDataShowIn() == WpProQuiz_Model_Quiz::QUIZ_TOPLIST_SHOW_IN_BUTTON ) { ?> <input class="wpProQuiz_button" type="button" name="showToplist" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_show_leaderboard_button_label', 'message' => esc_html__( 'Show leaderboard', 'learndash' ) ) )); ?>"> <?php } ?> </div> </div> <?php } private function showToplistInButtonBox() { ?> <div class="wpProQuiz_toplistShowInButton" style="display: none;"> <?php echo do_shortcode( '[LDAdvQuiz_toplist ' . $this->quiz->getId() . ' q="true"]' ); ?> </div> <?php } public function showQuizBox( $questionCount ) { $globalPoints = 0; $json = array(); $catPoints = array(); ?> <div style="display: none;" class="wpProQuiz_quiz"> <ol class="wpProQuiz_list"> <?php $index = 0; foreach ( $this->question as $question ) { $index ++; $answerArray = $question->getAnswerData(); $globalPoints += $question->getPoints(); $json[ $question->getId() ]['type'] = $question->getAnswerType(); $json[ $question->getId() ]['id'] = (int) $question->getId(); $json[ $question->getId() ]['question_post_id'] = (int) $question->getQuestionPostId(); $json[ $question->getId() ]['catId'] = (int) $question->getCategoryId(); if ( $question->isAnswerPointsActivated() && $question->isAnswerPointsDiffModusActivated() && $question->isDisableCorrect() ) { $json[ $question->getId() ]['disCorrect'] = (int) $question->isDisableCorrect(); //$json[$question->getId()]['discoordinates'] = (int)$question->isDisableCorrect(); } if ( ! isset( $catPoints[ $question->getCategoryId() ] ) ) { $catPoints[ $question->getCategoryId() ] = 0; } $catPoints[ $question->getCategoryId() ] += $question->getPoints(); if ( ! $question->isAnswerPointsActivated() ) { $json[ $question->getId() ]['points'] = $question->getPoints(); //$json[$question->getId()]['version'] = $question->getPoints(); // $catPoints[$question->getCategoryId()] += $question->getPoints(); } if ( $question->isAnswerPointsActivated() && $question->isAnswerPointsDiffModusActivated() ) { // $catPoints[$question->getCategoryId()] += $question->getPoints(); $json[ $question->getId() ]['diffMode'] = 1; } $question_meta = array( 'type' => $question->getAnswerType(), 'question_pro_id' => $question->getId(), 'question_post_id' => $question->getQuestionPostId(), ); ?> <li class="wpProQuiz_listItem" style="display: none;" data-type="<?php echo $question->getAnswerType(); ?>" data-question-meta="<?php echo htmlspecialchars( wp_json_encode( $question_meta ) ); ?>"> <div class="wpProQuiz_question_page" <?php $this->isDisplayNone( $this->quiz->getQuizModus() != WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE && ! $this->quiz->isHideQuestionPositionOverview() ); ?> > <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_list_2_message', 'message' => sprintf( esc_html_x( 'Question %1$s of %2$s', 'placeholder: question number, questions total', 'learndash' ), '<span>' . $index . '</span>', '<span>' . $questionCount . '</span>' ), 'placeholders' => array( $index, $questionCount ) ) ); ?> </div> <h5 style="<?php echo $this->quiz->isHideQuestionNumbering() ? 'display: none;' : 'display: inline-block;' ?>" class="wpProQuiz_header"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_list_1_message', 'message' => '<span>'. $index .'</span>. '. esc_html__( 'Question', 'learndash' ), 'placeholders' => array( $index ) ) ); ?> </h5> <?php if ( $this->quiz->isShowPoints() ) { ?> <span style="font-weight: bold; float: right;"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_points_message', 'message' => sprintf( esc_html_x( '%s point(s)', 'placeholder: total quiz points', 'learndash' ), '<span>'. $question->getPoints() . '</span>' ), 'placeholders' => array( $question->getPoints() ) ) ); ?></span> <div style="clear: both;"></div> <?php } ?> <?php if ( $question->getCategoryId() && $this->quiz->isShowCategory() ) { ?> <div style="font-weight: bold; padding-top: 5px;"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_category_message', 'message' => sprintf( esc_html_x( 'Category: %s', 'placeholder: Quiz Category', 'learndash' ), '<span>'. esc_html( $question->getCategoryName() ) .'</span>' ), 'placeholders' => array( esc_html( $question->getCategoryName() ) ) ) ); ?> </div> <?php } ?> <div class="wpProQuiz_question" style="margin: 10px 0px 0px 0px;"> <div class="wpProQuiz_question_text"> <?php $questionText = $question->getQuestion(); $questionText = sanitize_post_field( 'post_content', $questionText, 0, 'display' ); //$questionText = wp_unslash( $questionText ); $questionText = wpautop( $questionText ); $questionText = do_shortcode( $questionText ); echo $questionText; ?> </div> <p class="wpProQuiz_clear" style="clear:both;"></p> <?php /** * Matrix Sort Answer */ ?> <?php if ( $question->getAnswerType() === 'matrix_sort_answer' ) { ?> <div class="wpProQuiz_matrixSortString"> <h5 class="wpProQuiz_header"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_sort_elements_header', 'message' => esc_html__( 'Sort elements', 'learndash' ) ) ); ?></h5> <ul class="wpProQuiz_sortStringList"><?php $matrix = array(); foreach ( $answerArray as $k => $v ) { $matrix[ $k ][] = $k; foreach ( $answerArray as $k2 => $v2 ) { if ( $k != $k2 ) { if ( $v->getAnswer() == $v2->getAnswer() ) { $matrix[ $k ][] = $k2; } else if ( $v->getSortString() == $v2->getSortString() ) { $matrix[ $k ][] = $k2; } } } } foreach ( $answerArray as $k => $v ) { ?><li class="wpProQuiz_sortStringItem" data-pos="<?php echo $k; ?>"><?php echo $v->isSortStringHtml() ? do_shortcode( nl2br( $v->getSortString() ) ) : esc_html( $v->getSortString() ); ?></li><?php } ?></ul> <div style="clear: both;"></div> </div> <?php } ?> <?php /** * Print questions in a list for all other answer types */ ?> <ul class="wpProQuiz_questionList" data-question_id="<?php echo $question->getId(); ?>" data-type="<?php echo $question->getAnswerType(); ?>"> <?php $answer_index = 0; foreach ( $answerArray as $v ) { $answer_text = $v->isHtml() ? do_shortcode( nl2br( $v->getAnswer() ) ) : esc_html( $v->getAnswer() ); if ( $answer_text == '' && ! $v->isGraded() ) { continue; } if ( $question->isAnswerPointsActivated() ) { $json[ $question->getId() ]['points'][] = $v->getPoints(); //$json[$question->getId()]['version'][] = $v->getPoints(); // if(!$question->isAnswerPointsDiffModusActivated()) // $catPoints[$question->getCategoryId()] += $question->getPoints(); } $datapos = $answer_index; if ( $question->getAnswerType() === 'sort_answer' || $question->getAnswerType() === 'matrix_sort_answer' ) { $datapos = LD_QuizPro::datapos( $question->getId(), $answer_index ); } ?> <li class="wpProQuiz_questionListItem" data-pos="<?php echo $datapos; ?>"> <?php /** * Single/Multiple */ ?> <?php if ( $question->getAnswerType() === 'single' || $question->getAnswerType() === 'multiple' ) { ?> <?php $json[ $question->getId() ]['correct'][] = (int) $v->isCorrect(); ?> <?php /* $json[$question->getId()]['coordinates'][] = (int)$v->isCorrect(); */ ?> <span <?php echo $this->quiz->isNumberedAnswer() ? '' : 'style="display:none;"' ?>></span> <label> <input class="wpProQuiz_questionInput" type="<?php echo $question->getAnswerType() === 'single' ? 'radio' : 'checkbox'; ?>" name="question_<?php echo $this->quiz->getId(); ?>_<?php echo $question->getId(); ?>" value="<?php echo( $answer_index + 1 ); ?>"> <?php echo $answer_text; ?> </label> <?php /** * Sort Answer */ ?> <?php } else if ( $question->getAnswerType() === 'sort_answer' ) { ?> <?php $json[ $question->getId() ]['correct'][] = (int) $answer_index; ?> <?php /* $json[$question->getId()]['coordinates'][] = (int)$answer_index; */ ?> <div class="wpProQuiz_sortable"> <?php echo $answer_text; ?> </div> <?php /** * Free Answer */ ?> <?php } else if ( $question->getAnswerType() === 'free_answer' ) { ?> <?php $json[ $question->getId() ]['correct'] = $this->getFreeCorrect( $v ); ?> <?php /* $json[$question->getId()]['coordinates'] = $this->getFreeCorrect($v); */ ?> <label> <input class="wpProQuiz_questionInput" type="text" name="question_<?php echo $this->quiz->getId(); ?>_<?php echo $question->getId(); ?>" style="width: 300px;"> </label> <?php /** * Matrix Sort Answer */ ?> <?php } else if ( $question->getAnswerType() === 'matrix_sort_answer' ) { ?> <?php $json[ $question->getId() ]['correct'][] = (int) $answer_index; //$json[$question->getId()]['coordinates'][] = (int)$answer_index; $msacwValue = $question->getMatrixSortAnswerCriteriaWidth() > 0 ? $question->getMatrixSortAnswerCriteriaWidth() : 20; ?> <table> <tbody> <tr class="wpProQuiz_mextrixTr"> <td width="<?php echo $msacwValue; ?>%"> <div class="wpProQuiz_maxtrixSortText"><?php echo $answer_text; ?></div> </td> <td width="<?php echo 100 - $msacwValue; ?>%"> <ul class="wpProQuiz_maxtrixSortCriterion"></ul> </td> </tr> </tbody> </table> <?php /** * Cloze Answer */ ?> <?php } else if ( $question->getAnswerType() === 'cloze_answer' ) { //$clozeData = $this->fetchCloze( $v->getAnswer() ); $clozeData = fetchQuestionCloze( $v->getAnswer() ); $this->_clozeTemp = isset( $clozeData['data'] ) ? $clozeData['data'] : []; $json[ $question->getId() ]['correct'] = isset( $clozeData['correct'] ) ? $clozeData['correct'] : []; //$json[$question->getId()]['coordinates'] = $clozeData['correct']; if ( $question->isAnswerPointsActivated() ) { $json[ $question->getId() ]['points'] = $clozeData['points']; //$json[$question->getId()]['version'] = $clozeData['points']; } // Added the wpautop in LD 2.2.1 to retain line-break formatting. $clozeData['replace'] = wpautop($clozeData['replace']); //$cloze = do_shortcode( wp_kses_post( $clozeData['replace'], null, null ) ); $clozeData['replace'] = sanitize_post_field( 'post_content', $clozeData['replace'], 0, 'display' ); $clozeData['replace'] = do_shortcode( $clozeData['replace'] ); $cloze = $clozeData['replace']; echo preg_replace_callback( '#@@wpProQuizCloze@@#im', array( $this, 'clozeCallback' ), $cloze ); /** * Assessment answer */ } else if ( $question->getAnswerType() === 'assessment_answer' ) { $assessmentData = $this->fetchAssessment( $v->getAnswer(), $this->quiz->getId(), $question->getId() ); //$assessment = do_shortcode( apply_filters( 'comment_text', $assessmentData['replace'], null, null ) ); $assessment = sanitize_post_field( 'post_content', $assessmentData['replace'], 0, 'display' ); //$assessment = strip_tags($assessment); $assessment = wpautop( $assessment ); $assessment = do_shortcode( $assessment ); $assessment = preg_replace_callback( '#@@wpProQuizAssessment@@#im', array( $this, 'assessmentCallback' ), $assessment ); $assessment = apply_filters( 'learndash_quiz_question_answer_postprocess', $assessment, 'assessment' ); $assessment = do_shortcode( $assessment ); echo $assessment; /** * Essay answer */ } else if ( $question->getAnswerType() === 'essay' ) { ?> <?php if ( $v->getGradedType() === 'text' ) : ?> <textarea class="wpProQuiz_questionEssay" rows="10" cols="40" name="question_<?php echo $this->quiz->getId(); ?>_<?php echo $question->getId(); ?>" id="wpProQuiz_questionEssay_question_<?php echo $this->quiz->getId(); ?>_<?php echo $question->getId(); ?>" cols="30" autocomplete="off" rows="10" placeholder="<?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_question_textarea_placeholder_message', 'message' => esc_html__( 'Type your response here', 'learndash' ) ) ); ?>"></textarea> <?php elseif ( $v->getGradedType() === 'upload' ) : ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_question_upload_answer_message', 'message' => '<p>'. esc_html__( 'Upload your answer to this question.', 'learndash' ) .'</p>' ) ); ?> <p> <form enctype="multipart/form-data" method="post" name="uploadEssay"> <input type='file' name='uploadEssay[]' id='uploadEssay_<?php echo $question->getId(); ?>' size='35' class='wpProQuiz_upload_essay' /> <input type="submit" id='uploadEssaySubmit_<?php echo $question->getId(); ?>' value="<?php esc_html_e('Upload', 'learndash') ?>" /> <input type="hidden" id="_uploadEssay_nonce_<?php echo $question->getId(); ?>" name="_uploadEssay_nonce" value="<?php echo wp_create_nonce('learndash-upload-essay-' . $question->getId() ); ?>" /> </form> <input type="hidden" class="uploadEssayFile" id='uploadEssayFile_<?php echo $question->getId(); ?>' value="" /> </p> <?php else : ?> <?php esc_html_e( 'Essay type not found', 'learndash' ); ?> <?php endif; ?> <p class="graded-disclaimer"> <?php if ( 'graded-full' == $v->getGradingProgression() ) : ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_question_graded_full_message', 'message' => esc_html__( 'This response will be awarded full points automatically, but it can be reviewed and adjusted after submission.', 'learndash' ) ) ); ?> <?php elseif ( 'not-graded-full' == $v->getGradingProgression() ) : ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_question_not_graded_full_message', 'message' => esc_html__( 'This response will be awarded full points automatically, but it will be reviewed and possibly adjusted after submission.', 'learndash' ) ) ); ?> <?php elseif ( 'not-graded-none' == $v->getGradingProgression() ) : ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_question_not_graded_none_message', 'message' => esc_html__( 'This response will be reviewed and graded after submission.', 'learndash' ) ) ); ?> <?php endif; ?> </p> <?php } ?> </li> <?php $answer_index ++; } ?> </ul> </div> <?php if ( ! $this->quiz->isHideAnswerMessageBox() ) { ?> <div class="wpProQuiz_response" style="display: none;"> <div style="display: none;" class="wpProQuiz_correct"> <?php if ( $question->isShowPointsInBox() && $question->isAnswerPointsActivated() ) { ?> <div> <span class="wpProQuiz_response_correct_label" style="float: left;"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_answer_correct_message', 'message' => esc_html__( 'Correct', 'learndash' ) ) ); ?></span> <span class="wpProQuiz_response_correct_points_label" style="float: right;"><?php echo $question->getPoints() . ' / ' . $question->getPoints(); ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_answer_points_message', 'message' => esc_html__( 'Points', 'learndash' ) ) ); ?></span> <div style="clear: both;"></div> </div> <?php } elseif ( 'essay' == $question->getAnswerType() ) { ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_question_graded_review_message', 'message' => esc_html__( 'Grading can be reviewed and adjusted.', 'learndash' ) ) ); ?> <?php } else { ?> <span><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_answer_correct_message', 'message' => esc_html__( 'Correct', 'learndash' ) ) ); ?></span> <?php } ?> <p class="wpProQuiz_AnswerMessage"> </p> </div> <div style="display: none;" class="wpProQuiz_incorrect"> <?php if ( $question->isShowPointsInBox() && $question->isAnswerPointsActivated() ) { ?> <div> <span style="float: left;"> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_answer_incorrect_message', 'message' => esc_html__( 'Incorrect', 'learndash' ) ) ); ?> </span> <span style="float: right;"><span class="wpProQuiz_responsePoints"></span> / <?php echo $question->getPoints(); ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_answer_points_message', 'message' => esc_html__( 'Points', 'learndash' ) ) ); ?></span> <div style="clear: both;"></div> </div> <?php } elseif ( 'essay' == $question->getAnswerType() ) { ?> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_essay_question_graded_review_message', 'message' => esc_html__( 'Grading can be reviewed and adjusted.', 'learndash' ) ) ); ?> <?php } else { ?> <span> <?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_question_answer_incorrect_message', 'message' => esc_html__( 'Incorrect', 'learndash' ) ) ); ?> </span> <?php } ?> <p class="wpProQuiz_AnswerMessage"> </p> </div> </div> <?php } ?> <?php if ( $question->isTipEnabled() ) { ?> <div class="wpProQuiz_tipp" style="display: none; position: relative;"> <div> <h5 style="margin: 0px 0px 10px;" class="wpProQuiz_header"><?php echo SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_hint_header', 'message' => esc_html__( 'Hint', 'learndash' ) ) ); ?></h5> <?php echo do_shortcode( apply_filters( 'comment_text', $question->getTipMsg(), null, null ) ); ?> </div> </div> <?php } ?> <?php if ( $this->quiz->getQuizModus() == WpProQuiz_Model_Quiz::QUIZ_MODUS_CHECK && ! $this->quiz->isSkipQuestionDisabled() && $this->quiz->isShowReviewQuestion() ) { ?> <input type="button" name="skip" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_skip_button_label', 'message' => esc_html__( 'Skip question', 'learndash' ) ) ) ) ?>" class="wpProQuiz_button wpProQuiz_QuestionButton" style="float: left; margin-right: 10px ;"> <?php } ?> <input type="button" name="back" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_back_button_label', 'message' => esc_html__( 'Back', 'learndash' ) ) ) ) ?>" class="wpProQuiz_button wpProQuiz_QuestionButton" style="float: left ; margin-right: 10px ; display: none;"> <?php if ( $question->isTipEnabled() ) { ?> <input type="button" name="tip" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_hint_button_label', 'message' => esc_html__( 'Hint', 'learndash' ) ) ) ) ?>" class="wpProQuiz_button wpProQuiz_QuestionButton wpProQuiz_TipButton" style="float: left ; display: inline-block; margin-right: 10px ;"> <?php } ?> <input type="button" name="check" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_check_button_label', 'message' => esc_html__( 'Check', 'learndash' ) ) ) ) ?>" class="wpProQuiz_button wpProQuiz_QuestionButton" style="float: right ; margin-right: 10px ; display: none;"> <input type="button" name="next" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_next_button_label', 'message' => esc_html__( 'Next', 'learndash' ) ) ) ) ?>" class="wpProQuiz_button wpProQuiz_QuestionButton" style="float: right; display: none;"> <div style="clear: both;"></div> <?php if ( $this->quiz->getQuizModus() == WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE ) { ?> <div style="margin-bottom: 20px;"></div> <?php } ?> </li> <?php } ?> </ol> <?php if ( $this->quiz->getQuizModus() == WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE ) { ?> <div> <input type="button" name="wpProQuiz_pageLeft" data-text="<?php echo esc_html__( 'Page %d', 'learndash' ); ?>" style="float: left; display: none;" class="wpProQuiz_button wpProQuiz_QuestionButton"> <input type="button" name="wpProQuiz_pageRight" data-text="<?php echo esc_html__( 'Page %d', 'learndash' ); ?>" style="float: right; display: none;" class="wpProQuiz_button wpProQuiz_QuestionButton"> <?php if ( $this->quiz->isShowReviewQuestion() && ! $this->quiz->isQuizSummaryHide() ) { ?> <input type="button" name="checkSingle" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_quiz_summary_button_label', 'message' => sprintf( esc_html_x( '%s Summary', 'Quiz Summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) )); ?>" class="wpProQuiz_button wpProQuiz_QuestionButton" style="float: right;"> <?php } else { ?> <input type="button" name="checkSingle" value="<?php echo esc_html( SFWD_LMS::get_template( 'learndash_quiz_messages', array( 'quiz_post_id' => $this->quiz->getID(), 'context' => 'quiz_finish_button_label', 'message' => sprintf( esc_html_x( 'Finish %s', 'Finish Quiz Button Label', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) ) ) ) ?>" class="wpProQuiz_button wpProQuiz_QuestionButton" style="float: right;"> <?php } ?> <div style="clear: both;"></div> </div> <?php } ?> </div> <?php if ( empty( $globalPoints ) ) { $globalPoints = 1; } return array( 'globalPoints' => $globalPoints, 'json' => $json, 'catPoints' => $catPoints ); } private function showLoadQuizBox() { ?> <div style="display: none;" class="wpProQuiz_loadQuiz"> <p> <?php printf( esc_html_x('%s is loading...', 'quiz is loading... Label', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?> </p> </div> <?php } } lib/view/WpProQuiz_View_QuizEdit.php 0000666 00000162727 15214236625 0013556 0 ustar 00 <?php class WpProQuiz_View_QuizEdit extends WpProQuiz_View_View { /** * @var WpProQuiz_Model_Quiz */ public $quiz; public function show_advanced( $get = null ) { ?> <input name="name" id="wpProQuiz_title" type="hidden" class="regular-text" value="<?php echo $this->quiz->getName(); ?>"> <input name="text" type="hidden" value="AAZZAAZZ" /> <div class="wrap wpProQuiz_quizEdit"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php echo sprintf( esc_html_x('Hide %s title', 'Hide quiz title', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Hide title', 'learndash'); ?></span> </legend> <label for="title_hidden"> <input type="checkbox" id="title_hidden" value="1" name="titleHidden" <?php echo $this->quiz->isTitleHidden() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('The title serves as %s heading.', 'The title serves as quiz heading.', 'learndash'), learndash_get_custom_label_lower( 'quiz' )); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php echo sprintf( esc_html_x('Hide "Restart %s" button', 'Hide "Restart quiz" button', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php echo sprintf( esc_html_x('Hide "Restart %s" button', 'Hide "Restart quiz" button', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?></span> </legend> <label for="btn_restart_quiz_hidden"> <input type="checkbox" id="btn_restart_quiz_hidden" value="1" name="btnRestartQuizHidden" <?php echo $this->quiz->isBtnRestartQuizHidden() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('Hide the "Restart %s" button in the Frontend.', 'Hide the "Restart quiz" button in the Frontend.', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Hide "View question" button', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Hide "View question" button', 'learndash'); ?></span> </legend> <label for="btn_view_question_hidden"> <input type="checkbox" id="btn_view_question_hidden" value="1" name="btnViewQuestionHidden" <?php echo $this->quiz->isBtnViewQuestionHidden() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Hide the "View question" button in the Frontend.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Display question randomly', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Display question randomly', 'learndash'); ?></span> </legend> <label for="question_random"> <input type="checkbox" id="question_random" value="1" name="questionRandom" <?php echo $this->quiz->isQuestionRandom() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Display answers randomly', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Display answers randomly', 'learndash'); ?></span> </legend> <label for="answer_random"> <input type="checkbox" id="answer_random" value="1" name="answerRandom" <?php echo $this->quiz->isAnswerRandom() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Sort questions by category', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Sort questions by category', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="sortCategories" <?php $this->checked($this->quiz->isSortCategories()); ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Also works in conjunction with the "display randomly question" option.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Time limit', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Time limit', 'learndash'); ?></span> </legend> <label for="time_limit"> <input type="number" min="0" class="small-text" id="time_limit" value="<?php echo $this->quiz->getTimeLimit(); ?>" name="timeLimit"> <?php esc_html_e('Seconds', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('0 = no limit', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php echo sprintf( esc_html_x('Protect %s Answers in Browser Cookie', 'Protect Quiz Answers in Browser Cookie', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php echo sprintf( esc_html_x('Use cookies for %s Answers', 'Use cookies for Quiz Answers', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?></span> </legend> <label for="time_limit_cookie"> <input type="number" min="0" class="small-text" id="time_limit_cookie" value="<?php echo intval($this->quiz->getTimeLimitCookie()); ?>" name="timeLimitCookie"> <?php esc_html_e('Seconds', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x("0 = Don't save answers. This option will save the user's answers into a browser cookie until the %s is submitted.", 'placeholders: Quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Statistics', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Statistics', 'learndash'); ?></span> </legend> <label for="statistics_on"> <input type="checkbox" id="statistics_on" value="1" name="statisticsOn" <?php echo ( !isset( $_GET["post"] ) || $this->quiz->isStatisticsOn() ) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('Statistics about right or wrong answers. Statistics will be saved by completed %s, not after every question. The statistics is only visible over administration menu. (internal statistics)', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> <tr id="statistics_ip_lock_tr" style="display: none;"> <th scope="row"> <?php esc_html_e('Statistics IP-lock', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Statistics IP-lock', 'learndash'); ?></span> </legend> <label for="statistics_ip_lock"> <input type="number" min="0" class="small-text" id="statistics_ip_lock" value="<?php echo ($this->quiz->getStatisticsIpLock() === null) ? 0 : $this->quiz->getStatisticsIpLock(); ?>" name="statisticsIpLock"> <?php esc_html_e('in minutes (recommended 1440 minutes = 1 day)', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Protect the statistics from spam. Result will only be saved every X minutes from same IP. (0 = deactivated)', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr id="statistics_show_profile_tr" style="display: none;"> <th scope="row"> <?php esc_html_e('View Profile Statistics', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('View Profile Statistics', 'learndash'); ?></span> </legend> <label for="statistics_on"> <input type="checkbox" id="view_profile_statistics_on" value="1" name="viewProfileStatistics" <?php echo ( !isset( $_GET["post"] ) || $this->quiz->getViewProfileStatistics() ) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('Enable user to view statistics for this %s on their profile.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php echo sprintf( esc_html_x('Execute %s only once', 'Execute quiz only once', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php echo sprintf( esc_html_x('Execute %s only once', 'Execute quiz only once', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?></span> </legend> <label> <input type="checkbox" value="1" name="quizRunOnce" <?php echo $this->quiz->isQuizRunOnce() ? 'checked="checked"' : '' ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you activate this option, the user can complete the %1$s only once. Afterwards the %2$s is blocked for this user.', 'placeholders: quiz, quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> <div id="wpProQuiz_quiz_run_once_type" style="margin-bottom: 5px; display: none;"> <?php esc_html_e('This option applies to:', 'learndash'); $quizRunOnceType = $this->quiz->getQuizRunOnceType(); $quizRunOnceType = ($quizRunOnceType == 0) ? 1: $quizRunOnceType; ?> <label> <input name="quizRunOnceType" type="radio" value="1" <?php echo ($quizRunOnceType == 1) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('all users', 'learndash'); ?> </label> <label> <input name="quizRunOnceType" type="radio" value="2" <?php echo ($quizRunOnceType == 2) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('registered useres only', 'learndash'); ?> </label> <label> <input name="quizRunOnceType" type="radio" value="3" <?php echo ($quizRunOnceType == 3) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('anonymous users only', 'learndash'); ?> </label> <div id="wpProQuiz_quiz_run_once_cookie" style="margin-top: 10px;"> <label> <input type="checkbox" value="1" name="quizRunOnceCookie" <?php echo $this->quiz->isQuizRunOnceCookie() ? 'checked="checked"' : '' ?>> <?php esc_html_e('user identification by cookie', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you activate this option, a cookie is set additionally for unregistrated (anonymous) users. This ensures a longer assignment of the user than the simple assignment by the IP address.', 'learndash'); ?> </p> </div> <div style="margin-top: 15px;"> <input class="button-secondary" type="button" name="resetQuizLock" value="<?php esc_html_e('Reset the user identification', 'learndash'); ?>"> <span id="resetLockMsg" style="display:none; background-color: rgb(255, 255, 173); border: 1px solid rgb(143, 143, 143); padding: 4px; margin-left: 5px; "><?php esc_html_e('User identification has been reset.', 'learndash'); ?></span> <p class="description"> <?php esc_html_e('Resets user identification for all users.', 'learndash'); ?> </p> </div> </div> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Show only specific number of questions', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Show only specific number of questions', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="showMaxQuestion" <?php echo $this->quiz->isShowMaxQuestion() ? 'checked="checked"' : '' ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, maximum number of displayed questions will be X from X questions. (The output of questions is random)', 'learndash'); ?> </p> <div id="wpProQuiz_showMaxBox" style="display: none;"> <label> <?php esc_html_e('How many questions should be displayed simultaneously:', 'learndash'); ?> <input class="small-text" type="text" name="showMaxQuestionValue" value="<?php echo $this->quiz->getShowMaxQuestionValue(); ?>"> </label> <label> <input type="checkbox" value="1" name="showMaxQuestionPercent" <?php echo $this->quiz->isShowMaxQuestionPercent() ? 'checked="checked"' : '' ?>> <?php esc_html_e('in percent', 'learndash'); ?> </label> </div> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Prerequisites', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Prerequisites', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="prerequisite" <?php $this->checked($this->quiz->isPrerequisite()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you enable this option, you can choose %1$s, which user have to finish before he can start this %2$s.', 'placeholders: quiz, quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> <p class="description"> <?php echo sprintf( esc_html_x('In all selected %s statistic function have to be active. If it is not it will be activated automatically.', 'placeholders: quizzes', 'learndash'), learndash_get_custom_label_lower( 'quizzes' ) ); ?> </p> <div id="prerequisiteBox" style="display: none;"> <table id="learndash-prerequisite-table"> <tr> <th class="learndash-quiz-prerequisite-list learndash-quiz-prerequisite-list-left"><?php echo sprintf( esc_html_x('%s', 'Quiz', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?></th> <th class="learndash-quiz-prerequisite-list learndash-quiz-prerequisite-list-center"></th> <th class="learndash-quiz-prerequisite-list learndash-quiz-prerequisite-list-right"><?php echo sprintf( esc_html_x('Prerequisites (This %s has to be finished)', 'Prerequisites (This quiz has to be finished)', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?></th> </tr> <tr> <td class="learndash-quiz-prerequisite-list learndash-quiz-prerequisite-list-left"> <select class="learndash-quiz-prerequisite-list" multiple="multiple" size="8" name="quizList"> <?php foreach($this->quizList as $list) { if(in_array($list['id'], $this->prerequisiteQuizList)) continue; echo '<option value="'.$list['id'].'" title="'.$list['name'].'">'.$list['name'].'</option>'; } ?> </select> </td> <td class="learndash-quiz-prerequisite-list learndash-quiz-prerequisite-list-center" style="text-align: center;"> <div> <input type="button" id="btnPrerequisiteAdd" value=">>"> </div> <div> <input type="button" id="btnPrerequisiteDelete" value="<<"> </div> </td> <td class="learndash-quiz-prerequisite-list learndash-quiz-prerequisite-list-right"> <select class="learndash-quiz-prerequisite-list" multiple="multiple" size="8" name="prerequisiteList[]"> <?php foreach($this->quizList as $list) { if(!in_array($list['id'], $this->prerequisiteQuizList)) continue; echo '<option value="'.$list['id'].'" title="'.$list['name'].'">'.$list['name'].'</option>'; } ?> </select> </td> </tr> </table> </div> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Question overview', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Question overview', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="showReviewQuestion" <?php $this->checked($this->quiz->isShowReviewQuestion()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Add at the top of the quiz a question overview, which allows easy navigation. Additional questions can be marked "to review".', 'learndash'); ?> </p> <p class="description"> <?php echo sprintf( esc_html_x('Additional %s overview will be displayed, before %s is finished.', 'placeholders: quiz, quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ), learndash_get_custom_label_lower( 'quiz' )); ?> </p> </fieldset> </td> </tr> <tr class="wpProQuiz_reviewQuestionOptions" style="display: none;"> <th scope="row"> <?php echo sprintf( esc_html_x( '%s-summary', 'Quiz-summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php echo sprintf( esc_html_x( '%s-summary', 'Quiz-summary', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?></span> </legend> <label> <input type="checkbox" value="1" name="quizSummaryHide" <?php $this->checked($this->quiz->isQuizSummaryHide()); ?>> <?php esc_html_e('Deactivate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you enable this option, no %1$s overview will be displayed, before finishing %2$s.', 'placeholders: quiz, quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> <tr class="wpProQuiz_reviewQuestionOptions" style="display: none;"> <th scope="row"> <?php esc_html_e('Skip question', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Skip question', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="skipQuestionDisabled" <?php $this->checked($this->quiz->isSkipQuestionDisabled()); ?>> <?php esc_html_e('Deactivate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, user won\'t be able to skip question. (only in "Overview -> next" mode). User still will be able to navigate over "Question-Overview"', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Admin e-mail notification', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Admin e-mail notification', 'learndash'); ?></span> </legend> <label> <input type="radio" name="emailNotification" value="<?php echo WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_NONE; ?>" <?php $this->checked($this->quiz->getEmailNotification(), WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_NONE); ?>> <?php esc_html_e('Deactivate', 'learndash'); ?> </label> <label> <input type="radio" name="emailNotification" value="<?php echo WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_REG_USER; ?>" <?php $this->checked($this->quiz->getEmailNotification(), WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_REG_USER); ?>> <?php esc_html_e('for registered users only', 'learndash'); ?> </label> <label> <input type="radio" name="emailNotification" value="<?php echo WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_ALL; ?>" <?php $this->checked($this->quiz->getEmailNotification(), WpProQuiz_Model_Quiz::QUIZ_EMAIL_NOTE_ALL); ?>> <?php esc_html_e('for all users', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you enable this option, you will be informed if a user completes this %s.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> <p class="description"> <?php esc_html_e('E-Mail settings can be edited in global settings.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('User e-mail notification', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('User e-mail notification', 'learndash'); ?></span> </legend> <label> <input type="checkbox" name="userEmailNotification" value="1" <?php $this->checked($this->quiz->isUserEmailNotification()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you enable this option, an email is sent with his %s result to the user. (only registered users)', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'course' ) ); ?> </p> <p class="description"> <?php esc_html_e('E-Mail settings can be edited in global settings.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Autostart', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Autostart', 'learndash'); ?></span> </legend> <label> <input type="checkbox" name="autostart" value="1" <?php $this->checked($this->quiz->isAutostart()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you enable this option, the %s will start automatically after the page is loaded.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php echo sprintf( esc_html_x('Only registered users are allowed to start the %s', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php echo sprintf( esc_html_x('Only registered users are allowed to start the %s', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?></span> </legend> <label> <input type="checkbox" name="startOnlyRegisteredUser" value="1" <?php $this->checked($this->quiz->isStartOnlyRegisteredUser()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you enable this option, only registered users allowed start the %s.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> </tbody> </table> </div> <?php } public function show_templates($get = null) { $template_loaded_id = 0; if ( ( isset( $_GET['templateLoadId'] ) ) && ( ! empty( $_GET['templateLoadId'] ) ) ) { $template_loaded_id = intval( $_GET['templateLoadId'] ); } ?> <div class="wrap wpProQuiz_quizEdit"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php _e('Use Template', 'learndash' ); ?> </th> <td> <select name="templateLoadId"> <option value=""><?php _e('Select Template', 'learndash' ); ?></option> <?php foreach($this->templates as $template) { echo '<option ' . selected( $template_loaded_id, $template->getTemplateId() ) . ' value="', $template->getTemplateId(), '">', esc_html($template->getName()), '</option>'; } ?> </select> <input type="submit" name="templateLoad" value="<?php esc_html_e('load template', 'learndash'); ?>" class="button-primary"> </td> </tr> <tr> <th scope="row"> <?php _e('Save as Template', 'learndash' ); ?> </th> <td> <input type="text" placeholder="<?php esc_html_e('template name', 'learndash'); ?>" class="regular-text" name="templateName" style="border: 1px solid rgb(255, 134, 134);"> <select name="templateSaveList"> <option value="0">=== <?php esc_html_e('Create new template', 'learndash'); ?> === </option> <?php foreach($this->templates as $template) { echo '<option value="', $template->getTemplateId(), '">', esc_html($template->getName()), '</option>'; } ?> </select> <input type="submit" name="template" class="button-primary" id="wpProQuiz_saveTemplate" value="<?php esc_html_e('Save as template', 'learndash'); ?>"> </td> </tr> </tbody> </table> </div> <?php } public function resultOptions() { ?> <div class="wrap wpProQuiz_quizEdit"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php esc_html_e('Show average points', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Show average points', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="showAverageResult" <?php $this->checked($this->quiz->isShowAverageResult()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Statistics-function must be enabled.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Show category score', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Show category score', 'learndash'); ?></span> </legend> <label> <input type="checkbox" name="showCategoryScore" value="1" <?php $this->checked($this->quiz->isShowCategoryScore()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, the results of each category is displayed on the results page.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Hide correct questions - display', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Hide correct questions - display', 'learndash'); ?></span> </legend> <label> <input type="checkbox" name="hideResultCorrectQuestion" value="1" <?php $this->checked($this->quiz->isHideResultCorrectQuestion()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you select this option, no longer the number of correctly answered questions are displayed on the results page.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php echo sprintf( esc_html_x('Hide %s time - display', 'Hide quiz time - display', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php echo sprintf( esc_html_x('Hide %s time - display', 'Hide quiz time - display', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?></span> </legend> <label> <input type="checkbox" name="hideResultQuizTime" value="1" <?php $this->checked($this->quiz->isHideResultQuizTime()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('If you enable this option, the time for finishing the %s won\'t be displayed on the results page anymore.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Hide score - display', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Hide score - display', 'learndash'); ?></span> </legend> <label> <input type="checkbox" name="hideResultPoints" value="1" <?php $this->checked($this->quiz->isHideResultPoints()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, final score won\'t be displayed on the results page anymore.', 'learndash'); ?> </p> </fieldset> </td> </tr> </tbody> </table> </div> <?php } public function questionOptions() { ?> <div class="wrap wpProQuiz_quizEdit"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php esc_html_e('Show points', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Show points', 'learndash'); ?></span> </legend> <label for="show_points"> <input type="checkbox" id="show_points" value="1" name="showPoints" <?php echo $this->quiz->isShowPoints() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php echo sprintf( esc_html_x('Shows in %s, how many points are reachable for respective question.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' )); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Number answers', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Number answers', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="numberedAnswer" <?php echo $this->quiz->isNumberedAnswer() ? 'checked="checked"' : '' ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If this option is activated, all answers are numbered (only single and multiple choice)', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Hide correct- and incorrect message', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Hide correct- and incorrect message', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="hideAnswerMessageBox" <?php echo $this->quiz->isHideAnswerMessageBox() ? 'checked="checked"' : '' ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, no correct- or incorrect message will be displayed.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Correct and incorrect answer mark', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Correct and incorrect answer mark', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="disabledAnswerMark" <?php echo $this->quiz->isDisabledAnswerMark() ? 'checked="checked"' : '' ?>> <?php esc_html_e('Deactivate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, answers won\'t be color highlighted as correct or incorrect. ', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Force user to answer each question', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Force user to answer each question', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="forcingQuestionSolve" <?php $this->checked($this->quiz->isForcingQuestionSolve()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, the user is forced to answer each question.', 'learndash'); ?> <br> <?php esc_html_e('If the option "Question overview" is activated, this notification will appear after end of the quiz, otherwise after each question.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Hide question position overview', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Hide question position overview', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="hideQuestionPositionOverview" <?php $this->checked($this->quiz->isHideQuestionPositionOverview()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, the question position overview is hidden.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Hide question numbering', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Hide question numbering', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="hideQuestionNumbering" <?php $this->checked($this->quiz->isHideQuestionNumbering()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, the question numbering is hidden.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Display category', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Display category', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="showCategory" <?php $this->checked($this->quiz->isShowCategory()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, category will be displayed in the question.', 'learndash'); ?> </p> </fieldset> </td> </tr> </tbody> </table> </div> <?php } public function leaderboardOptions() { ?> <div class="wrap wpProQuiz_quizEdit"> <p><?php esc_html_e('The leaderboard allows users to enter results in public list and to share the result this way.', 'learndash'); ?></p> <p><?php esc_html_e('The leaderboard works independent from internal statistics function.', 'learndash'); ?></p> <table class="form-table"> <tbody id="toplistBox"> <tr> <th scope="row"> <?php esc_html_e('Leaderboard', 'learndash'); ?> </th> <td> <label> <input type="checkbox" name="toplistActivated" value="1" <?php echo $this->quiz->isToplistActivated() ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Who can sign up to the list', 'learndash'); ?> </th> <td> <label> <input name="toplistDataAddPermissions" type="radio" value="1" <?php echo $this->quiz->getToplistDataAddPermissions() == 1 ? 'checked="checked"' : ''; ?>> <?php esc_html_e('all users', 'learndash'); ?> </label> <label> <input name="toplistDataAddPermissions" type="radio" value="2" <?php echo $this->quiz->getToplistDataAddPermissions() == 2 ? 'checked="checked"' : ''; ?>> <?php esc_html_e('registered users only', 'learndash'); ?> </label> <label> <input name="toplistDataAddPermissions" type="radio" value="3" <?php echo $this->quiz->getToplistDataAddPermissions() == 3 ? 'checked="checked"' : ''; ?>> <?php esc_html_e('anonymous users only', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Not registered users have to enter name and e-mail (e-mail won\'t be displayed)', 'learndash'); ?> </p> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('insert automatically', 'learndash'); ?> </th> <td> <label> <input name="toplistDataAddAutomatic" type="checkbox" value="1" <?php $this->checked($this->quiz->isToplistDataAddAutomatic()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, logged in users will be automatically entered into leaderboard', 'learndash'); ?> </p> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('display captcha', 'learndash'); ?> </th> <td> <label> <input type="checkbox" name="toplistDataCaptcha" value="1" <?php echo $this->quiz->isToplistDataCaptcha() ? 'checked="checked"' : ''; ?> <?php echo $this->captchaIsInstalled ? '' : 'disabled="disabled"'; ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, additional captcha will be displayed for users who are not registered.', 'learndash'); ?> </p> <p class="description" style="color: red;"> <?php esc_html_e('This option requires additional plugin:', 'learndash'); ?> <a href="http://wordpress.org/extend/plugins/really-simple-captcha/" target="_blank">Really Simple CAPTCHA</a> </p> <?php if($this->captchaIsInstalled) { ?> <p class="description" style="color: green;"> <?php esc_html_e('Plugin has been detected.', 'learndash'); ?> </p> <?php } else { ?> <p class="description" style="color: red;"> <?php esc_html_e('Plugin is not installed.', 'learndash'); ?> </p> <?php } ?> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Sort list by', 'learndash'); ?> </th> <td> <label> <input name="toplistDataSort" type="radio" value="1" <?php echo ($this->quiz->getToplistDataSort() == 1) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('best user', 'learndash'); ?> </label> <label> <input name="toplistDataSort" type="radio" value="2" <?php echo ($this->quiz->getToplistDataSort() == 2) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('newest entry', 'learndash'); ?> </label> <label> <input name="toplistDataSort" type="radio" value="3" <?php echo ($this->quiz->getToplistDataSort() == 3) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('oldest entry', 'learndash'); ?> </label> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Users can apply multiple times', 'learndash'); ?> </th> <td> <div> <label> <input type="checkbox" name="toplistDataAddMultiple" value="1" <?php echo $this->quiz->isToplistDataAddMultiple() ? 'checked="checked"' : ''; ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> </div> <div id="toplistDataAddBlockBox" style="display: none;"> <label> <?php esc_html_e('User can apply after:', 'learndash'); ?> <input type="number" min="0" class="small-text" name="toplistDataAddBlock" value="<?php echo $this->quiz->getToplistDataAddBlock(); ?>"> <?php esc_html_e('minute', 'learndash'); ?> </label> </div> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('How many entries should be displayed', 'learndash'); ?> </th> <td> <div> <label> <input type="number" min="0" class="small-text" name="toplistDataShowLimit" value="<?php echo $this->quiz->getToplistDataShowLimit(); ?>"> <?php esc_html_e('Entries', 'learndash'); ?> </label> </div> </td> </tr> <tr id="AutomaticallyDisplayLeaderboard"> <th scope="row"> <?php echo sprintf( esc_html_x('Automatically display leaderboard in %s result', 'Automatically display leaderboard in quiz result', 'learndash'), learndash_get_custom_label_lower( 'quiz' )); ?> </th> <td> <div style="margin-top: 6px;"> <?php esc_html_e('Where should leaderboard be displayed:', 'learndash'); ?><br> <label style="margin-right: 5px; margin-left: 5px;"> <input type="radio" name="toplistDataShowIn" value="0" <?php echo ($this->quiz->getToplistDataShowIn() == 0) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('don\'t display', 'learndash'); ?> </label> <label> <input type="radio" name="toplistDataShowIn" value="1" <?php echo ($this->quiz->getToplistDataShowIn() == 1) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('below the "result text"', 'learndash'); ?> </label> <label> <input type="radio" name="toplistDataShowIn" value="2" <?php echo ($this->quiz->getToplistDataShowIn() == 2) ? 'checked="checked"' : ''; ?>> <?php esc_html_e('in a button', 'learndash'); ?> </label> </div> </td> </tr> </tbody> </table> </div> <?php } public function quizMode() { ?> <style> .wpProQuiz_quizModus th, .wpProQuiz_quizModus td { border-right: 1px solid #A0A0A0; padding: 5px; } </style> <div class="wrap wpProQuiz_quizEdit"> <table style="width: 100%; border-collapse: collapse; border: 1px solid #A0A0A0;" class="wpProQuiz_quizModus"> <thead> <tr> <th style="width: 25%;"><?php esc_html_e('Normal', 'learndash'); ?></th> <th style="width: 25%;"><?php esc_html_e('Normal + Back-Button', 'learndash'); ?></th> <th style="width: 25%;"><?php esc_html_e('Check -> continue', 'learndash'); ?></th> <th style="width: 25%;"><?php esc_html_e('Questions below each other', 'learndash'); ?></th> </tr> </thead> <tbody> <tr> <td><label><input type="radio" name="quizModus" value="0" <?php $this->checked($this->quiz->getQuizModus(), WpProQuiz_Model_Quiz::QUIZ_MODUS_NORMAL); ?>> <?php esc_html_e('Activate', 'learndash'); ?></label></td> <td><label><input type="radio" name="quizModus" value="1" <?php $this->checked($this->quiz->getQuizModus(), WpProQuiz_Model_Quiz::QUIZ_MODUS_BACK_BUTTON); ?>> <?php esc_html_e('Activate', 'learndash'); ?></label></td> <td><label><input type="radio" name="quizModus" value="2" <?php $this->checked($this->quiz->getQuizModus(), WpProQuiz_Model_Quiz::QUIZ_MODUS_CHECK); ?>> <?php esc_html_e('Activate', 'learndash'); ?></label></td> <td><label><input type="radio" name="quizModus" value="3" <?php $this->checked($this->quiz->getQuizModus(), WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE); ?>> <?php esc_html_e('Activate', 'learndash'); ?></label></td> </tr> <tr> <td> <?php echo sprintf( esc_html_x('Displays all questions sequentially, "right" or "false" will be displayed at the end of the %s.', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </td> <td> <?php esc_html_e('Allows to use the back button in a question.', 'learndash'); ?> </td> <td> <?php esc_html_e('Shows "right or wrong" after each question.', 'learndash'); ?> </td> <td> <?php esc_html_e('If this option is activated, all answers are displayed below each other, i.e. all questions are on a single page.', 'learndash'); ?> </td> </tr> <tr> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td></td> <td></td> <td></td> <td> <?php esc_html_e('How many questions to be displayed on a page:', 'learndash'); ?><br> <input type="number" name="questionsPerPage" value="<?php echo $this->quiz->getQuestionsPerPage(); ?>" min="0"> <span class="description"> <?php esc_html_e('(0 = All on one page)', 'learndash'); ?> </span> </td> </tr> </tbody> </table> </div> <?php } public function form() { $forms = $this->forms; $index = 0; if ( !is_array( $forms ) ) $forms = array(); if(!count($forms)) $forms = array(new WpProQuiz_Model_Form(), new WpProQuiz_Model_Form()); else array_unshift($forms, new WpProQuiz_Model_Form()); ?> <div class="wrap wpProQuiz_quizEdit"> <p class="description"> <?php esc_html_e('You can create custom fields, e.g. to request the name or the e-mail address of the users.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('The statistic function have to be enabled.', 'learndash'); ?> </p> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php esc_html_e('Custom fields enable', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Custom fields enable', 'learndash'); ?></span> </legend> <label> <input type="checkbox" id="formActivated" value="1" name="formActivated" <?php $this->checked($this->quiz->isFormActivated()); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('If you enable this option, custom fields are enabled.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Display position', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Display position', 'learndash'); ?></span> </legend> <?php esc_html_e('Where should the fields be displayed:', 'learndash'); ?><br> <label> <input type="radio" value="<?php echo WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_START; ?>" name="formShowPosition" <?php $this->checked($this->quiz->getFormShowPosition(), WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_START); ?>> <?php echo sprintf( esc_html_x('On the %s startpage', 'On the quiz startpage', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </label> <label> <input type="radio" value="<?php echo WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_END; ?>" name="formShowPosition" <?php $this->checked($this->quiz->getFormShowPosition(), WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_END); ?> > <?php echo sprintf( esc_html_x('At the end of the %s (before the %s result)', 'At the end of the quiz (before the quiz result)', 'learndash'), learndash_get_custom_label_lower( 'quiz' ), learndash_get_custom_label_lower( 'quiz' ) ); ?> </label> </fieldset> </td> </tr> </tbody> </table> <div style="margin-top: 10px; padding: 10px; border: 1px solid #C2C2C2;"> <table style=" width: 100%; text-align: left; " id="form_table"> <thead> <tr> <th><?php esc_html_e('Field name', 'learndash'); ?></th> <th><?php esc_html_e('Type', 'learndash'); ?></th> <th><?php esc_html_e('Required?', 'learndash'); ?></th> <th></th> </tr> </thead> <tbody> <?php foreach($forms as $form) { $checkType = $this->selectedArray($form->getType(), array( WpProQuiz_Model_Form::FORM_TYPE_TEXT, WpProQuiz_Model_Form::FORM_TYPE_TEXTAREA, WpProQuiz_Model_Form::FORM_TYPE_CHECKBOX, WpProQuiz_Model_Form::FORM_TYPE_SELECT, WpProQuiz_Model_Form::FORM_TYPE_RADIO, WpProQuiz_Model_Form::FORM_TYPE_NUMBER, WpProQuiz_Model_Form::FORM_TYPE_EMAIL, WpProQuiz_Model_Form::FORM_TYPE_YES_NO, WpProQuiz_Model_Form::FORM_TYPE_DATE )); ?> <tr <?php echo $index++ == 0 ? 'style="display: none;"' : '' ?>> <td> <input type="text" name="form[][fieldname]" value="<?php echo esc_attr($form->getFieldname()); ?>" class="regular-text"/> </td> <td style="position: relative;"> <select name="form[][type]"> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_TEXT; ?>" <?php echo $checkType[0]; ?>><?php esc_html_e('Text', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_TEXTAREA; ?>" <?php echo $checkType[1]; ?>><?php esc_html_e('TextArea', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_CHECKBOX; ?>" <?php echo $checkType[2]; ?>><?php esc_html_e('Checkbox', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_SELECT; ?>" <?php echo $checkType[3]; ?>><?php esc_html_e('Drop-Down menu', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_RADIO; ?>" <?php echo $checkType[4]; ?>><?php esc_html_e('Radio', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_NUMBER; ?>" <?php echo $checkType[5]; ?>><?php esc_html_e('Number', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_EMAIL; ?>" <?php echo $checkType[6]; ?>><?php esc_html_e('Email', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_YES_NO; ?>" <?php echo $checkType[7]; ?>><?php esc_html_e('Yes/No', 'learndash'); ?></option> <option value="<?php echo WpProQuiz_Model_Form::FORM_TYPE_DATE; ?>" <?php echo $checkType[8]; ?>><?php esc_html_e('Date', 'learndash'); ?></option> </select> <a href="#" class="editDropDown"><?php esc_html_e('Edit list', 'learndash'); ?></a> <div class="dropDownEditBox" style="position: absolute; border: 1px solid #AFAFAF; background: #EBEBEB; padding: 5px; bottom: 0;right: 0;box-shadow: 1px 1px 1px 1px #AFAFAF; display: none;"> <h4><?php esc_html_e('One entry per line', 'learndash'); ?></h4> <div> <textarea rows="5" cols="50" name="form[][data]"><?php echo $form->getData() === null ? '' : esc_textarea(implode("\n", $form->getData())); ?></textarea> </div> <input type="button" value="<?php esc_html_e('OK', 'learndash'); ?>" class="button-primary"> </div> </td> <td> <input type="checkbox" name="form[][required]" value="1" <?php $this->checked($form->isRequired()); ?>> </td> <td> <input type="button" name="form_delete" value="<?php esc_html_e('Delete', 'learndash'); ?>" class="button-secondary"> <a class="form_move button-secondary" href="#" style="cursor:move;"><?php esc_html_e('Move', 'learndash'); ?></a> <input type="hidden" name="form[][form_id]" value="<?php echo $form->getFormId(); ?>"> <input type="hidden" name="form[][form_delete]" value="0"> </td> </tr> <?php } ?> </tbody> </table> <div style="margin-top: 10px;"> <input type="button" name="form_add" id="form_add" value="<?php esc_html_e('Add field', 'learndash'); ?>" class="button-secondary"> </div> </div> </div> <?php } public function resultText() { return; ?> <div class="wrap wpProQuiz_quizEdit"> <h3 class="hndle"><?php esc_html_e('Results text', 'learndash'); ?> <?php esc_html_e('(optional)', 'learndash'); ?></h3> <div class="inside"> <p class="description"> <?php echo sprintf( esc_html_x('This text will be displayed at the end of the %s (in results). (this text is optional)', 'placeholders: quiz', 'learndash'), learndash_get_custom_label_lower( 'quiz' ) ); ?> </p> <div style="padding-top: 10px; padding-bottom: 10px;"> <label for="wpProQuiz_resultGradeEnabled"> <?php esc_html_e('Activate graduation', 'learndash'); ?> <input type="checkbox" name="resultGradeEnabled" id="wpProQuiz_resultGradeEnabled" value="1" <?php echo $this->quiz->isResultGradeEnabled() ? 'checked="checked"' : ''; ?>> </label> </div> <div style="display: none;" id="resultGrade"> <div> <strong><?php esc_html_e('Hint:', 'learndash'); ?></strong> <ul style="list-style-type: square; padding: 5px; margin-left: 20px; margin-top: 0;"> <li><?php esc_html_e('Maximal 15 levels', 'learndash'); ?></li> <li> <?php echo sprintf( esc_html_x('Percentages refer to the total score of the %1$s. (Current total %2d points in %3$d questions.)', 'placeholders: quiz, question points, question count', 'learndash'), learndash_get_custom_label_lower( 'quiz' ), $this->quiz->fetchSumQuestionPoints(), $this->quiz->fetchCountQuestions()); ?> </li> <li><?php esc_html_e('Values can also be mixed up', 'learndash'); ?></li> <li><?php esc_html_e('10,15% or 10.15% allowed (max. two digits after the decimal point)', 'learndash'); ?></li> </ul> </div> <div> <ul id="resultList"> <?php $resultText = $this->quiz->getResultText(); for($i = 0; $i < 15; $i++) { if($this->quiz->isResultGradeEnabled() && isset($resultText['text'][$i])) { ?> <li style="padding: 5px; border: 1; border: 1px dotted;"> <div style="margin-bottom: 5px;"><?php wp_editor($resultText['text'][$i], 'resultText_'.$i, array('textarea_rows' => 3, 'textarea_name' => 'resultTextGrade[text][]')); ?></div> <div style="margin-bottom: 5px;background-color: rgb(207, 207, 207);padding: 10px;"> <?php esc_html_e('from:', 'learndash'); ?> <input type="text" name="resultTextGrade[prozent][]" class="small-text" value="<?php echo $resultText['prozent'][$i]?>"> <?php esc_html_e('percent', 'learndash'); ?> <?php printf(__('(Will be displayed, when result-percent is >= <span class="resultProzent">%s</span>%%)', 'learndash'), $resultText['prozent'][$i]); ?> <input type="button" style="float: right;" class="button-primary deleteResult" value="<?php esc_html_e('Delete graduation', 'learndash'); ?>"> <div style="clear: right;"></div> <input type="hidden" value="1" name="resultTextGrade[activ][]"> </div> </li> <?php } else { ?> <li style="padding: 5px; border: 1; border: 1px dotted; <?php echo $i ? 'display:none;' : '' ?>"> <div style="margin-bottom: 5px;"><?php wp_editor('', 'resultText_'.$i, array('textarea_rows' => 3, 'textarea_name' => 'resultTextGrade[text][]')); ?></div> <div style="margin-bottom: 5px;background-color: rgb(207, 207, 207);padding: 10px;"> <?php esc_html_e('from:', 'learndash'); ?> <input type="text" name="resultTextGrade[prozent][]" class="small-text" value="0"> <?php esc_html_e('percent', 'learndash'); ?> <?php printf(__('(Will be displayed, when result-percent is >= <span class="resultProzent">%s</span>%%)', 'learndash'), '0'); ?> <input type="button" style="float: right;" class="button-primary deleteResult" value="<?php esc_html_e('Delete graduation', 'learndash'); ?>"> <div style="clear: right;"></div> <input type="hidden" value="<?php echo $i ? '0' : '1' ?>" name="resultTextGrade[activ][]"> </div> </li> <?php } } ?> </ul> <input type="button" class="button-primary addResult" value="<?php esc_html_e('Add graduation', 'learndash'); ?>"> </div> </div> <div id="resultNormal"> <?php $resultText = is_array($resultText) ? '' : $resultText; wp_editor($resultText, 'resultText', array('textarea_rows' => 10)); ?> </div> </div> </div> <?php } } lib/view/WpProQuiz_View_GobalSettings.php 0000666 00000060144 15214236625 0014553 0 ustar 00 <?php class WpProQuiz_View_GobalSettings extends WpProQuiz_View_View { public function show() { ?> <div class="wrap wpProQuiz_globalSettings"> <h2 style="margin-bottom: 10px;"><?php echo sprintf( esc_html_x('%s Options', 'Quiz Options', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?></h2> <a class="button-secondary" style="display:none" href="admin.php?page=ldAdvQuiz"><?php esc_html_e('back to overview', 'learndash'); ?></a> <div class="wpProQuiz_tab_wrapper" style="padding: 10px 0px;"> <a class="button-primary" href="#" data-tab="#globalContent"><?php echo sprintf( esc_html_x('%s Options', 'Quiz Options', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ); ?></a> <a class="button-secondary" href="#" data-tab="#emailSettingsTab"><?php esc_html_e('E-Mail settings', 'learndash'); ?></a> <a class="button-secondary" href="#" data-tab="#problemContent"><?php esc_html_e('Settings in case of problems', 'learndash'); ?></a> </div> <form method="post"> <div id="poststuff"> <div id="globalContent"> <?php $this->globalSettings(); ?> </div> <div id="emailSettingsTab" style="display: none;"> <?php $this->emailSettingsTab(); ?> </div> <div class="postbox" id="problemContent" style="display: none;"> <?php $this->problemSettings(); ?> </div> <input type="submit" name="submit" class="button-primary" id="wpProQuiz_save" value="<?php esc_html_e('Save', 'learndash'); ?>"> </div> </form> </div> <?php } private function globalSettings() { ?> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Global settings', 'learndash'); ?></h3> <div class="wrap"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php esc_html_e('Leaderboard time format', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Leaderboard time format', 'learndash'); ?></span> </legend> <label> <input type="radio" name="toplist_date_format" value="d.m.Y H:i" <?php $this->checked($this->toplistDataFormat, 'd.m.Y H:i'); ?>> 06.11.2010 12:50 </label> <br> <label> <input type="radio" name="toplist_date_format" value="Y/m/d g:i A" <?php $this->checked($this->toplistDataFormat, 'Y/m/d g:i A'); ?>> 2010/11/06 12:50 AM </label> <br> <label> <input type="radio" name="toplist_date_format" value="Y/m/d \a\t g:i A" <?php $this->checked($this->toplistDataFormat, 'Y/m/d \a\t g:i A'); ?>> 2010/11/06 at 12:50 AM </label> <br> <label> <input type="radio" name="toplist_date_format" value="Y/m/d \a\t g:ia" <?php $this->checked($this->toplistDataFormat, 'Y/m/d \a\t g:ia'); ?>> 2010/11/06 at 12:50am </label> <br> <label> <input type="radio" name="toplist_date_format" value="F j, Y g:i a" <?php $this->checked($this->toplistDataFormat, 'F j, Y g:i a'); ?>> November 6, 2010 12:50 am </label> <br> <label> <input type="radio" name="toplist_date_format" value="M j, Y @ G:i" <?php $this->checked($this->toplistDataFormat, 'M j, Y @ G:i'); ?>> Nov 6, 2010 @ 0:50 </label> <br> <label> <input type="radio" name="toplist_date_format" value="custom" <?php echo in_array($this->toplistDataFormat, array('d.m.Y H:i', 'Y/m/d g:i A', 'Y/m/d \a\t g:i A', 'Y/m/d \a\t g:ia', 'F j, Y g:i a', 'M j, Y @ G:i')) ? '' : 'checked="checked"'; ?> > <?php esc_html_e('Custom', 'learndash'); ?>: <input class="medium-text" name="toplist_date_format_custom" style="width: 100px;" value="<?php echo $this->toplistDataFormat; ?>"> </label> <p> <a href="http://codex.wordpress.org/Formatting_Date_and_Time" target="_blank"><?php esc_html_e('Documentation on date and time formatting', 'learndash'); ?></a> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Statistic time format', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Statistic time format', 'learndash'); ?></span> </legend> <label> <?php esc_html_e('Select example:', 'learndash'); ?> <select id="statistic_time_format_select"> <option value="0"></option> <option value="d.m.Y H:i"> 06.11.2010 12:50</option> <option value="Y/m/d g:i A"> 2010/11/06 12:50 AM</option> <option value="Y/m/d \a\t g:i A"> 2010/11/06 at 12:50 AM</option> <option value="Y/m/d \a\t g:ia"> 2010/11/06 at 12:50am</option> <option value="F j, Y g:i a"> November 6, 2010 12:50 am</option> <option value="M j, Y @ G:i"> Nov 6, 2010 @ 0:50</option> </select> </label> <div style="margin-top: 10px;"> <label> <?php esc_html_e('Time format:', 'learndash'); ?>: <input class="medium-text" name="statisticTimeFormat" value="<?php echo $this->statisticTimeFormat; ?>"> </label> <p> <a href="http://codex.wordpress.org/Formatting_Date_and_Time" target="_blank"><?php esc_html_e('Documentation on date and time formatting', 'learndash'); ?></a> </p> </div> </fieldset> </td> </tr> <?php if (count($this->category)) { ?> <tr> <th scope="row"> <?php esc_html_e('Question Category management', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Question Category management', 'learndash'); ?></span> </legend> <select name="category"> <option value=""><?php esc_html_e('Select Question Category', 'learndash'); ?></option> <?php foreach($this->category as $cat) { echo '<option value="'.$cat->getCategoryId().'">'.$cat->getCategoryName().'</option>'; } ?> </select> <div style="padding-top: 5px;"> <input type="text" value="" name="categoryEditText" class="regular-text" /> </div> <div style="padding-top: 5px;"> <input type="button" title="<?php esc_html_e('Delete selected Question Category', 'learndash') ?>" value="<?php esc_html_e('Delete', 'learndash'); ?>" name="categoryDelete" class="button-secondary"> <input type="button" title="<?php esc_html_e('Save changed to selected Question Category', 'learndash') ?>" value="<?php esc_html_e('Save Changes', 'learndash'); ?>" name="categoryEdit" class="button-secondary"> <div class="categorySpinner spinner"></div> <span class="categoryEditUpdate" style="display:none"><?php esc_html_e('Question Category Saved', 'learndash') ?></span> <span class="categoryDeleteUpdate" style="display:none"><?php esc_html_e('Question Category Deleted', 'learndash') ?></span> </div> </fieldset> </td> </tr> <?php } ?> <?php if (count($this->templateQuiz)) { ?> <tr> <th scope="row"> <?php echo sprintf( esc_html_x('%s template management', 'Quiz template management', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php echo sprintf( esc_html_x('%s template management', 'Quiz template management', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )); ?></span> </legend> <select name="templateQuiz"> <option value=""><?php echo sprintf( esc_html_x('Select %s template', 'Select Quiz template', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )); ?></option> <?php foreach($this->templateQuiz as $templateQuiz) { echo '<option value="'.$templateQuiz->getTemplateId().'">'.esc_html($templateQuiz->getName()).'</option>'; } ?> </select> <div style="padding-top: 5px;"> <input type="text" value="" name="templateQuizEditText" class="regular-text" /> </div> <div style="padding-top: 5px;"> <input type="button" title="<?php echo sprintf( esc_html_x('Delete selected %s template', 'Delete selected Quiz template', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' )) ?>" value="<?php esc_html_e('Delete', 'learndash'); ?>" name="templateQuizDelete" class="button-secondary"> <input type="button" title="<?php echo sprintf( esc_html_x('Save changed to selected %s template', 'Save changed to selected Quiz template', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ) ?>" value="<?php esc_html_e('Save Changes', 'learndash'); ?>" name="templateQuizEdit" class="button-secondary"> <div class="templateQuizSpinner spinner"></div> <span class="templateQuizEditUpdate" style="display:none"><?php echo sprintf( esc_html_x('%s template Saved', 'Quiz template Saved', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ) ?></span> <span class="templateQuizDeleteUpdate" style="display:none"><?php echo sprintf( esc_html_x('%s template Deleted', 'Quiz template Deleted', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ) ) ?></span> </div> </fieldset> </td> </tr> <?php } ?> <?php if (count($this->templateQuestion)) { ?> <tr> <th scope="row"> <?php esc_html_e('Question template management', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Question template management', 'learndash'); ?></span> </legend> <select name="templateQuestion"> <option value=""><?php esc_html_e('Select Question template', 'learndash'); ?></option> <?php foreach($this->templateQuestion as $templateQuestion) { echo '<option value="'.$templateQuestion->getTemplateId().'">'.esc_html($templateQuestion->getName()).'</option>'; } ?> </select> <div style="padding-top: 5px;"> <input type="text" value="" name="templateQuestionEditText" class="regular-text" /> </div> <div style="padding-top: 5px;"> <input type="button" title="<?php esc_html_e('Delete selected Question template', 'learndash') ?>" value="<?php esc_html_e('Delete', 'learndash'); ?>" name="templateQuestionDelete" class="button-secondary"> <input type="button" title="<?php esc_html_e('Save changed to selected Question template', 'learndash') ?>" value="<?php esc_html_e('Save Changes', 'learndash'); ?>" name="templateQuestionEdit" class="button-secondary"> <div class="templateQuestionSpinner spinner"></div> <span class="templateQuestionEditUpdate" style="display:none"><?php esc_html_e('Question template Saved', 'learndash') ?></span> <span class="templateQuestionDeleteUpdate" style="display:none"><?php esc_html_e('Question template Deleted', 'learndash') ?></span> </div> </fieldset> </td> </tr> <?php } ?> </tbody> </table> </div> </div> <?php } private function emailSettings() { ?> <div class="postbox" id="adminEmailSettings"> <h3 class="hndle"><?php esc_html_e('Admin e-mail settings', 'learndash'); ?></h3> <div class="wrap"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php esc_html_e('To:', 'learndash'); ?> </th> <td> <label> <input type="text" name="email[to]" value="<?php echo $this->email['to']; ?>" class="regular-text"> </label> <p class="description"> <?php esc_html_e('Separate multiple email addresses with a comma, e.g. wp@test.com, test@test.com', 'learndash'); ?> </p> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('From Name:', 'learndash'); ?> </th> <td> <label> <input type="text" name="email[from_name]" value="<?php echo (isset($this->email['from_name']))? $this->email['from_name'] : ''; ?>" class="regular-text"> </label> <p class="description"><?php esc_html_e('This is the email name of the sender. If not provided will default to the system email name.', 'learndash' ); ?></p> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('From Email:', 'learndash'); ?> </th> <td> <?php if ( ( !empty( $this->email['from'] ) ) && ( !is_email( $this->email['from'] ) ) ) { ?><p class="ld-error error-message"><?php esc_html_e('The value entered is not a valid email address', 'learndash'); ?></p><?php } ?> <label> <input type="text" name="email[from]" value="<?php echo (isset($this->email['from'])) ? $this->email['from'] : ''; ?>" class="regular-text"> </label> <p class="description"> <?php echo sprintf( wp_kses_post( __('This is the email address of the sender. If not provided the admin email <strong>(%s)</strong> will be used.', 'learndash') ), get_option('admin_email') ); ?> </p> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Subject:', 'learndash'); ?> </th> <td> <label> <input type="text" name="email[subject]" value="<?php echo $this->email['subject']; ?>" class="regular-text"> </label> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('HTML', 'learndash'); ?> </th> <td> <label> <input type="checkbox" name="email[html]" value="1" <?php $this->checked(isset($this->email['html']) ? $this->email['html'] : false); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Message body:', 'learndash'); ?> </th> <td> <?php wp_editor($this->email['message'], 'adminEmailEditor', array('textarea_rows' => 20, 'textarea_name' => 'email[message]')); ?> <div> <h4><?php esc_html_e('Allowed variables', 'learndash'); ?>:</h4> <ul> <li><span>$userId</span> - <?php esc_html_e('User-ID', 'learndash'); ?></li> <li><span>$username</span> - <?php esc_html_e('Username', 'learndash'); ?></li> <li><span>$quizname</span> - <?php esc_html_e('Quiz-Name', 'learndash'); ?></li> <li><span>$result</span> - <?php esc_html_e('Result in precent', 'learndash'); ?></li> <li><span>$points</span> - <?php esc_html_e('Reached points', 'learndash'); ?></li> <li><span>$ip</span> - <?php esc_html_e('IP-address of the user', 'learndash'); ?></li> <li><span>$categories</span> - <?php esc_html_e('Category-Overview', 'learndash'); ?></li> </ul> </div> </td> </tr> </tbody> </table> </div> </div> <?php } private function userEmailSettings() { ?> <div class="postbox" id="userEmailSettings" style="display: none;"> <h3 class="hndle"><?php esc_html_e('User e-mail settings', 'learndash'); ?></h3> <div class="wrap"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php esc_html_e('From Name:', 'learndash'); ?> </th> <td> <label> <input type="text" name="userEmail[from_name]" value="<?php echo (isset($this->userEmail['from_name'])) ? $this->userEmail['from_name'] : ''; ?>" class="regular-text"> </label> <p class="description"> <?php esc_html_e('This is the email name of the sender. If not provided will default to the system email name.', 'learndash' ); ?> </p> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('From Email:', 'learndash'); ?> </th> <td> <?php if ( ( !empty( $this->email['from'] ) ) && ( !is_email( $this->userEmail['from'] ) ) ) { ?><p class="ld-error error-message"><?php esc_html_e('The value entered is not a valid email address', 'learndash'); ?></p><?php } ?> <label> <input type="text" name="userEmail[from]" value="<?php echo (isset($this->userEmail['from'])) ? $this->userEmail['from'] : ''; ?>" class="regular-text"> </label> <p class="description"> <?php echo sprintf( wp_kses_post( __('This is the email address of the sender. If not provided the admin email <strong>(%s)</strong> will be used.', 'learndash') ), get_option('admin_email') ); ?> </p> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Subject:', 'learndash'); ?> </th> <td> <label> <input type="text" name="userEmail[subject]" value="<?php echo $this->userEmail['subject']; ?>" class="regular-text"> </label> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('HTML', 'learndash'); ?> </th> <td> <label> <input type="checkbox" name="userEmail[html]" value="1" <?php $this->checked($this->userEmail['html']); ?>> <?php esc_html_e('Activate', 'learndash'); ?> </label> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Message body:', 'learndash'); ?> </th> <td> <?php wp_editor($this->userEmail['message'], 'userEmailEditor', array('textarea_rows' => 20, 'textarea_name' => 'userEmail[message]')); ?> <div> <h4><?php esc_html_e('Allowed variables', 'learndash'); ?>:</h4> <ul> <li><span>$userId</span> - <?php esc_html_e('User-ID', 'learndash'); ?></li> <li><span>$username</span> - <?php esc_html_e('Username', 'learndash'); ?></li> <li><span>$quizname</span> - <?php esc_html_e('Quiz-Name', 'learndash'); ?></li> <li><span>$result</span> - <?php esc_html_e('Result in precent', 'learndash'); ?></li> <li><span>$points</span> - <?php esc_html_e('Reached points', 'learndash'); ?></li> <li><span>$ip</span> - <?php esc_html_e('IP-address of the user', 'learndash'); ?></li> <li><span>$categories</span> - <?php esc_html_e('Category-Overview', 'learndash'); ?></li> </ul> </div> </td> </tr> </tbody> </table> </div> </div> <?php } private function problemSettings() { if($this->isRaw) { $rawSystem = esc_html__('to activate', 'learndash'); } else { $rawSystem = esc_html__('not to activate', 'learndash'); } ?> <div class="updated" id="problemInfo" style="display: none;"> <h3><?php esc_html_e('Please note', 'learndash'); ?></h3> <p> <?php esc_html_e('These settings should only be set in cases of problems with LD Advanced Quiz.', 'learndash'); ?> </p> </div> <h3 class="hndle"><?php esc_html_e('Settings in case of problems', 'learndash'); ?></h3> <div class="wrap"> <table class="form-table"> <tbody> <tr> <th scope="row"> <?php esc_html_e('Automatically add [raw] shortcode', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Automatically add [raw] shortcode', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="addRawShortcode" <?php echo $this->settings->isAddRawShortcode() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> <span class="description">( <?php printf(__('It is recommended %s this option on your system.', 'learndash'), '<span style=" font-weight: bold;">'.$rawSystem.'</span>'); ?> )</span> </label> <p class="description"> <?php esc_html_e('If this option is activated, a [raw] shortcode is automatically set around LDAdvQuiz shortcode ( [LDAdvQuiz X] ) into [raw] [LDAdvQuiz X] [/raw]', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('Own themes changes internal order of filters, what causes the problems. With additional shortcode [raw] this is prevented.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Do not load the Javascript-files in the footer', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Do not load the Javascript-files in the footer', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="jsLoadInHead" <?php echo $this->settings->isJsLoadInHead() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Generally all LDAdvQuiz-Javascript files are loaded in the footer and only when they are really needed.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('In very old Wordpress themes this can lead to problems.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('If you activate this option, all LDAdvQuiz-Javascript files are loaded in the header even if they are not needed.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Touch Library', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Touch Library', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="touchLibraryDeactivate" <?php echo $this->settings->isTouchLibraryDeactivate() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Deactivate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('In Version 0.13 a new Touch Library was added for mobile devices.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('If you have any problems with the Touch Library, please deactivate it.', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('jQuery support cors', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('jQuery support cors', 'learndash'); ?></span> </legend> <label> <input type="checkbox" value="1" name="corsActivated" <?php echo $this->settings->isCorsActivated() ? 'checked="checked"' : '' ?> > <?php esc_html_e('Activate', 'learndash'); ?> </label> <p class="description"> <?php esc_html_e('Is required only in rare cases.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('If you have problems with the front ajax, please activate it.', 'learndash'); ?> </p> <p class="description"> <?php esc_html_e('e.g. Domain with special characters in combination with IE', 'learndash'); ?> </p> </fieldset> </td> </tr> <tr> <th scope="row"> <?php esc_html_e('Repair database', 'learndash'); ?> </th> <td> <fieldset> <legend class="screen-reader-text"> <span><?php esc_html_e('Repair database', 'learndash'); ?></span> </legend> <input type="submit" name="databaseFix" class="button-primary" value="<?php esc_html_e('Repair database', 'learndash');?>"> <p class="description"> <?php esc_html_e('No data will be deleted. Only LDAdvQuiz tables will be repaired.', 'learndash'); ?> </p> </fieldset> </td> </tr> </tbody> </table> </div> <?php } private function emailSettingsTab() { ?> <div class="wpProQuiz_tab_wrapper" style="padding-bottom: 10px;"> <a class="button-primary" href="#" data-tab="#adminEmailSettings"><?php esc_html_e('Admin e-mail settings', 'learndash'); ?></a> <a class="button-secondary" href="#" data-tab="#userEmailSettings"><?php esc_html_e('User e-mail settings', 'learndash'); ?></a> </div> <?php $this->emailSettings(); ?> <?php $this->userEmailSettings(); ?> <?php } } lib/view/WpProQuiz_View_StatisticsNew.php 0000666 00000021447 15214236625 0014615 0 ustar 00 <?php class WpProQuiz_View_StatisticsNew extends WpProQuiz_View_View { /** * @var WpProQuiz_Model_Quiz */ public $quiz; public function show() { ?> <style> .wpProQuiz_blueBox { padding: 20px; background-color: rgb(223, 238, 255); border: 1px dotted; margin-top: 10px; } .categoryTr th { background-color: #F1F1F1; } .wpProQuiz_modal_backdrop { background: #000; opacity: 0.7; top: 0; bottom: 0; right: 0; left: 0; position: fixed; z-index: 159900; } .wpProQuiz_modal_window { position: fixed; background: #FFF; top: 40px; bottom: 40px; left: 40px; right: 40px; z-index: 160000; } .wpProQuiz_actions { display: none; padding: 2px 0 0; } .mobile .wpProQuiz_actions { display: block; } tr:hover .wpProQuiz_actions { display: block; } </style> <div class="wrap wpProQuiz_statisticsNew"> <input type="hidden" id="quizId" value="<?php echo $this->quiz->getId(); ?>" name="quizId"> <?php /* ?><h1><?php echo sprintf( esc_html_x('%1$s: %2$s - Statistics', 'placeholders: Quiz, Quiz Name/Title', 'learndash'), LearnDash_Custom_Label::get_label( 'quiz' ), $this->quiz->getName()); ?></h1><?php */ ?> <br> <?php if(!$this->quiz->isStatisticsOn()) { ?> <p style="padding: 30px; background: #F7E4E4; border: 1px dotted; width: 300px;"> <span style="font-weight: bold; padding-right: 10px;"><?php esc_html_e('Stats not enabled', 'learndash'); ?></span> <a class="button-secondary" href="admin.php?page=ldAdvQuiz&action=addEdit&quizId=<?php echo $this->quiz->getId(); ?>&post_id=<?php echo @$_GET['post_id']; ?>"><?php esc_html_e('Activate statistics', 'learndash'); ?></a> </p> <?php return; } ?> <div style="padding: 10px 0px;" class="wpProQuiz_tab_wrapper"> <a class="button-primary" href="#" data-tab="#wpProQuiz_tabHistory"><?php esc_html_e('History', 'learndash'); ?></a> <a class="button-secondary" href="#" data-tab="#wpProQuiz_tabOverview"><?php esc_html_e('Overview', 'learndash'); ?></a> </div> <div id="wpProQuiz_loadData" class="wpProQuiz_blueBox" style="background-color: #F8F5A8; display: none;"> <img alt="load" src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" /> <?php esc_html_e('Loading', 'learndash'); ?> </div> <div id="wpProQuiz_content" style="display: block;"> <?php $this->showHistory(); ?> <?php $this->showTabOverview(); ?> </div> <?php $this->showModalWindow(); ?> </div> <?php } private function showHistory() { ?> <div id="wpProQuiz_tabHistory" class="wpProQuiz_tabContent" style="display: block;"> <div id="poststuff"> <div class="postbox"> <h2 class="hndle"><?php esc_html_e('Filter', 'learndash'); ?></h2> <div class="inside"> <ul> <li> <label> <?php esc_html_e('Which users should be displayed:', 'learndash'); ?> <select id="wpProQuiz_historyUser"> <optgroup label="<?php esc_html_e('special filter', 'learndash'); ?>"> <option value="-1" selected="selected"><?php esc_html_e('all users', 'learndash'); ?></option> <option value="-2"><?php esc_html_e('only registered users', 'learndash'); ?></option> <option value="-3"><?php esc_html_e('only anonymous users', 'learndash'); ?></option> </optgroup> <optgroup label="<?php esc_html_e('User', 'learndash'); ?>"> <?php foreach($this->users as $user) { if($user->ID == 0) continue; echo '<option value="', $user->ID, '">', $user->user_login, ' (', $user->display_name, ')</option>'; } ?> </optgroup> </select> </label> </li> <li> <label> <?php esc_html_e('How many entries should be shown on one page:', 'learndash'); ?> <select id="wpProQuiz_historyPageLimit"> <option>1</option> <option selected="selected">10</option> <option>50</option> <option>100</option> <option>500</option> <option>1000</option> </select> </label> </li> <li> <?php $dateVon = '<input type="text" id="datepickerFrom" class="learndash-datepicker-field" />'; $dateBis = '<input type="text" id="datepickerTo" class="learndash-datepicker-field" />'; printf(__('Search to date limit from %s to %s', 'learndash'), $dateVon, $dateBis); ?> </li> <li> <input type="button" value="<?php esc_html_e('Filter', 'learndash'); ?>" class="button-secondary" id="filter"> </li> </ul> </div> </div> </div> <div id="wpProQuiz_loadDataHistory" class="wpProQuiz_blueBox" style="background-color: #F8F5A8; display: none;"> <img alt="load" src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" /> <?php esc_html_e('Loading', 'learndash'); ?> </div> <div id="wpProQuiz_historyLoadContext"></div> <div style="margin-top: 10px;"> <div style="float: left;" id="historyNavigation"> <input style="font-weight: bold;" class="button-secondary navigationLeft" value="<" type="button"> <select class="navigationCurrentPage"><option value="1">1</option></select> <input style="font-weight: bold;" class="button-secondary navigationRight" value=">" type="button"> </div> <div style="float: right;"> <a class="button-secondary wpProQuiz_update" href="#"><?php esc_html_e('Refresh', 'learndash'); ?></a> <?php if(current_user_can('wpProQuiz_reset_statistics')) { ?> <a class="button-secondary wpProQuiz_resetComplete" href="#"><?php esc_html_e('Reset entire statistic', 'learndash'); ?></a> <?php } ?> </div> <div style="clear: both;"></div> </div> </div> <?php } private function showModalWindow() { ?> <div id="wpProQuiz_user_overlay" style="display: none;"> <div class="wpProQuiz_modal_window" style="padding: 20px; overflow: scroll;"> <input type="button" value="<?php esc_html_e('Close', 'learndash'); ?>" class="button-primary" style=" position: fixed; top: 48px; right: 59px; z-index: 160001;" id="wpProQuiz_overlay_close"> <div id="wpProQuiz_user_content" style="margin-top: 20px;"></div> <div id="wpProQuiz_loadUserData" class="wpProQuiz_blueBox" style="background-color: #F8F5A8; display: none; margin: 50px;"> <img alt="load" src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" /> <?php esc_html_e('Loading', 'learndash'); ?> </div> </div> <div class="wpProQuiz_modal_backdrop"></div> </div> <?php } private function showTabOverview() { ?> <div id="wpProQuiz_tabOverview" class="wpProQuiz_tabContent" style="display: none;"> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Filter', 'learndash'); ?></h3> <div class="inside"> <ul> <li> <label> <?php echo sprintf( esc_html_x('Show only users, who solved the %s:', 'Show only users, who solved the quiz:', 'learndash'), learndash_get_custom_label_lower( 'quiz' )); ?> <input type="checkbox" value="1" id="wpProQuiz_overviewOnlyCompleted"> </label> </li> <li> <label> <?php esc_html_e('How many entries should be shown on one page:', 'learndash'); ?> <select id="wpProQuiz_overviewPageLimit"> <option>1</option> <option>4</option> <option selected="selected">50</option> <option>100</option> <option>500</option> <option>1000</option> </select> </label> </li> <li> <input type="button" value="<?php esc_html_e('Filter', 'learndash'); ?>" class="button-secondary" id="overviewFilter"> </li> </ul> </div> </div> </div> <div id="wpProQuiz_loadDataOverview" class="wpProQuiz_blueBox" style="background-color: #F8F5A8; display: none;"> <img alt="load" src="<?php echo admin_url('/images/wpspin_light.gif'); ?>" /> <?php esc_html_e('Loading', 'learndash'); ?> </div> <div id="wpProQuiz_overviewLoadContext"></div> <div style="margin-top: 10px;"> <div style="float: left;" id="overviewNavigation"> <input style="font-weight: bold;" class="button-secondary navigationLeft" value="<" type="button"> <select class="navigationCurrentPage"><option value="1">1</option></select> <input style="font-weight: bold;" class="button-secondary navigationRight" value=">" type="button"> </div> <div style="float: right;"> <a class="button-secondary wpProQuiz_update" href="#"><?php esc_html_e('Refresh', 'learndash'); ?></a> <?php if(current_user_can('wpProQuiz_reset_statistics')) { ?> <a class="button-secondary wpProQuiz_resetComplete" href="#"><?php esc_html_e('Reset entire statistic', 'learndash'); ?></a> <?php } ?> </div> <div style="clear: both;"></div> </div> </div> <?php } } lib/view/WpProQuiz_View_StatisticsAjax.php 0000666 00000072116 15214236625 0014746 0 ustar 00 <?php class WpProQuiz_View_StatisticsAjax extends WpProQuiz_View_View { public function getHistoryTable() { ob_start(); $this->showHistoryTable(); $content = ob_get_contents(); ob_end_clean(); /** * Filter to allow extending history table content * @since 2.4.2 */ return apply_filters('ld_getHistoryTable', $content, array($this) ); } public function showHistoryTable() { ?> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col"><?php esc_html_e('Username', 'learndash'); ?></th> <th scope="col" style="width: 200px;"><?php esc_html_e('Date', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Correct', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Incorrect', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Points', 'learndash'); ?></th> <th scope="col" style="width: 60px;"><?php esc_html_e('Results', 'learndash'); ?></th> </tr> </thead> <tbody id="wpProQuiz_statistics_form_data"> <?php if(!count($this->historyModel)) { ?> <tr> <td colspan="6" style="text-align: center; font-weight: bold; padding: 10px;"><?php esc_html_e('No data available', 'learndash'); ?></td> </tr> <?php } else { ?> <?php foreach($this->historyModel as $model) { /* @var $model WpProQuiz_Model_StatisticHistory */ ?> <tr> <th> <a href="#" class="user_statistic" data-ref_id="<?php echo $model->getStatisticRefId(); ?>"><?php echo $model->getUserName(); ?></a> <div class="row-actions"> <span> <a style="color: red;" class="wpProQuiz_delete" href="#"><?php esc_html_e('Delete', 'learndash'); ?></a> </span> </div> </th> <th><?php echo $model->getFormatTime(); ?></th> <th style="color: green;"><?php echo $model->getFormatCorrect(); ?></th> <th style="color: red;"><?php echo $model->getFormatIncorrect(); ?></th> <th><?php echo $model->getPoints(); ?></th> <th style="font-weight: bold;"><?php echo $model->getResult(); ?>%</th> </tr> <?php } } ?> </tbody> </table> <?php } public function getUserTable() { ob_start(); $this->showUserTable(); $content = ob_get_contents(); ob_end_clean(); return $content; } public function showUserTable() { $filepath = SFWD_LMS::get_template( 'learndash_quiz_statistics.css', null, null, true ); if ( file_exists( $filepath ) ) { ?><style type="text/css"><?php include $filepath ?></style><?php } if ( ( isset( $_POST['data']['quizId'] ) ) && ( !empty( $_POST['data']['quizId'] ) ) ) { $quizMapper = new WpProQuiz_Model_QuizMapper(); $quiz = $quizMapper->fetch( intval( $_POST['data']['quizId'] ) ); } else { return; } ?> <h2><?php printf( esc_html_x('User statistics: %s', 'placeholder: user name', 'learndash' ), $this->userName ); ?></h2> <?php if($this->avg) { ?> <h2> <?php echo date_i18n( //get_option('wpProQuiz_statisticTimeFormat', 'Y/m/d g:i A'), LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'statistics_time_format' ), $this->statisticModel->getMinCreateTime() ); ?> - <?php echo date_i18n( //get_option('wpProQuiz_statisticTimeFormat', 'Y/m/d g:i A'), LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'statistics_time_format' ), $this->statisticModel->getMaxCreateTime() ); ?> </h2> <?php } else { ?> <h2><?php echo WpProQuiz_Helper_Until::convertTime( $this->statisticModel->getCreateTime(), //get_option('wpProQuiz_statisticTimeFormat', 'Y/m/d g:i A') LearnDash_Settings_Section::get_section_setting( 'LearnDash_Settings_Quizzes_Management_Display', 'statistics_time_format' ) ); ?></h2> <?php } ?> <?php $this->formTable(); ?> <table class="wp-list-table widefat" style="margin-top: 20px;"> <thead> <tr> <th scope="col" style="width: 50px;"></th> <th scope="col"><?php esc_html_e('Question', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Points', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Correct', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Incorrect', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Hints used', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Time', 'learndash'); ?> <span style="font-size: x-small;">(hh:mm:ss)</span></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Points scored', 'learndash'); ?></th> <th scope="col" style="width: 95px;"><?php esc_html_e('Results', 'learndash'); ?></th> </tr> </thead> <tbody> <?php $gCorrect = $gIncorrect = $gHintCount = $gPoints = $gGPoints = $gTime = 0; foreach($this->userStatistic as $cat) { $cCorrect = $cIncorrect = $cHintCount = $cPoints = $cGPoints = $cTime = 0; ?> <tr class="categoryTr"> <th colspan="9"> <span><?php esc_html_e('Category', 'learndash'); ?>:</span> <span style="font-weight: bold;"><?php echo esc_html($cat['categoryName']); ?></span> </th> </tr> <?php $index = 1; foreach($cat['questions'] as $q) { $q['questionShowMsgs'] = ! $quiz->isHideAnswerMessageBox(); $q = apply_filters( 'learndash_question_statistics_data', $q, $quiz, $_POST ); if ( ( empty( $q ) ) || ( ! is_array( $q ) ) ) { continue; } $sum = $q['correct'] + $q['incorrect']; $cPoints += $q['points']; $cGPoints += $q['gPoints']; $cCorrect += $q['correct']; $cIncorrect += $q['incorrect']; $cHintCount += $q['hintCount']; $cTime += $q['time']; ?> <tr> <th><?php echo $index++ ?></th> <th> <?php if ( !$this->avg && $q['statistcAnswerData'] !== null ) { //echo strip_shortcodes(strip_tags($q['questionName'])); /** * Changed above logic which removes all shortcodes and HTML tags. This is better served as a filter. * @since 2.4 */ $q['questionName'] = apply_filters('learndash_quiz_statistics_questionName', $q['questionName'], $q, $_POST ); if ( !empty( $q['questionName'] ) ) { $q['questionName'] = do_shortcode ( $q['questionName'] ); } if ( !empty( $q['questionName'] ) ) { echo wpautop( $q['questionName'] ); } ?><a href="#" class="statistic_data"><?php esc_html_e( '(view)', 'learndash') ?></a><?php } else { //echo strip_shortcodes(strip_tags($q['questionName'])); $q['questionName'] = apply_filters('learndash_quiz_statistics_questionName', $q['questionName'], $q, $_POST ); if ( !empty( $q['questionName'] ) ) { $q['questionName'] = do_shortcode ( $q['questionName'] ); } if ( !empty( $q['questionName'] ) ) { echo wpautop( $q['questionName'] ); } ?><a href="#" class="statistic_data"><?php esc_html_e( '(view)', 'learndash') ?></a><?php } ?> </th> <th><?php echo $q['gPoints']; ?></th> <th style="color: green;"><?php echo $q['correct']; if ( $sum ) echo ' (' . round(100 * $q['correct'] / $sum, 2) . '%)'; else echo ' (' . round( $sum, 2) . '%)'; ?></th> <th style="color: red;"><?php echo $q['incorrect']; if ( $sum ) echo ' (' . round(100 * $q['incorrect'] / $sum, 2) . '%)'; else echo ' (' . round( $sum, 2) . '%)'; ?></th> <th><?php echo $q['hintCount']; ?></th> <th><?php echo WpProQuiz_Helper_Until::convertToTimeString($q['time']); ?></th> <th><?php echo $q['points']; ?></th> <th><?php if ( ( isset( $q['result'] ) ) && ( !empty( $q['result'] ) ) ) { echo $q['result']; } ?></th> </tr> <?php if(!$this->avg && $q['statistcAnswerData'] !== null) { ?> <tr style="display: none;"> <th colspan="9"> <?php $this->showUserAnswer($q['questionAnswerData'], $q['statistcAnswerData'], $q['answerType'], $q['questionId'], $quiz ); $show_messages = apply_filters( 'learndash_quiz_statistics_show_feedback_messages', $q['questionShowMsgs'], $q, $quiz, $_POST ); if ( $show_messages ) { $answerText = ''; if ( $q['correct'] == true ) { if ( !isset( $q['questionCorrectMsg'] ) ) $q['questionCorrectMsg'] = ''; //echo $q['questionCorrectMsg']; $q['questionCorrectMsg'] = apply_filters('learndash_quiz_statistics_questionCorrectMsg', $q['questionCorrectMsg'], $q, $_POST ); if ( !empty( $q['questionCorrectMsg'] ) ) { $q['questionCorrectMsg'] = do_shortcode ( $q['questionCorrectMsg'] ); } if ( !empty( $q['questionCorrectMsg'] ) ) { $answerText = wpautop( $q['questionCorrectMsg'] ); } } else if ( $q['incorrect'] == true ) { if ( !isset( $q['questionIncorrectMsg'] ) ) $q['questionIncorrectMsg'] = ''; //echo $q['questionIncorrectMsg']; $q['questionIncorrectMsg'] = apply_filters('learndash_quiz_statistics_questionIncorrectMsg', $q['questionIncorrectMsg'], $q, $_POST ); if ( !empty( $q['questionIncorrectMsg'] ) ) { $q['questionIncorrectMsg'] = do_shortcode ( $q['questionIncorrectMsg'] ); } if ( !empty( $q['questionIncorrectMsg'] ) ) { $answerText = wpautop( $q['questionIncorrectMsg'] ); } } if ( ! empty( $answerText ) ) { ?><div class="wpProQuiz_response" style=""><?php echo $answerText; ?></div><?php } } ?> </th> </tr> <?php } } $sum = $cCorrect + $cIncorrect; $result = round((100 * $cPoints / $cGPoints), 2).'%'; ?> <tr class="categoryTr" id="wpProQuiz_ctr_222"> <th colspan="2"> <span><?php esc_html_e('Sub-Total: ', 'learndash'); ?></span> </th> <th><?php echo $cGPoints; ?></th> <th style="color: green;"><?php echo $cCorrect.' ('.round(100 * $cCorrect / $sum, 2).'%)'; ?></th> <th style="color: red;"><?php echo $cIncorrect.' ('.round(100 * $cIncorrect / $sum, 2).'%)'; ?></th> <th><?php echo $cHintCount; ?></th> <th><?php echo WpProQuiz_Helper_Until::convertToTimeString($cTime); ?></th> <th><?php echo $cPoints; ?></th> <th style="font-weight: bold;"><?php echo $result; ?></th> </tr> <tr> <th colspan="9"></th> </tr> <?php $gPoints += $cPoints; $gGPoints += $cGPoints; $gCorrect += $cCorrect; $gIncorrect += $cIncorrect; $gHintCount += $cHintCount; $gTime += $cTime; } ?> </tbody> <?php $sum = $gCorrect + $gIncorrect; $result = round((100 * $gPoints / $gGPoints), 2).'%'; ?> <tfoot> <tr id="wpProQuiz_tr_0"> <th></th> <th><?php esc_html_e('Total', 'learndash'); ?></th> <th><?php echo $gGPoints; ?></th> <th style="color: green;"><?php echo $gCorrect.' ('.round(100 * $gCorrect / $sum, 2).'%)'; ?></th> <th style="color: red;"><?php echo $gIncorrect.' ('.round(100 * $gIncorrect / $sum, 2).'%)'; ?></th> <th><?php echo $gHintCount; ?></th> <th><?php echo WpProQuiz_Helper_Until::convertToTimeString($gTime); ?></th> <th><?php echo $gPoints; ?></th> <th style="font-weight: bold;"><?php echo $result; ?></th> </tr> </tfoot> </table> <div style="margin-top: 10px;"> <div style="float: left;"> <a class="button-secondary wpProQuiz_update" href="#"><?php esc_html_e('Refresh', 'learndash'); ?></a> </div> <div style="float: right;"> <?php if(current_user_can('wpProQuiz_reset_statistics')) { ?> <a class="button-secondary" href="#" id="wpProQuiz_resetUserStatistic"><?php esc_html_e('Reset statistics', 'learndash'); ?></a> <?php } ?> </div> <div style="clear: both;"></div> </div> <?php } private function showUserAnswer($qAnswerData, $sAnswerData, $anserType, $questionId, $quiz ) { $matrix = array(); if($anserType == 'matrix_sort_answer') { foreach($qAnswerData as $k => $v) { $matrix[$k][] = $k; foreach($qAnswerData as $k2 => $v2) { if($k != $k2) { if($v->getAnswer() == $v2->getAnswer()) { $matrix[$k][] = $k2; } else if($v->getSortString() == $v2->getSortString()) { $matrix[$k][] = $k2; } } } } } ?> <ul class="wpProQuiz_questionList"> <?php for($i = 0; $i < count($qAnswerData); $i++) { $answerText = $qAnswerData[$i]->isHtml() ? $qAnswerData[$i]->getAnswer() : esc_html($qAnswerData[$i]->getAnswer()); $answerText = do_shortcode( $answerText ); $correct = ''; ?> <?php if($anserType === 'single' || $anserType === 'multiple') { if ( !$quiz->isDisabledAnswerMark() ) { if($qAnswerData[$i]->isCorrect()) { $correct = 'wpProQuiz_answerCorrect'; } else if(isset($sAnswerData[$i]) && $sAnswerData[$i]) { $correct = 'wpProQuiz_answerIncorrect'; } } else { $correct = ''; } ?> <li class="<?php echo $correct; ?>"> <label> <input disabled="disabled" type="<?php echo $anserType === 'single' ? 'radio' : 'checkbox'; ?>" <?php if ( isset( $sAnswerData[$i] ) ) { echo $sAnswerData[$i] ? 'checked="checked"' : ''; } ?>> <?php echo $answerText; ?> </label> </li> <?php } else if($anserType === 'free_answer') { $t = str_replace("\r\n", "\n", strtolower($qAnswerData[$i]->getAnswer())); $t = str_replace("\r", "\n", $t); $t = explode("\n", $t); $t = array_values(array_filter(array_map('trim', $t))); if ( !$quiz->isDisabledAnswerMark() ) { if(isset($sAnswerData[0]) && in_array(strtolower(trim($sAnswerData[0])), $t)) $correct = 'wpProQuiz_answerCorrect'; else $correct = 'wpProQuiz_answerIncorrect'; } else { $correct = ''; } ?> <li class="<?php echo $correct?>"> <label> <input type="text" disabled="disabled" style="width: 300px; padding: 5px;margin-bottom: 5px;" value="<?php if ( ( isset( $sAnswerData[0] ) ) && ( ! empty( $sAnswerData[0] ) ) ) { echo esc_attr( $sAnswerData[0] ); } ?>"> </label> <br> <?php esc_html_e('Correct', 'learndash'); ?>: <?php foreach( $t as $idx => $t_ans ) { $t[ $idx ] = do_shortcode( $t_ans ); } ?> <?php echo implode(', ', $t); ?> </li> <?php } else if($anserType === 'sort_answer') { if ( !$quiz->isDisabledAnswerMark() ) { $correct = 'wpProQuiz_answerIncorrect'; } else { $correct = ''; } $sortText = ''; if(isset($sAnswerData[$i]) && isset($qAnswerData[$sAnswerData[$i]])) { if($sAnswerData[$i] == $i) { if ( !$quiz->isDisabledAnswerMark() ) { $correct = 'wpProQuiz_answerCorrect'; } else { $correct = ''; } } $v = $qAnswerData[$sAnswerData[$i]]; $sortText = $v->isHtml() ? $v->getAnswer() : esc_html($v->getAnswer()); } ?> <li class="<?php echo $correct; ?>"> <div class="wpProQuiz_sortable"> <?php echo do_shortcode( $sortText ); ?> </div> </li> <?php } else if($anserType == 'matrix_sort_answer') { if ( !$quiz->isDisabledAnswerMark() ) { $correct = 'wpProQuiz_answerIncorrect'; } else { $correct = ''; } $sortText = ''; if(isset($sAnswerData[$i]) && isset($qAnswerData[$sAnswerData[$i]])) { if(in_array($sAnswerData[$i], $matrix[$i])) { if ( !$quiz->isDisabledAnswerMark() ) { $correct = 'wpProQuiz_answerCorrect'; } else { $correct = ''; } } $v = $qAnswerData[$sAnswerData[$i]]; $sortText = $v->isSortStringHtml() ? $v->getSortString() : esc_html($v->getSortString()); } ?> <li> <table> <tbody> <tr class="wpProQuiz_mextrixTr"> <td width="20%"> <div class="wpProQuiz_maxtrixSortText"><?php echo do_shortcode( $answerText ); ?></div> </td> <td width="80%"> <ul class="wpProQuiz_maxtrixSortCriterion <?php echo $correct; ?>"> <li class="wpProQuiz_sortStringItem" data-pos="0" style="box-shadow: 0px 0px; cursor: auto;"> <?php echo do_shortcode( $sortText ); ?> </li> </ul> </td> </tr> </tbody> </table> </li> <?php } else if($anserType == 'cloze_answer') { $clozeData = $this->fetchCloze($qAnswerData[$i]->getAnswer(), $sAnswerData); $this->_clozeTemp = $clozeData['data']; $cloze = $clozeData['replace']; $cloze_answer = preg_replace_callback('#@@wpProQuizCloze@@#im', array($this, 'clozeCallback'), $cloze); $cloze_answer = do_shortcode( $cloze_answer ); echo $cloze_answer; } else if($anserType == 'assessment_answer') { $assessmentData = $this->fetchAssessment($qAnswerData[$i]->getAnswer(), $sAnswerData); $assessment = do_shortcode(apply_filters('comment_text', $assessmentData['replace'], null, null)); $assessment = preg_replace_callback('#@@wpProQuizAssessment@@#im', array($this, 'assessmentCallback'), $assessment); $assessment = apply_filters( 'learndash_quiz_question_answer_postprocess', $assessment, 'assessment' ); $assessment = do_shortcode( $assessment ); echo $assessment; } else if($anserType == 'essay') { if ( ( !isset( $sAnswerData['graded_id'] ) ) || ( empty($sAnswerData['graded_id'] ) ) ) { // Due to a bug on LD v2.4.3 the essay file user answer data was not saved. So we need to lookup // the essay post ID from the user quiz meta. $statisticRefId = $this->statisticModel->getStatisticRefId(); $quizId = $this->statisticModel->getQuizId(); $userId = $this->statisticModel->getUserId(); if ( ( !empty( $userId ) ) && ( !empty( $quizId ) ) && ( !empty( $statisticRefId ) ) ) { $user_quizzes = get_user_meta( $userId, '_sfwd-quizzes', true ); if ( !empty( $user_quizzes ) ) { foreach( $user_quizzes as $user_quiz ) { if ( ( isset( $user_quiz['pro_quizid'] ) ) && ( $user_quiz['pro_quizid'] == $quizId ) && ( isset( $user_quiz['statistic_ref_id'] ) ) && ( $user_quiz['statistic_ref_id'] == $statisticRefId ) ) { if ( isset( $user_quiz['graded'][$questionId] ) ) { if ( ( isset( $user_quiz['graded'][$questionId]['post_id'] ) ) && ( !empty( $user_quiz['graded'][$questionId]['post_id'] ) ) ) { $sAnswerData = array( 'graded_id' => $user_quiz['graded'][$questionId]['post_id'] ); // Once we have the correct post_id we update the quiz statistics for next time. global $wpdb; $update_ret = $wpdb->update( LDLMS_DB::get_table_name( 'quiz_statistic' ), array( 'answer_data' => json_encode( $sAnswerData ) ), array( 'statistic_ref_id' => $statisticRefId, 'question_id' => $questionId, ), array( '%s' ), array( '%d', '%d' ) ); break; } } } } } } } if ( ( isset( $sAnswerData['graded_id'] ) ) && ( !empty($sAnswerData['graded_id'] ) ) ) { $essay_post = get_post( $sAnswerData['graded_id'] ); if ( $essay_post instanceof WP_Post ) { ?><li class="<?php echo $correct; ?>"> <div class="wpProQuiz_sortable"> <?php if ($essay_post->post_status == 'graded') { esc_html_e('Status: Graded', 'learndash'); } else { esc_html_e('Status: Not Graded', 'learndash'); } if ( ( learndash_is_group_leader_user() ) || ( learndash_is_admin_user() ) || ( $essay_post->post_author == get_current_user_id() ) ) { ?> (<a target="_blank" href="<?php echo get_permalink( $sAnswerData['graded_id'] ); ?>"><?php esc_html_e('view', 'learndash') ?></a>)<?php } if ( current_user_can( 'edit_post', $sAnswerData['graded_id'] ) ) { ?> (<a target="_blank" href="<?php echo get_edit_post_link( $sAnswerData['graded_id'] ); ?>"><?php esc_html_e('edit', 'learndash') ?></a>)<?php } ?> </div> </li> <?php } } } ?> <?php } ?> </ul> <?php } private $_assessmetTemp = array(); private function assessmentCallback($t) { $a = array_shift($this->_assessmetTemp); return $a === null ? '' : $a; } private function fetchAssessment($answerText, $answerData) { $answerText = apply_filters( 'learndash_quiz_question_answer_preprocess', $answerText, 'assessment' ); preg_match_all('#\{(.*?)\}#im', $answerText, $matches); $this->_assessmetTemp = array(); $data = array(); for($i = 0, $ci = count($matches[1]); $i < $ci; $i++) { $match = $matches[1][$i]; preg_match_all('#\[([^\|\]]+)(?:\|(\d+))?\]#im', $match, $ms); $a = ''; $checked = isset($answerData[$i]) ? $answerData[$i]-1 : -1; for($j = 0, $cj = count($ms[1]); $j < $cj; $j++) { $v = $ms[1][$j]; $a .= '<label> <input type="radio" disabled="disabled" '.($checked == $j ? 'checked="checked"' : '').'> '.$v.' </label>'; } $this->_assessmetTemp[] = $a; } $data['replace'] = preg_replace('#\{(.*?)\}#im', '@@wpProQuizAssessment@@', $answerText); return $data; } private $_clozeTemp = array(); private function fetchCloze($answer_text, $answerData) { $answer_text = apply_filters( 'learndash_quiz_question_answer_preprocess', $answer_text, 'cloze' ); preg_match_all('#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', $answer_text, $matches, PREG_SET_ORDER); $data = array(); $index = 0; $answerData_check = $answerData; if ( apply_filters('learndash_quiz_question_cloze_answers_to_lowercase', true ) ) { if ( function_exists( 'mb_strtolower' ) ) { $answerData_check = array_map('mb_strtolower', $answerData_check ); } else { $answerData_check = array_map('strtolower', $answerData_check ); } } foreach($matches as $k => $v) { $text = $v[1]; $points = !empty($v[2]) ? (int)$v[2] : 1; $rowText = $multiTextData = array(); $len = array(); if(preg_match_all('#\[(.*?)\]#im', $text, $multiTextMatches)) { foreach($multiTextMatches[1] as $multiText) { $multiText_clean = trim( html_entity_decode( $multiText, ENT_QUOTES ) ); if ( apply_filters('learndash_quiz_question_cloze_answers_to_lowercase', true ) ) { if ( function_exists( 'mb_strtolower' ) ) $x = mb_strtolower(trim(html_entity_decode($multiText, ENT_QUOTES))); else $x = strtolower(trim(html_entity_decode($multiText, ENT_QUOTES))); } else { $x = $multiText_clean; } $len[] = strlen($x); $multiTextData[] = $x; $rowText[] = $multiText; } } else { $text_clean = trim( html_entity_decode( $text, ENT_QUOTES ) ); if ( apply_filters('learndash_quiz_question_cloze_answers_to_lowercase', true ) ) { if ( function_exists( 'mb_strtolower' ) ) $x = mb_strtolower(trim(html_entity_decode($text_clean, ENT_QUOTES))); else $x = strtolower(trim(html_entity_decode($text_clean, ENT_QUOTES))); } else { $x = $text_clean; } $len[] = strlen($x); $multiTextData[] = $x; $rowText[] = $text; } $correct = 'wpProQuiz_answerIncorrect'; if(isset($answerData_check[$index]) && in_array($answerData_check[$index], $multiTextData)) { $correct = 'wpProQuiz_answerCorrect'; } // $a = '<span class="wpProQuiz_cloze"><input data-wordlen="'.max($len).'" type="text" value=""> '; // $a .= '<span class="wpProQuiz_clozeCorrect" style="display: none;">('.implode(', ', $rowText).')</span></span>'; $a = '<span class="wpProQuiz_cloze '.$correct.'">'.esc_html(isset($answerData[$index]) ? empty($answerData[$index]) ? '---' : $answerData[$index] : '---').'</span> '; $a .= '<span>('.implode(', ', $rowText).')</span>'; $data['correct'][] = $multiTextData; $data['points'][] = $points; $data['data'][] = $a; $index++; } $data['replace'] = preg_replace('#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', '@@wpProQuizCloze@@', $answer_text); $data['replace'] = apply_filters( 'learndash_quiz_question_answer_postprocess', $data['replace'], 'cloze' ); return $data; } private function clozeCallback($t) { $a = array_shift($this->_clozeTemp); return $a === null ? '' : $a; } private function formTable() { if($this->forms === null || $this->statisticModel === null) return; $formData = $this->statisticModel->getFormData(); if($formData === null) return; ?> <div id="wpProQuiz_form_box"> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Custom fields', 'learndash'); ?></h3> <div class="inside"> <table> <tbody> <?php foreach($this->forms as $form) { /* @var $form WpProQuiz_Model_Form */ if(!isset($formData[$form->getFormId()])) continue; $str = $formData[$form->getFormId()]; ?> <tr> <td style="padding: 5px;"><?php echo esc_html($form->getFieldname()); ?></td> <td> <?php switch ($form->getType()) { case WpProQuiz_Model_Form::FORM_TYPE_TEXT: case WpProQuiz_Model_Form::FORM_TYPE_TEXTAREA: case WpProQuiz_Model_Form::FORM_TYPE_EMAIL: case WpProQuiz_Model_Form::FORM_TYPE_NUMBER: case WpProQuiz_Model_Form::FORM_TYPE_RADIO: case WpProQuiz_Model_Form::FORM_TYPE_SELECT: echo esc_html($str); break; case WpProQuiz_Model_Form::FORM_TYPE_CHECKBOX: echo $str == '1' ? esc_html__('ticked', 'learndash') : esc_html__('not ticked', 'learndash'); break; case WpProQuiz_Model_Form::FORM_TYPE_YES_NO: echo $str == 1 ? esc_html__('Yes', 'learndash') : esc_html__('No', 'learndash'); break; case WpProQuiz_Model_Form::FORM_TYPE_DATE: echo date_format(date_create($str), get_option('date_format')); break; } ?> </td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> <?php } public function getOverviewTable() { ob_start(); $this->showOverviewTable(); $content = ob_get_contents(); ob_end_clean(); return $content; } public function showOverviewTable() { ?> <table class="wp-list-table widefat"> <thead> <tr> <th scope="col"><?php esc_html_e('User', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Points', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Correct', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Incorrect', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Hints used', 'learndash'); ?></th> <th scope="col" style="width: 100px;"><?php esc_html_e('Time', 'learndash'); ?> <span style="font-size: x-small;">(hh:mm:ss)</span></th> <th scope="col" style="width: 60px;"><?php esc_html_e('Results', 'learndash'); ?></th> </tr> </thead> <tbody> <?php if(!count($this->statisticModel)) { ?> <tr> <td colspan="7" style="text-align: center; font-weight: bold; padding: 10px;"><?php esc_html_e('No data available', 'learndash'); ?></td> </tr> <?php } else { ?> <?php foreach($this->statisticModel as $model) { /** @var WpProQuiz_Model_StatisticOverview $model **/ $sum = $model->getCorrectCount() + $model->getIncorrectCount(); if(!$model->getUserId()) $model->setUserName(__('Anonymous', 'learndash')); if($sum) { $points = $model->getPoints(); $correct = $model->getCorrectCount().' ('.round(100 * $model->getCorrectCount() / $sum, 2).'%)'; $incorrect = $model->getIncorrectCount().' ('.round(100 * $model->getIncorrectCount() / $sum, 2).'%)'; $hintCount = $model->getHintCount(); $time = WpProQuiz_Helper_Until::convertToTimeString($model->getQuestionTime()); $result = round((100 * $points / $model->getGPoints()), 2).'%'; } else { $result = $time = $hintCount = $incorrect = $correct = $points = '---'; } ?> <tr> <th> <?php if($sum) { ?> <a href="#" class="user_statistic" data-user_id="<?php echo $model->getUserId(); ?>"><?php echo esc_html($model->getUserName()); ?></a> <?php } else { echo esc_html($model->getUserName()); } ?> <div <?php echo $sum ? 'class="row-actions"' : 'style="visibility: hidden;"'; ?>> <span> <a style="color: red;" class="wpProQuiz_delete" href="#"><?php esc_html_e('Delete', 'learndash'); ?></a> </span> </div> </th> <th><?php echo $points ?></th> <th style="color: green;"><?php echo $correct ?></th> <th style="color: red;"><?php echo $incorrect ?></th> <th><?php echo $hintCount ?></th> <th><?php echo $time ?></th> <th style="font-weight: bold;"><?php echo $result ?></th> </tr> <?php } } ?> </tbody> </table> <?php } } lib/view/WpProQuiz_View_StyleManager.php 0000666 00000005327 15214236625 0014403 0 ustar 00 <?php class WpProQuiz_View_StyleManager extends WpProQuiz_View_View { public function show() { ?> <div class="wrap"> <h2 style="margin-bottom: 10px;"><?php echo $this->header; ?></h2> <form method="post"> <div id="poststuff"> <div class="postbox"> <h3 class="hndle"><?php esc_html_e('Front', 'learndash'); ?></h3> <div class="wrap wpProQuiz_quizEdit"> <table class="form-table"> <tbody> <tr> <td width="50%"> </td> <td> <div style="" class="wpProQuiz_quiz"> <ol class="wpProQuiz_list"> <li class="wpProQuiz_listItem" style="display: list-item;"> <div class="wpProQuiz_question_page"> Frage <span>4</span> von <span>7</span> <span style="float:right;">1 Punkte</span> <div style="clear: right;"></div> </div> <h3><span>4</span>. Frage</h3> <div class="wpProQuiz_question" style="margin: 10px 0px 0px 0px;"> <div class="wpProQuiz_question_text"> <p>Frage3</p> </div> <ul class="wpProQuiz_questionList"> <li class="wpProQuiz_questionListItem" style=""> <label> <input class="wpProQuiz_questionInput" type="checkbox" name="question_5_26" value="2"> Test </label> </li><li class="wpProQuiz_questionListItem" style=""> <label> <input class="wpProQuiz_questionInput" type="checkbox" name="question_5_26" value="1"> Test </label> </li><li class="wpProQuiz_questionListItem" style=""> <label> <input class="wpProQuiz_questionInput" type="checkbox" name="question_5_26" value="3"> Test </label> </li></ul> </div> <div class="wpProQuiz_response" style=""> <div style="" class="wpProQuiz_correct"> <span> Korrekt </span> <p> </p> </div> </div> <div class="wpProQuiz_tipp" style="display: none;"> <h3>Tipp</h3> </div> <input type="button" name="check" value="Prüfen" class="wpProQuiz_QuestionButton" style="float: left !important; margin-right: 10px;"> <input type="button" name="back" value="Zurück" class="wpProQuiz_QuestionButton" style="float: left !important; margin-right: 10px; "> <input type="button" name="next" value="Nächste Frage" class="wpProQuiz_QuestionButton" style="float: right; "> <div style="clear: both;"></div> </li></ol> </div> </td> </tr> </tbody> </table> </div> </div> </div> </form> </div> <?php } } lib/helper/WpProQuiz_Helper_Export.php 0000666 00000006720 15214236625 0014101 0 ustar 00 <?php class WpProQuiz_Helper_Export { const WPPROQUIZ_EXPORT_VERSION = 4; public function export( $ids ) { $export = array(); $export['version'] = WPPROQUIZ_VERSION; $export['exportVersion'] = WpProQuiz_Helper_Export::WPPROQUIZ_EXPORT_VERSION; $export['ld_version'] = LEARNDASH_VERSION; $export['LEARNDASH_SETTINGS_DB_VERSION'] = LEARNDASH_SETTINGS_DB_VERSION; $export['date'] = time(); $v = str_pad( WPPROQUIZ_VERSION, 5, '0', STR_PAD_LEFT ); $v .= str_pad( WpProQuiz_Helper_Export::WPPROQUIZ_EXPORT_VERSION, 5, '0', STR_PAD_LEFT ); $code = 'WPQ' . $v; $export['master'] = $this->getQuizMaster( $ids ); foreach ($export['master'] as $master ) { $export['question'][ $master->getId() ] = $this->getQuestion( $master ); $export['forms'][ $master->getId() ] = $this->getForms( $master->getId() ); $export['post'][ $master->getId() ] = $this->getPostContent( $master ); $export['post_meta'][ $master->getId() ] = $this->getPostMeta( $master ); } return $code.base64_encode( serialize( $export ) ); } private function getQuizMaster( $ids = array() ) { $r = array(); if ( ! empty( $ids ) ) { $m = new WpProQuiz_Model_QuizMapper(); foreach ( $ids as $quiz_post_id ) { $quiz_post_id = absint( $quiz_post_id ); if ( ! empty( $quiz_post_id ) ) { $quiz_pro_id = learndash_get_setting( $quiz_post_id, 'quiz_pro' ); if ( ! empty( $quiz_pro_id ) ) { $master = $m->fetch( $quiz_pro_id ); if ( ( $master ) && ( is_a( $master, 'WpProQuiz_Model_Quiz' ) ) && ( $master->getId() > 0 ) ) { $master->setPostId( $quiz_post_id ); $r[] = $master; } } } } } return $r; } public function getQuestion( $quiz_pro ) { if ( ( ! empty( $quiz_pro ) ) && ( is_a( $quiz_pro, 'WpProQuiz_Model_Quiz' ) ) ) { $m = new WpProQuiz_Model_QuestionMapper(); return $m->fetchAll( $quiz_pro ); } } public function getPostContent( $quiz_pro ) { if ( ( ! empty( $quiz_pro ) ) && ( is_a( $quiz_pro, 'WpProQuiz_Model_Quiz' ) ) ) { $quiz_post_id = $quiz_pro->getPostId(); if ( ! empty( $quiz_post_id ) ) { $post_export_keys = array( 'post_title', 'post_content' ); $post_export_keys = apply_filters( 'learndash_quiz_export_post_keys', $post_export_keys, $quiz_post_id ); if ( ! empty( $post_export_keys ) ) { $quiz_post = get_post( $quiz_post_id, ARRAY_A ); $quiz_post_keys = array(); foreach( $post_export_keys as $export_key ) { if ( isset( $quiz_post[ $export_key ] ) ) { $quiz_post_keys[ $export_key ] = $quiz_post[ $export_key ]; } } return $quiz_post_keys; } } } } public function getPostMeta( $quiz_pro ) { if ( ( ! empty( $quiz_pro ) ) && ( is_a( $quiz_pro, 'WpProQuiz_Model_Quiz' ) ) ) { $quiz_post_id = $quiz_pro->getPostId(); if ( ! empty( $quiz_post_id ) ) { $post_meta_export_keys = array( '_' . get_post_type( $quiz_post_id ), '_viewProfileStatistics', '_timeLimitCookie' ); $post_meta_export_keys = apply_filters( 'learndash_quiz_export_post_meta_keys', $post_meta_export_keys, $quiz_post_id ); $all_post_meta = get_post_meta( $quiz_post_id ); if ( ! empty( $all_post_meta ) ) { foreach( $all_post_meta as $_key => $_data ) { if ( ! in_array( $_key, $post_meta_export_keys ) ) { unset( $all_post_meta[ $_key ] ); } } } return $all_post_meta; } } } private function getForms($quizId) { $formMapper = new WpProQuiz_Model_FormMapper(); return $formMapper->fetch($quizId); } } lib/helper/WpProQuiz_Helper_Captcha.php 0000666 00000002767 15214236625 0014172 0 ustar 00 <?php class WpProQuiz_Helper_Captcha { private static $INSTANCE = null; private $_captcha = null; private $_supp = false; private $_prefix = ''; public function __construct() { if(!class_exists('ReallySimpleCaptcha')) return; $this->_captcha = new ReallySimpleCaptcha(); $this->_captcha->tmp_dir = WPPROQUIZ_CAPTCHA_DIR.'/'; $this->_captcha->file_mode = 0666; $this->_captcha->answer_file_mode = 0666; if(!$this->_captcha->make_tmp_dir()) { $this->_supp = false; return; } $this->_supp = true; } public function getPrefix() { return $this->_prefix; } public function isSupported() { return $this->_supp; } public function createImage() { if(!$this->isSupported()) return false; $w = $this->_captcha->generate_random_word(); $this->_prefix = mt_rand(); return $this->_captcha->generate_image($this->_prefix, $w); } public function remove($prefix) { if(!$this->isSupported()) return; $this->_captcha->remove($prefix); } public function check($prefix, $answer) { if(!$this->isSupported()) return; return $this->_captcha->check($prefix, $answer); } public function cleanup() { if(!$this->isSupported()) return; $this->_captcha->cleanup(); } /** * @return WpProQuiz_Helper_Captcha */ public static function getInstance() { if(WpProQuiz_Helper_Captcha::$INSTANCE == null) { WpProQuiz_Helper_Captcha::$INSTANCE = new WpProQuiz_Helper_Captcha(); } return WpProQuiz_Helper_Captcha::$INSTANCE; } } lib/helper/WpProQuiz_Helper_ImportXml.php 0000666 00000043344 15214236625 0014556 0 ustar 00 <?php class WpProQuiz_Helper_ImportXml { private $_content = null; private $_error = false; public $import_post_id = 0; public function setImportFileUpload($file) { if(!is_uploaded_file($file['tmp_name'])) { $this->setError(__('File was not uploaded', 'learndash')); return false; } $this->_content = file_get_contents($file['tmp_name']); return $this->checkCode(); } public function setImportString($str) { $this->_content = gzuncompress(base64_decode($str)); return true; } public function setString($str) { $this->_content = $str; return $this->checkCode(); } private function checkCode() { $xml = @simplexml_load_string($this->_content); if($xml === false) { $this->_error = esc_html__('XML could not be loaded.', 'learndash'); return false; } return isset($xml->header); } public function getImportData() { $xml = @simplexml_load_string($this->_content, 'SimpleXMLElement', LIBXML_NOCDATA); $a = array('master' => array(), 'question' => array(), 'forms' => array()); $i = 0; if($xml === false) { $this->_error = esc_html__('XML could not be loaded.', 'learndash'); return false; } if(isset($xml->data) && isset($xml->data->quiz)) { foreach($xml->data->quiz as $quiz) { $quizModel = $this->createQuizModel($quiz); if($quizModel !== null) { $quizModel->setId($i++); $a['master'][] = $quizModel; if($quiz->forms->form) { foreach ($quiz->forms->form as $form) { $a['forms'][$quizModel->getId()][] = $this->createFormModel($form); } } if(isset($quiz->questions)) { foreach ($quiz->questions->question as $question) { $questionModel = $this->createQuestionModel($question); if($questionModel !== null) $a['question'][$quizModel->getId()][] = $questionModel; } } // We don't need to process the post content and post meta on the preview screen. if ( ( isset( $_POST['importSave'] ) ) && ( ! empty( $_POST['importSave'] ) ) ) { if ( isset( $quiz->post_meta ) ) { if ( ! isset( $a['post_meta'][$quizModel->getId()] ) ) { $a['post_meta'][$quizModel->getId()] = array(); } foreach ( $quiz->post_meta as $post_meta ) { $meta_key = trim( $post_meta->meta_key ); if ( ! empty( $meta_key ) ) { $meta_value = trim( $post_meta->meta_value ); //if ( ! isset( $a['post_meta'][$quizModel->getId()][ $meta_key ] ) ) { // $a['post_meta'][ $quizModel->getId() ][ $meta_key ] = array(); //} $a['post_meta'][ $quizModel->getId() ][ $meta_key ] = maybe_unserialize( $meta_value ); } } } if ( isset( $quiz->post ) ) { if ( ! isset( $a['post'][$quizModel->getId()] ) ) { $a['post'][$quizModel->getId()] = array(); } foreach ( $quiz->post as $post_items ) { foreach ( $post_items as $post_item_key => $post_item_value ) { $post_item_key = trim( $post_item_key ); $post_item_value = trim( $post_item_value ); $a['post'][$quizModel->getId()][ $post_item_key ] = $post_item_value; } } } } } } } return $a; } public function getContent() { return base64_encode(gzcompress($this->_content)); } public function saveImport( $ids ) { $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $data = $this->getImportData(); $categoryArray = $categoryMapper->getCategoryArrayForImport(); foreach ( $data['master'] as $quiz ) { if ( get_class($quiz) !== 'WpProQuiz_Model_Quiz' ) { continue; } $oldId = $quiz->getId(); if ( $ids !== false && ! in_array( $oldId, $ids ) ) { continue; } $quiz->setId (0 ); $quizMapper->save( $quiz ); $user_id = get_current_user_id(); $quiz_insert_data = array( 'post_type' => learndash_get_post_type_slug( 'quiz' ), 'post_title' => $quiz->getName(), 'post_status' => 'publish', 'post_author' => $user_id, ); if ( ( isset( $data['post'][ $oldId ] ) ) && ( ! empty( $data['post'][ $oldId ] ) ) ) { //$quiz_insert_data['post'] = $data['post'][ $oldId ]; $post_import_keys = array( 'post_title', 'post_content' ); $post_import_keys = apply_filters( 'learndash_quiz_import_post_keys', $post_import_keys ); if ( ! empty( $post_import_keys ) ) { foreach( $post_import_keys as $import_key ) { if ( isset( $data['post'][ $oldId ][ $import_key ] ) ) { $quiz_insert_data[ $import_key ] = $data['post'][ $oldId ][ $import_key ]; } } } } $quiz_insert_data = apply_filters( 'learndash_quiz_import_post_data', $quiz_insert_data, 'xml' ); $quiz_post_id = wp_insert_post( $quiz_insert_data ); if ( ! empty( $quiz_post_id ) ) { $this->import_post_id = $quiz_post_id; $post_meta_import_keys = array( '_' . get_post_type( $quiz_post_id ), '_viewProfileStatistics', '_timeLimitCookie' ); $post_meta_import_keys = apply_filters( 'learndash_quiz_import_post_meta_keys', $post_meta_import_keys ); if ( ! empty( $post_import_keys ) ) { if ( ( isset( $data['post_meta'][ $oldId ] ) ) && ( ! empty( $data['post_meta'][ $oldId ] ) ) ) { if ( ( isset( $data['post_meta'][ $oldId ] ) ) && ( ! empty( $data['post_meta'][ $oldId ] ) ) ) { foreach( $data['post_meta'][ $oldId ] as $_key => $_key_data ) { if ( ( empty( $_key ) ) || ( empty( $_key_data ) ) ) { continue; } if ( in_array( $_key, $post_meta_import_keys ) ) { foreach( $_key_data as $_data_set ) { $_data_set = maybe_unserialize( $_data_set ); add_post_meta( $quiz_post_id, $_key, $_data_set ); } } } } } } learndash_update_setting( $quiz_post_id, 'quiz_pro', $quiz->getId() ); } if( isset( $data['forms'] ) && isset( $data['forms'][ $oldId ] ) ) { $sort = 0; foreach( $data['forms'][ $oldId ] as $form ) { $form->setQuizId( $quiz->getId() ); $form->setSort( $sort++ ); } $formMapper->update( $data['forms'][ $oldId ] ); } $sort = 0; if ( ( isset( $data['question'][ $oldId ] ) ) && ( ! empty( $data['question'][ $oldId ] ) ) ) { foreach( $data['question'][ $oldId ] as $question ) { if(get_class($question) !== 'WpProQuiz_Model_Question') continue; $question->setQuizId($quiz->getId()); $question->setId(0); $question->setSort($sort++); $question->setCategoryId(0); if(trim($question->getCategoryName()) != '') { if(isset($categoryArray[strtolower($question->getCategoryName())])) { $question->setCategoryId($categoryArray[strtolower($question->getCategoryName())]); } else { $categoryModel = new WpProQuiz_Model_Category(); $categoryModel->setCategoryName($question->getCategoryName()); $categoryMapper->save($categoryModel); $question->setCategoryId($categoryModel->getCategoryId()); $categoryArray[strtolower($question->getCategoryName())] = $categoryModel->getCategoryId(); } } $question = $questionMapper->save( $question ); $question_post_array = array( 'post_type' => learndash_get_post_type_slug( 'question' ), 'post_title' => $question->getTitle(), 'post_content' => $question->getQuestion(), 'post_status' => 'publish', 'post_author' => $user_id, 'menu_order' => $sort, ); $question_post_array = wp_slash( $question_post_array ); $question_post_id = wp_insert_post( $question_post_array ); if ( ! empty( $question_post_id ) ) { update_post_meta( $question_post_id, 'points', absint( $question->getPoints() ) ); update_post_meta( $question_post_id, 'question_type', $question->getAnswerType() ); update_post_meta( $question_post_id, 'question_pro_id', absint( $question->getId() ) ); learndash_update_setting( $question_post_id, 'quiz', $quiz_post_id ); add_post_meta( $question_post_id, 'ld_quiz_id', $quiz_post_id ); } } } } return true; } public function saveImportSingle() { $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); $data = $this->getImportData(); $categoryArray = $categoryMapper->getCategoryArrayForImport(); foreach($data['master'] as $quiz) { if(get_class($quiz) !== 'WpProQuiz_Model_Quiz') continue; $oldId = $quiz->getId(); if($oldId != 0) continue; $quiz->setId(0); $quizMapper->save($quiz); if(isset($data['forms']) && isset($data['forms'][$oldId])) { $sort = 0; foreach($data['forms'][$oldId] as $form) { $form->setQuizId($quiz->getId()); $form->setSort($sort++); } $formMapper->update($data['forms'][$oldId]); } $sort = 0; foreach($data['question'][$oldId] as $question) { if(get_class($question) !== 'WpProQuiz_Model_Question') continue; $question->setQuizId($quiz->getId()); $question->setId(0); $question->setSort($sort++); $question->setCategoryId(0); if(trim($question->getCategoryName()) != '') { if(isset($categoryArray[strtolower($question->getCategoryName())])) { $question->setCategoryId($categoryArray[strtolower($question->getCategoryName())]); } else { $categoryModel = new WpProQuiz_Model_Category(); $categoryModel->setCategoryName($question->getCategoryName()); $categoryMapper->save($categoryModel); $question->setCategoryId($categoryModel->getCategoryId()); $categoryArray[strtolower($question->getCategoryName())] = $categoryModel->getCategoryId(); } } $questionMapper->save($question); } return $quiz->getId(); } return 0; } public function getError() { return $this->_error; } private function createFormModel($xml) { $form = new WpProQuiz_Model_Form(); $attr = $xml->attributes(); if($attr !== null) { $form->setType($attr->type); $form->setRequired($attr->required == 'true'); $form->setFieldname($attr->fieldname); } if(isset($xml->formData)) { $d = array(); foreach($xml->formData as $data) { $v = trim((string)$data); if($v !== '') $d[] = $v; } $form->setData($d); } return $form; } private function createQuizModel($xml) { $model = new WpProQuiz_Model_Quiz(); $quizId = $xml->attributes()->id; $model->setName(trim($xml->title)); $model->setText(trim($xml->text)); $model->setTitleHidden($xml->title->attributes()->titleHidden == 'true'); $model->setQuestionRandom($xml->questionRandom == 'true'); $model->setAnswerRandom($xml->answerRandom == 'true'); $model->setTimeLimit($xml->timeLimit); $model->setResultText($xml->resultText); $model->setResultGradeEnabled($xml->resultText); if(isset($xml->resultText)) { $attr = $xml->resultText->attributes(); if($attr !== null) { $model->setResultGradeEnabled($attr->gradeEnabled == 'true'); if($model->isResultGradeEnabled()) { $resultArray = array('text' => array(), 'prozent' => array()); foreach($xml->resultText->text as $result) { $resultArray['text'][] = trim((string)$result); $resultArray['prozent'][] = $result->attributes() === null ? 0 : (int)$result->attributes()->prozent; } $model->setResultText($resultArray); } else { $model->setResultText(trim((string) $xml->resultText)); } } } $model->setShowPoints($xml->showPoints == 'true'); $model->setBtnRestartQuizHidden($xml->btnRestartQuizHidden == 'true'); $model->setBtnViewQuestionHidden($xml->btnViewQuestionHidden == 'true'); $model->setNumberedAnswer($xml->numberedAnswer == 'true'); $model->setHideAnswerMessageBox($xml->hideAnswerMessageBox == 'true'); $model->setDisabledAnswerMark($xml->disabledAnswerMark == 'true'); if(isset($xml->statistic)) { $attr = $xml->statistic->attributes(); if($attr !== null) { $model->setStatisticsOn($attr->activated == 'true'); $model->setStatisticsIpLock($attr->ipLock); } } if(isset($xml->quizRunOnce)) { $model->setQuizRunOnce($xml->quizRunOnce == 'true'); $attr = $xml->quizRunOnce->attributes(); if($attr !== null) { $model->setQuizRunOnceCookie($attr->cookie == 'true'); $model->setQuizRunOnceType($attr->type); $model->setQuizRunOnceTime($attr->time); } } if(isset($xml->showMaxQuestion)) { $model->setShowMaxQuestion($xml->showMaxQuestion == 'true'); $attr = $xml->showMaxQuestion->attributes(); if($attr !== null) { $model->setShowMaxQuestionValue($attr->showMaxQuestionValue); $model->setShowMaxQuestionPercent($attr->showMaxQuestionPercent == 'true'); } } if(isset($xml->toplist)) { $model->setToplistActivated($xml->toplist->attributes()->activated == 'true'); $model->setToplistDataAddPermissions($xml->toplist->toplistDataAddPermissions); $model->setToplistDataSort($xml->toplist->toplistDataSort); $model->setToplistDataAddMultiple($xml->toplist->toplistDataAddMultiple == 'true'); $model->setToplistDataAddBlock($xml->toplist->toplistDataAddBlock); $model->setToplistDataShowLimit($xml->toplist->toplistDataShowLimit); $model->setToplistDataShowIn($xml->toplist->toplistDataShowIn); $model->setToplistDataCaptcha($xml->toplist->toplistDataCaptcha == 'true'); $model->setToplistDataAddAutomatic($xml->toplist->toplistDataAddAutomatic == 'true'); } $model->setShowAverageResult($xml->showAverageResult == 'true'); $model->setPrerequisite($xml->prerequisite == 'true'); $model->setQuizModus($xml->quizModus); $model->setShowReviewQuestion($xml->showReviewQuestion == 'true'); $model->setQuizSummaryHide($xml->quizSummaryHide == 'true'); $model->setSkipQuestionDisabled($xml->skipQuestionDisabled == 'true'); $model->setEmailNotification($xml->emailNotification); $model->setUserEmailNotification($xml->userEmailNotification == 'true'); $model->setShowCategoryScore($xml->showCategoryScore == 'true'); $model->setHideResultCorrectQuestion($xml->hideResultCorrectQuestion == 'true'); $model->setHideResultQuizTime($xml->hideResultQuizTime == 'true'); $model->setHideResultPoints($xml->hideResultPoints == 'true'); $model->setAutostart($xml->autostart == 'true'); $model->setForcingQuestionSolve($xml->forcingQuestionSolve == 'true'); $model->setHideQuestionPositionOverview($xml->hideQuestionPositionOverview == 'true'); $model->setHideQuestionNumbering($xml->hideQuestionNumbering == 'true'); //0.27 $model->setStartOnlyRegisteredUser($xml->startOnlyRegisteredUser == 'true'); $model->setSortCategories($xml->sortCategories == 'true'); $model->setShowCategory($xml->showCategory == 'true'); if(isset($xml->quizModus)) { $attr = $xml->quizModus->attributes(); if($attr !== null) { $model->setQuestionsPerPage($attr->questionsPerPage); } } if(isset($xml->forms)) { $attr = $xml->forms->attributes(); $model->setFormActivated($attr->activated == 'true'); $model->setFormShowPosition($attr->position); } //Check if($model->getName() == '') return null; if($model->getText() == '') return null; return $model; } /** * * @param DOMDocument $xml * @return NULL|WpProQuiz_Model_Question */ private function createQuestionModel($xml) { $model = new WpProQuiz_Model_Question(); $model->setTitle(trim($xml->title)); $model->setQuestion(trim($xml->questionText)); $model->setCorrectMsg(trim($xml->correctMsg)); $model->setIncorrectMsg(trim($xml->incorrectMsg)); $model->setAnswerType(trim($xml->attributes()->answerType)); $model->setCorrectSameText($xml->correctSameText == 'true'); $model->setTipMsg(trim($xml->tipMsg)); if(isset($xml->tipMsg) && $xml->tipMsg->attributes() !== null) $model->setTipEnabled($xml->tipMsg->attributes()->enabled == 'true'); $model->setPoints($xml->points); $model->setShowPointsInBox($xml->showPointsInBox == 'true'); $model->setAnswerPointsActivated($xml->answerPointsActivated == 'true'); $model->setAnswerPointsDiffModusActivated($xml->answerPointsDiffModusActivated == 'true'); $model->setDisableCorrect($xml->disableCorrect == 'true'); $model->setCategoryName(trim($xml->category)); $answerData = array(); if(isset($xml->answers)) { foreach($xml->answers->answer as $answer) { $answerModel = new WpProQuiz_Model_AnswerTypes(); $attr = $answer->attributes(); if($attr !== null) { $answerModel->setCorrect($attr->correct == 'true'); $answerModel->setPoints($attr->points); if ( 'essay' === $model->getAnswerType() ) { $answerModel->setGraded('1'); if ( isset( $attr->gradedType ) ) { $answerModel->setGradedType( $attr->gradedType ); } if ( isset( $attr->gradingProgression ) ) { $answerModel->setGradingProgression( $attr->gradingProgression ); } } } $answerModel->setAnswer(trim($answer->answerText)); if($answer->answerText->attributes() !== null) $answerModel->setHtml($answer->answerText->attributes()->html); $answerModel->setSortString(trim($answer->stortText)); if($answer->stortText->attributes() !== null) $answerModel->setSortStringHtml($answer->stortText->attributes()->html); $answerData[] = $answerModel; } } $model->setAnswerData($answerData); //Check if(trim($model->getAnswerType()) == '') return null; if(trim($model->getQuestion()) == '') return null; if(trim($model->getTitle()) == '') return null; if(count($model->getAnswerData()) == 0) return null; return $model; } } lib/helper/WpProQuiz_Helper_ExportXml.php 0000666 00000040702 15214236625 0014560 0 ustar 00 <?php class WpProQuiz_Helper_ExportXml { public function export( $ids ) { $dom = new DOMDocument( '1.0', 'utf-8' ); $root = $dom->createElement( 'wpProQuiz' ); $dom->appendChild( $root ); $header = $dom->createElement( 'header' ); $header->setAttribute( 'version', WPPROQUIZ_VERSION ); $header->setAttribute( 'exportVersion', 1 ); $header->setAttribute( 'ld_version', LEARNDASH_VERSION ); $header->setAttribute( 'LEARNDASH_SETTINGS_DB_VERSION', LEARNDASH_SETTINGS_DB_VERSION ); $root->appendChild( $header ); $data = $dom->createElement( 'data' ); $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); /* foreach($ids as $id) { $quizModel = $quizMapper->fetch($id); if($quizModel->getId() <= 0) continue; $questionModel = $questionMapper->fetchAll($quizModel->getId()); $forms = array(); if($quizModel->isFormActivated()) $forms = $formMapper->fetch($quizModel->getId()); $quizElement = $this->getQuizElement($dom, $quizModel, $forms); $quizElement->appendChild($questionsElement = $dom->createElement('questions')); foreach($questionModel as $model) { $questionElement = $this->createQuestionElement($dom, $model); $questionsElement->appendChild($questionElement); } $data->appendChild($quizElement); } */ foreach ( $ids as $quiz_post_id ) { $quiz_post_id = absint( $quiz_post_id ); if ( ! empty( $quiz_post_id ) ) { $quiz_pro_id = learndash_get_setting( $quiz_post_id, 'quiz_pro' ); if ( ! empty( $quiz_pro_id ) ) { $quizModel = $quizMapper->fetch( $quiz_pro_id ); if ( ( $quizModel ) && ( is_a( $quizModel, 'WpProQuiz_Model_Quiz' ) ) && ( $quizModel->getId() > 0 ) ) { $quizModel->setPostId( $quiz_post_id ); $questionModel = $questionMapper->fetchAll( $quizModel ); $forms = array(); if ( $quizModel->isFormActivated() ) { $forms = $formMapper->fetch( $quizModel->getId() ); } $quizElement = $this->getQuizElement( $dom, $quizModel, $forms ); $quizElement->appendChild( $questionsElement = $dom->createElement( 'questions' ) ); foreach( $questionModel as $model ) { $questionElement = $this->createQuestionElement( $dom, $model ); $questionsElement->appendChild( $questionElement ); } $data->appendChild( $quizElement ); $quizPostContentElement = $this->getPostContentElement( $dom, $quizModel ); $quizElement->appendChild( $quizPostContentElement ); //$quizPostMetaElement = $this->getPostMetaElement( $dom, $quizModel ); //$quizElement->appendChild( $quizPostMetaElement ); $quizElement = $this->addPostMetaElement( $dom, $quizModel, $quizElement ); } $root->appendChild( $data ); } } } return $dom->saveXML(); } private function getPostContentElement( $dom, $quizModel ) { $quizPostContentElement = $dom->createElement('post'); $quiz_post_id = $quizModel->getPostId(); if ( ! empty( $quiz_post_id ) ) { $post_export_keys = array( 'post_title', 'post_content' ); $post_export_keys = apply_filters( 'learndash_quiz_export_post_keys', $post_export_keys, $quiz_post_id ); if ( ! empty( $post_export_keys ) ) { $quiz_post = get_post( $quiz_post_id, ARRAY_A ); foreach( $post_export_keys as $export_key ) { if ( isset( $quiz_post[ $export_key ] ) ) { $post_element = $dom->createElement( $export_key ); $post_element->appendChild( $dom->createCDATASection( maybe_serialize( $quiz_post[ $export_key ] ) ) ); $quizPostContentElement->appendChild( $post_element ); } } } } return $quizPostContentElement; } private function addPostMetaElement( $dom, $quizModel, $quizElement ) { $quiz_post_id = $quizModel->getPostId( ); if ( ! empty( $quiz_post_id ) ) { $post_meta_export_keys = array( '_' . get_post_type( $quiz_post_id ), '_viewProfileStatistics', '_timeLimitCookie' ); $post_meta_export_keys = apply_filters( 'learndash_quiz_export_post_meta_keys', $post_meta_export_keys, $quiz_post_id ); $all_post_meta = get_post_meta( $quiz_post_id ); if ( ! empty( $all_post_meta ) ) { foreach( $all_post_meta as $_key => $_data ) { if ( ! in_array( $_key, $post_meta_export_keys ) ) { unset( $all_post_meta[ $_key ] ); } } } if ( ! empty( $all_post_meta ) ) { foreach( $all_post_meta as $_key => $_key_data ) { if ( ( empty( $_key ) ) || ( empty( $_key_data ) ) ) { continue; } $quizPostMetaElement = $dom->createElement('post_meta'); $post_meta_item_key = $dom->createElement( 'meta_key' ); $post_meta_item_key->appendChild( $dom->createCDATASection( $_key ) ); $quizPostMetaElement->appendChild( $post_meta_item_key ); $post_meta_item_value = $dom->createElement( 'meta_value' ); $post_meta_item_value->appendChild( $dom->createCDATASection( maybe_serialize( $_key_data ) ) ); $quizPostMetaElement->appendChild( $post_meta_item_value ); $quizElement->appendChild( $quizPostMetaElement ); } } } return $quizElement; } /** * @param DOMDocument $dom * @param WpProQuiz_Model_Quiz $quiz */ private function getQuizElement($dom, $quiz, $forms) { $quizElement = $dom->createElement('quiz'); //$quizElement->setAttribute( 'id', $quiz->getId()); $title = $dom->createElement('title'); $title->appendChild($dom->createCDATASection($quiz->getName())); $title->setAttribute('titleHidden', $this->booleanToTrueOrFalse($quiz->isTitleHidden())); $quizElement->appendChild($title); $quizElement->appendChild($text = $dom->createElement('text')); $text->appendChild($dom->createCDATASection($quiz->getText())); if(is_array($quiz->getResultText())) { $resultArray = $quiz->getResultText(); $result = $dom->createElement('resultText'); $result->setAttribute('gradeEnabled', $this->booleanToTrueOrFalse($quiz->isResultGradeEnabled())); if ( ( isset( $resultArray['text'] ) ) && ( ! empty( $resultArray['text'] ) ) ) { for($i = 0; $i < count($resultArray['text']); $i++) { $r = $dom->createElement('text'); $r->appendChild($dom->createCDATASection($resultArray['text'][$i])); $r->setAttribute('prozent', $resultArray['prozent'][$i]); $result->appendChild($r); } } $quizElement->appendChild($result); } else { $result = $dom->createElement('resultText'); $result->setAttribute('gradeEnabled', $this->booleanToTrueOrFalse($quiz->isResultGradeEnabled())); $result->appendChild($dom->createCDATASection($quiz->getResultText())); $quizElement->appendChild($result); } $quizElement->appendChild($dom->createElement('btnRestartQuizHidden', $this->booleanToTrueOrFalse($quiz->isBtnRestartQuizHidden()))); $quizElement->appendChild($dom->createElement('btnViewQuestionHidden', $this->booleanToTrueOrFalse($quiz->isBtnViewQuestionHidden()))); $quizElement->appendChild($dom->createElement('questionRandom', $this->booleanToTrueOrFalse($quiz->isQuestionRandom()))); $quizElement->appendChild($dom->createElement('answerRandom', $this->booleanToTrueOrFalse($quiz->isAnswerRandom()))); $quizElement->appendChild($dom->createElement('timeLimit', $quiz->getTimeLimit())); $quizElement->appendChild($dom->createElement('showPoints', $this->booleanToTrueOrFalse($quiz->isShowPoints()))); $statistic = $dom->createElement('statistic'); $statistic->setAttribute('activated', $this->booleanToTrueOrFalse($quiz->isStatisticsOn())); $statistic->setAttribute('ipLock', $quiz->getStatisticsIpLock()); $quizElement->appendChild($statistic); $quizElement->appendChild($quizRunOnce = $dom->createElement('quizRunOnce', $this->booleanToTrueOrFalse($quiz->isQuizRunOnce()))); $quizRunOnce->setAttribute('type', $quiz->getQuizRunOnceType()); $quizRunOnce->setAttribute('cookie', $this->booleanToTrueOrFalse($quiz->isQuizRunOnceCookie())); $quizRunOnce->setAttribute('time', $quiz->getQuizRunOnceTime()); $quizElement->appendChild($dom->createElement('numberedAnswer', $this->booleanToTrueOrFalse($quiz->isNumberedAnswer()))); $quizElement->appendChild($dom->createElement('hideAnswerMessageBox', $this->booleanToTrueOrFalse($quiz->isHideAnswerMessageBox()))); $quizElement->appendChild($dom->createElement('disabledAnswerMark', $this->booleanToTrueOrFalse($quiz->isDisabledAnswerMark()))); $quizElement->appendChild($showMaxQuestion = $dom->createElement('showMaxQuestion', $this->booleanToTrueOrFalse($quiz->isShowMaxQuestion()))); $showMaxQuestion->setAttribute('showMaxQuestionValue', $quiz->getShowMaxQuestionValue()); $showMaxQuestion->setAttribute('showMaxQuestionPercent', $this->booleanToTrueOrFalse($quiz->isShowMaxQuestionPercent())); //Toplist $toplist = $dom->createElement('toplist'); $toplist->setAttribute('activated', $this->booleanToTrueOrFalse($quiz->isToplistActivated())); $toplist->appendChild($dom->createElement('toplistDataAddPermissions', $quiz->getToplistDataAddPermissions())); $toplist->appendChild($dom->createElement('toplistDataSort', $quiz->getToplistDataSort())); $toplist->appendChild($dom->createElement('toplistDataAddMultiple', $this->booleanToTrueOrFalse($quiz->isToplistDataAddMultiple()))); $toplist->appendChild($dom->createElement('toplistDataAddBlock', $quiz->getToplistDataAddBlock())); $toplist->appendChild($dom->createElement('toplistDataShowLimit', $quiz->getToplistDataShowLimit())); $toplist->appendChild($dom->createElement('toplistDataShowIn', $quiz->getToplistDataShowIn())); $toplist->appendChild($dom->createElement('toplistDataCaptcha', $this->booleanToTrueOrFalse($quiz->isToplistDataCaptcha()))); $toplist->appendChild($dom->createElement('toplistDataAddAutomatic', $this->booleanToTrueOrFalse($quiz->isToplistDataAddAutomatic()))); $quizElement->appendChild($toplist); $quizElement->appendChild($dom->createElement('showAverageResult', $this->booleanToTrueOrFalse($quiz->isShowAverageResult()))); $quizElement->appendChild($dom->createElement('prerequisite', $this->booleanToTrueOrFalse($quiz->isPrerequisite()))); $quizElement->appendChild($dom->createElement('showReviewQuestion', $this->booleanToTrueOrFalse($quiz->isShowReviewQuestion()))); $quizElement->appendChild($dom->createElement('quizSummaryHide', $this->booleanToTrueOrFalse($quiz->isQuizSummaryHide()))); $quizElement->appendChild($dom->createElement('skipQuestionDisabled', $this->booleanToTrueOrFalse($quiz->isSkipQuestionDisabled()))); $quizElement->appendChild($dom->createElement('emailNotification', $quiz->getEmailNotification())); $quizElement->appendChild($dom->createElement('userEmailNotification', $this->booleanToTrueOrFalse($quiz->isUserEmailNotification()))); $quizElement->appendChild($dom->createElement('showCategoryScore', $this->booleanToTrueOrFalse($quiz->isShowCategoryScore()))); $quizElement->appendChild($dom->createElement('hideResultCorrectQuestion', $this->booleanToTrueOrFalse($quiz->isHideResultCorrectQuestion()))); $quizElement->appendChild($dom->createElement('hideResultQuizTime', $this->booleanToTrueOrFalse($quiz->isHideResultQuizTime()))); $quizElement->appendChild($dom->createElement('hideResultPoints', $this->booleanToTrueOrFalse($quiz->isHideResultPoints()))); $quizElement->appendChild($dom->createElement('autostart', $this->booleanToTrueOrFalse($quiz->isAutostart()))); $quizElement->appendChild($dom->createElement('forcingQuestionSolve', $this->booleanToTrueOrFalse($quiz->isForcingQuestionSolve()))); $quizElement->appendChild($dom->createElement('hideQuestionPositionOverview', $this->booleanToTrueOrFalse($quiz->isHideQuestionPositionOverview()))); $quizElement->appendChild($dom->createElement('hideQuestionNumbering', $this->booleanToTrueOrFalse($quiz->isHideQuestionNumbering()))); //0.27 $quizElement->appendChild($dom->createElement('sortCategories', $this->booleanToTrueOrFalse($quiz->isSortCategories()))); $quizElement->appendChild($dom->createElement('showCategory', $this->booleanToTrueOrFalse($quiz->isShowCategory()))); $quizModus = $dom->createElement('quizModus', $quiz->getQuizModus()); $quizModus->setAttribute('questionsPerPage', $quiz->getQuestionsPerPage()); $quizElement->appendChild($quizModus); $quizElement->appendChild($dom->createElement('startOnlyRegisteredUser', $this->booleanToTrueOrFalse($quiz->isStartOnlyRegisteredUser()))); $formsElement = $dom->createElement('forms'); $formsElement->setAttribute('activated', $this->booleanToTrueOrFalse($quiz->isFormActivated())); $formsElement->setAttribute('position', $quiz->getFormShowPosition()); foreach($forms as $form) { /** @var WpProQuiz_Model_Form $form **/ $formElement = $dom->createElement('form'); $formElement->setAttribute('type', $form->getType()); $formElement->setAttribute('required', $this->booleanToTrueOrFalse($form->isRequired())); $formElement->setAttribute('fieldname', $form->getFieldname()); if($form->getData() !== null) { $data = $form->getData(); foreach($data as $d) { $formDataElement = $dom->createElement('formData', $d); $formElement->appendChild($formDataElement); } } $formsElement->appendChild($formElement); } $quizElement->appendChild($formsElement); return $quizElement; } /** * @param DOMDocument $dom * @param WpProQuiz_Model_Question $question * @return DOMDocument */ private function createQuestionElement($dom, $question) { $qElement = $dom->createElement('question'); $qElement->setAttribute('answerType', $question->getAnswerType()); $qElement->appendChild($title = $dom->createElement('title')); $title->appendChild($dom->createCDATASection($question->getTitle())); $qElement->appendChild($dom->createElement('points', $question->getPoints())); $qElement->appendChild($questionText = $dom->createElement('questionText')); $questionText->appendChild($dom->createCDATASection($question->getQuestion())); $qElement->appendChild($correctMsg = $dom->createElement('correctMsg')); $correctMsg->appendChild($dom->createCDATASection($question->getCorrectMsg())); $qElement->appendChild($incorrectMsg = $dom->createElement('incorrectMsg')); $incorrectMsg->appendChild($dom->createCDATASection($question->getIncorrectMsg())); $qElement->appendChild($tipMsg = $dom->createElement('tipMsg')); $tipMsg->setAttribute('enabled', $this->booleanToTrueOrFalse($question->isTipEnabled())); $tipMsg->appendChild($dom->createCDATASection($question->getTipMsg())); $qElement->appendChild($dom->createElement('category', $question->getCategoryName())); $qElement->appendChild($dom->createElement('correctSameText', $this->booleanToTrueOrFalse($question->isCorrectSameText()))); $qElement->appendChild($dom->createElement('showPointsInBox', $this->booleanToTrueOrFalse($question->isShowPointsInBox()))); $qElement->appendChild($dom->createElement('answerPointsActivated', $this->booleanToTrueOrFalse($question->isAnswerPointsActivated()))); $qElement->appendChild($dom->createElement('answerPointsDiffModusActivated', $this->booleanToTrueOrFalse($question->isAnswerPointsDiffModusActivated()))); $qElement->appendChild($dom->createElement('disableCorrect', $this->booleanToTrueOrFalse($question->isDisableCorrect()))); $answersElement = $dom->createElement('answers'); $answerData = $question->getAnswerData(); if(is_array($answerData)) { foreach ($answerData as $answer) { $answerElement = $dom->createElement('answer'); $answerElement->setAttribute('points', $answer->getPoints()); $answerElement->setAttribute('correct', $this->booleanToTrueOrFalse($answer->isCorrect())); if ( 'essay' === $question->getAnswerType() ) { $answerElement->setAttribute('gradingProgression', $answer->getGradingProgression()); $answerElement->setAttribute('gradedType', $answer->getGradedType()); } $answerText = $dom->createElement('answerText'); $answerText->setAttribute('html', $this->booleanToTrueOrFalse($answer->isHtml())); $answerText->appendChild($dom->createCDATASection($answer->getAnswer())); $answerElement->appendChild($answerText); $sortText = $dom->createElement('stortText'); $sortText->setAttribute('html', $this->booleanToTrueOrFalse($answer->isSortStringHtml())); $sortText->appendChild($dom->createCDATASection($answer->getSortString())); $answerElement->appendChild($sortText); $answersElement->appendChild($answerElement); } } $qElement->appendChild($answersElement); return $qElement; } private function booleanToTrueOrFalse($v) { return $v ? 'true' : 'false'; } } lib/helper/WpProQuiz_Helper_Form.php 0000666 00000003463 15214236625 0013524 0 ustar 00 <?php class WpProQuiz_Helper_Form { /** * * @param WpProQuiz_Model_Form $form * @param mixed $data * * @return bool */ public static function valid($form, $data) { if(is_string($data)) $data = trim($data); if($form->isRequired() && (trim($data) == "")) return false; switch ($form->getType()) { case WpProQuiz_Model_Form::FORM_TYPE_TEXT: case WpProQuiz_Model_Form::FORM_TYPE_TEXTAREA: return true; case WpProQuiz_Model_Form::FORM_TYPE_CHECKBOX: return empty($data) ? true : $data == '1'; case WpProQuiz_Model_Form::FORM_TYPE_EMAIL: return empty($data) ? true : filter_var($data, FILTER_VALIDATE_EMAIL) !== false; case WpProQuiz_Model_Form::FORM_TYPE_NUMBER: return empty($data) ? true : is_numeric($data); case WpProQuiz_Model_Form::FORM_TYPE_RADIO: case WpProQuiz_Model_Form::FORM_TYPE_SELECT: return empty($data) ? true : in_array($data, $form->getData()); case WpProQuiz_Model_Form::FORM_TYPE_YES_NO: return ($data !== 0 && $data !== 1 && $data !== "0" && $data !== "1") ? true : ($data == 0 || $data == 1); case WpProQuiz_Model_Form::FORM_TYPE_DATE: return true; } } /** * * @param WpProQuiz_Model_Form $form * @param array $data */ public static function validData($form, $data) { if($form->isRequired() && empty($data)) return null; $check = 0; $format = $data['day'].'-'.$data['month'].'-'.$data['year']; if($data['day'] > 0 && $data['day'] <= 31) { $check++; } if($data['month'] > 0 && $data['month'] <= 12) { $check++; } if($data['year'] >= 1900 && $data['year'] <= date('Y')) { $check++; } if($form->isRequired()) { if($check == 3) return $format; return null; } if($check == 0) return ''; if($check == 3) return $format; return null; } } lib/helper/WpProQuiz_Helper_Import.php 0000666 00000017060 15214236625 0014071 0 ustar 00 <?php class WpProQuiz_Helper_Import { private $_content = null; private $_error = false; public $import_post_id = 0; public function setImportFileUpload($file) { if(!is_uploaded_file($file['tmp_name'])) { $this->setError(__('File was not uploaded', 'learndash')); return false; } $this->_content = file_get_contents($file['tmp_name']); return $this->checkCode(); } public function setImportString($str) { $this->_content = $str; return $this->checkCode(); } private function setError($str) { $this->_error = $str; } public function getError() { return $this->_error; } private function checkCode() { $code = substr($this->_content, 0, 13); $c = substr($code, 0, 3); $v1 = substr($code, 3, 5); $v2 = substr($code, 8, 5); if($c !== 'WPQ') { $this->setError(__('File have wrong format', 'learndash')); return false; } if($v2 < 3) { $this->setError(__('File is not compatible with the current version', 'learndash')); return false; } return true; } public function getContent() { return $this->_content; } public function getImportData() { if($this->_content === null) { $this->setError(__('File cannot be processed', 'learndash')); return false; } $data = substr($this->_content, 13); $b = base64_decode($data); if($b === null) { $this->setError(__('File cannot be processed', 'learndash')); return false; } $check = $this->saveUnserialize($b, $o); if($check === false || !is_array($o)) { $this->setError(__('File cannot be processed', 'learndash')); return false; } unset($b); return $o; } public function saveImport($ids = false) { $data = $this->getImportData(); if($data === false) { return false; } switch($data['exportVersion']) { case '3': case '4': return $this->importData($data, $ids, $data['exportVersion']); break; } return false; } private function importData($o, $ids = false, $version = '1') { global $wpdb; $quizMapper = new WpProQuiz_Model_QuizMapper(); $questionMapper = new WpProQuiz_Model_QuestionMapper(); $formMapper = new WpProQuiz_Model_FormMapper(); foreach($o['master'] as $master) { if(get_class($master) !== 'WpProQuiz_Model_Quiz') { continue; } $oldId = $master->getId(); if($ids !== false) { if(!in_array($oldId, $ids)) { continue; } } $master->setId(0); $master->setPostId(0); if($version == 3) { if($master->isQuestionOnSinglePage()) { $master->setQuizModus(WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE); } else if($master->isCheckAnswer()) { $master->setQuizModus(WpProQuiz_Model_Quiz::QUIZ_MODUS_CHECK); } else if($master->isBackButton()) { $master->setQuizModus(WpProQuiz_Model_Quiz::QUIZ_MODUS_BACK_BUTTON); } else { $master->setQuizModus(WpProQuiz_Model_Quiz::QUIZ_MODUS_NORMAL); } } $quizMapper->save( $master ); $user_id = get_current_user_id(); $quiz_insert_data = array( 'post_type' => learndash_get_post_type_slug( 'quiz' ), 'post_title' => $master->getName(), 'post_status' => 'publish', 'post_author' => $user_id, ); if ( ( isset( $o['post'][ $oldId ] ) ) && ( ! empty( $o['post'][ $oldId ] ) ) ) { $post_import_keys = array( 'post_title', 'post_content' ); $post_import_keys = apply_filters( 'learndash_quiz_import_post_keys', $post_import_keys ); if ( ! empty( $post_import_keys ) ) { foreach( $post_import_keys as $import_key ) { if ( isset( $o['post'][ $oldId ][ $import_key ] ) ) { $quiz_insert_data[ $import_key ] = $o['post'][ $oldId ][ $import_key ]; } } } } $quiz_insert_data = apply_filters( 'learndash_quiz_import_post_data', $quiz_insert_data, 'wpq' ); $quiz_post_id = wp_insert_post( $quiz_insert_data ); if ( ! empty( $quiz_post_id ) ) { $this->import_post_id = $quiz_post_id; $post_meta_import_keys = array( '_' . get_post_type( $quiz_post_id ), '_viewProfileStatistics', '_timeLimitCookie' ); $post_meta_import_keys = apply_filters( 'learndash_quiz_import_post_meta_keys', $post_meta_import_keys ); if ( ! empty( $post_import_keys ) ) { foreach( $post_import_keys as $import_key ) { if ( ( isset( $o['post_meta'][ $oldId ] ) ) && ( ! empty( $o['post_meta'][ $oldId ] ) ) ) { foreach( $o['post_meta'][ $oldId ] as $_key => $_key_data ) { if ( ( empty( $_key ) ) || ( empty( $_key_data ) ) ) { continue; } if ( in_array( $_key, $post_meta_import_keys ) ) { foreach( $_key_data as $_data_set ) { $_data_set = maybe_unserialize( $_data_set ); add_post_meta( $quiz_post_id, $_key, $_data_set ); } } } } } } learndash_update_setting( $quiz_post_id, 'quiz_pro', $master->getId() ); $master->setPostId( $quiz_post_id ); } if ( isset( $o['forms'] ) && isset( $o['forms'][$oldId] ) ) { foreach ( $o['forms'][ $oldId ] as $form ) { /** @var WpProQuiz_Model_Form $form **/ $form->setFormId( 0 ); $form->setQuizId( $master->getId() ); } $formMapper->update( $o['forms'][ $oldId ] ); } $question_idx = 0; $quiz_questions = array(); foreach ( $o['question'][ $oldId ] as $question ) { if ( get_class( $question ) !== 'WpProQuiz_Model_Question' ) { continue; } $question->setQuizId( $master->getId() ); $question->setId( 0 ); $pro_category_id = $question->getCategoryId(); $pro_category_name = $question->getCategoryName(); if ( ! empty( $pro_category_name ) ) { $categoryMapper = new WpProQuiz_Model_CategoryMapper(); $category = $categoryMapper->fetchByName( $pro_category_name ); $categoryId = $category->getCategoryId(); if ( ( ! empty( $categoryId ) ) && ( absint( $pro_category_id ) !== absint( $categoryId ) ) ) { $question->setCategoryId( $category->getCategoryId() ); $question->setCategoryName( $category->getCategoryName() ); } else { $category->setCategoryName( $question->getCategoryName() ); $category = $categoryMapper->save( $category ); $question->setCategoryId( $category->getCategoryId() ); $question->setCategoryName( $category->getCategoryName() ); } } $question_idx++; $question->setSort( $question_idx ); $question = $questionMapper->save( $question ); $question_post_array = array( 'post_type' => learndash_get_post_type_slug( 'question' ), 'post_title' => $question->getTitle(), 'post_content' => $question->getQuestion(), 'post_status' => 'publish', 'post_author' => $user_id, 'menu_order' => $question_idx, ); $question_post_array = wp_slash( $question_post_array ); $question_post_id = wp_insert_post( $question_post_array ); if ( ! empty( $question_post_id ) ) { update_post_meta( $question_post_id, 'points', absint( $question->getPoints() ) ); update_post_meta( $question_post_id, 'question_type', $question->getAnswerType() ); update_post_meta( $question_post_id, 'question_pro_id', absint( $question->getId() ) ); learndash_update_setting( $question_post_id, 'quiz', $quiz_post_id ); add_post_meta( $question_post_id, 'ld_quiz_id', $quiz_post_id ); $quiz_questions[ $question_post_id ] = absint( $question->getId() ); } } if ( ! empty( $quiz_questions ) ) { update_post_meta( $quiz_post_id, 'ld_quiz_questions', $quiz_questions ); } } return true; } private function saveUnserialize($str, &$into) { $into = @unserialize($str); return $into !== false || rtrim($str) === serialize(false); } } lib/helper/WpProQuiz_Helper_DbUpgrade.php 0000666 00000103436 15214236625 0014457 0 ustar 00 <?php class WpProQuiz_Helper_DbUpgrade { const WPPROQUIZ_DB_VERSION = 22; private $_wpdb; private $_prefix; public function __construct() { global $wpdb; $this->_wpdb = $wpdb; } public function upgrade($version) { @set_time_limit(300); if ( ( defined('LEARNDASH_ACTIVATED')) || ( $version === false ) || ( (int)$version > WpProQuiz_Helper_DbUpgrade::WPPROQUIZ_DB_VERSION ) ) { $this->install(); return WpProQuiz_Helper_DbUpgrade::WPPROQUIZ_DB_VERSION; } $version = (int) $version; if($version === WpProQuiz_Helper_DbUpgrade::WPPROQUIZ_DB_VERSION) return WpProQuiz_Helper_DbUpgrade::WPPROQUIZ_DB_VERSION; do { $f = 'upgradeDbV'.$version; if(method_exists($this, $f)) { $version = $this->$f(); } else { die("WpProQuiz upgrade error"); } } while ($version < WpProQuiz_Helper_DbUpgrade::WPPROQUIZ_DB_VERSION); return WpProQuiz_Helper_DbUpgrade::WPPROQUIZ_DB_VERSION; } public function delete() { /* $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_category' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_form' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_lock' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_prerequisite' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_statistic' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_statistic_ref' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_template' ) .'`'); $this->_wpdb->query('DROP TABLE IF EXISTS `'. LDLMS_DB::get_table_name( 'quiz_toplist' ) .'`'); */ } private function install() { $this->delete(); $this->databaseDelta(); } public function databaseDelta() { if(!function_exists('dbDelta')) require_once(ABSPATH.'wp-admin/includes/upgrade.php'); $charset_collate = ''; if ( ! empty( $wpdb->charset ) ) { $charset_collate .= "DEFAULT CHARACTER SET $wpdb->charset"; } if ( ! empty( $wpdb->collate ) ) { $charset_collate .= " COLLATE $wpdb->collate"; } dbDelta(" CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_category' ) . " ( category_id int(10) unsigned NOT NULL AUTO_INCREMENT, category_name varchar(200) NOT NULL, PRIMARY KEY (category_id) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_form' ) . " ( form_id int(11) NOT NULL AUTO_INCREMENT, quiz_id int(11) NOT NULL, fieldname varchar(100) NOT NULL, type tinyint(4) NOT NULL, required tinyint(1) unsigned NOT NULL, sort tinyint(4) NOT NULL, data mediumtext, PRIMARY KEY (form_id), KEY quiz_id (quiz_id) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_lock' ) . " ( quiz_id int(11) NOT NULL, lock_ip varchar(100) NOT NULL, user_id bigint(20) unsigned NOT NULL, lock_type tinyint(3) unsigned NOT NULL, lock_date int(11) NOT NULL, PRIMARY KEY (quiz_id,lock_ip,user_id,lock_type) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_master' ) . " ( id int(11) NOT NULL AUTO_INCREMENT, name varchar(200) NOT NULL, text text NOT NULL, result_text text NOT NULL, result_grade_enabled tinyint(1) NOT NULL, title_hidden tinyint(1) NOT NULL, btn_restart_quiz_hidden tinyint(1) NOT NULL, btn_view_question_hidden tinyint(1) NOT NULL, question_random tinyint(1) NOT NULL, answer_random tinyint(1) NOT NULL, time_limit int(11) NOT NULL, statistics_on tinyint(1) NOT NULL, statistics_ip_lock int(10) unsigned NOT NULL, show_points tinyint(1) NOT NULL, quiz_run_once tinyint(1) NOT NULL, quiz_run_once_type tinyint(4) NOT NULL, quiz_run_once_cookie tinyint(1) NOT NULL, quiz_run_once_time int(10) unsigned NOT NULL, numbered_answer tinyint(1) NOT NULL, hide_answer_message_box tinyint(1) NOT NULL, disabled_answer_mark tinyint(1) NOT NULL, show_max_question tinyint(1) NOT NULL, show_max_question_value int(10) unsigned NOT NULL, show_max_question_percent tinyint(1) NOT NULL, toplist_activated tinyint(1) NOT NULL, toplist_data text NOT NULL, show_average_result tinyint(1) NOT NULL, prerequisite tinyint(1) NOT NULL, quiz_modus tinyint(3) unsigned NOT NULL, show_review_question tinyint(1) NOT NULL, quiz_summary_hide tinyint(1) NOT NULL, skip_question_disabled tinyint(1) NOT NULL, email_notification tinyint(3) unsigned NOT NULL, user_email_notification tinyint(1) unsigned NOT NULL, show_category_score tinyint(1) unsigned NOT NULL, hide_result_correct_question tinyint(1) unsigned NOT NULL DEFAULT '0', hide_result_quiz_time tinyint(1) unsigned NOT NULL DEFAULT '0', hide_result_points tinyint(1) unsigned NOT NULL DEFAULT '0', autostart tinyint(1) unsigned NOT NULL DEFAULT '0', forcing_question_solve tinyint(1) unsigned NOT NULL DEFAULT '0', hide_question_position_overview tinyint(1) unsigned NOT NULL DEFAULT '0', hide_question_numbering tinyint(1) unsigned NOT NULL DEFAULT '0', form_activated tinyint(1) unsigned NOT NULL, form_show_position tinyint(3) unsigned NOT NULL, start_only_registered_user tinyint(1) unsigned NOT NULL, questions_per_page tinyint(3) unsigned NOT NULL, sort_categories tinyint(1) unsigned NOT NULL, show_category tinyint(1) unsigned NOT NULL, PRIMARY KEY (id) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_prerequisite' ) . " ( prerequisite_quiz_id int(11) NOT NULL, quiz_id int(11) NOT NULL, PRIMARY KEY (prerequisite_quiz_id,quiz_id) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_question' ) . " ( id int(11) NOT NULL AUTO_INCREMENT, quiz_id int(11) NOT NULL, online tinyint(1) unsigned NOT NULL, sort smallint(5) unsigned NOT NULL, title varchar(200) NOT NULL, points int(11) NOT NULL, question text NOT NULL, correct_msg text NOT NULL, incorrect_msg text NOT NULL, correct_same_text tinyint(1) NOT NULL, tip_enabled tinyint(1) NOT NULL, tip_msg text NOT NULL, answer_type varchar(50) NOT NULL, show_points_in_box tinyint(1) NOT NULL, answer_points_activated tinyint(1) NOT NULL, answer_data longtext NOT NULL, category_id int(10) unsigned NOT NULL, answer_points_diff_modus_activated tinyint(1) unsigned NOT NULL, disable_correct tinyint(1) unsigned NOT NULL, matrix_sort_answer_criteria_width tinyint(3) unsigned NOT NULL, PRIMARY KEY (id), KEY quiz_id (quiz_id), KEY category_id (category_id) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_statistic' ) . " ( statistic_ref_id int(10) unsigned NOT NULL, question_id int(11) NOT NULL, correct_count int(10) unsigned NOT NULL, incorrect_count int(10) unsigned NOT NULL, hint_count int(10) unsigned NOT NULL, points int(10) unsigned NOT NULL, question_time int(10) unsigned NOT NULL, answer_data text, PRIMARY KEY (statistic_ref_id,question_id) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_statistic_ref' ) . " ( statistic_ref_id int(10) unsigned NOT NULL AUTO_INCREMENT, quiz_id int(11) NOT NULL, user_id bigint(20) unsigned NOT NULL, create_time int(11) NOT NULL, is_old tinyint(1) unsigned NOT NULL, form_data text, PRIMARY KEY (statistic_ref_id), KEY quiz_id (quiz_id,user_id), KEY time (create_time) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_template' ) . " ( template_id int(11) NOT NULL AUTO_INCREMENT, name varchar(200) NOT NULL, type tinyint(3) unsigned NOT NULL, data text NOT NULL, PRIMARY KEY (template_id) ) " . $charset_collate . "; CREATE TABLE " . LDLMS_DB::get_table_name( 'quiz_toplist' ) . " ( toplist_id int(11) NOT NULL AUTO_INCREMENT, quiz_id int(11) NOT NULL, date int(10) unsigned NOT NULL, user_id bigint(20) unsigned NOT NULL, name varchar(30) NOT NULL, email varchar(200) NOT NULL, points int(10) unsigned NOT NULL, result float unsigned NOT NULL, ip varchar(100) NOT NULL, PRIMARY KEY (toplist_id,quiz_id) ) " . $charset_collate . "; "); } private function upgradeDbV1() { $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_master' ) . '` ADD `back_button` TINYINT( 1 ) NOT NULL AFTER `answer_random`, ADD `check_answer` TINYINT( 1 ) NOT NULL AFTER `answer_random`, ADD `result_text` TEXT NOT NULL AFTER `text` '); return 2; } private function upgradeDbV2() { return 3; } private function upgradeDbV3() { $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_question' ) . '` ADD `incorrect_count` INT UNSIGNED NOT NULL AFTER `incorrect_msg` , ADD `correct_count` INT UNSIGNED NOT NULL AFTER `incorrect_msg` , ADD `correct_same_text` TINYINT( 1 ) NOT NULL AFTER `incorrect_msg` '); $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_master' ) . '` ADD `statistics_on` TINYINT( 1 ) NOT NULL , ADD `statistics_ip_lock` INT UNSIGNED NOT NULL '); $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS `' . LDLMS_DB::get_table_name( 'quiz_lock' ) . '` ( `quiz_id` int(11) NOT NULL, `lock_ip` varchar(100) NOT NULL, `lock_date` int(11) NOT NULL, PRIMARY KEY (`quiz_id`,`lock_ip`) ) DEFAULT CHARSET=latin1; '); $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_question' ) . '` ADD INDEX ( `quiz_id` ) '); return 4; } private function upgradeDbV4() { $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_question' ) . '` ADD `tip_enabled` TINYINT( 1 ) NOT NULL AFTER `incorrect_count` , ADD `tip_msg` TEXT NOT NULL AFTER `tip_enabled` , ADD `tip_count` INT NOT NULL AFTER `tip_msg` '); return 5; } private function upgradeFixDbV4() { if($this->_wpdb->prefix != 'wp_') { $this->_wpdb->query('SELECT * FROM `' . LDLMS_DB::get_table_name( 'quiz_question' ) . '` LIMIT 0,1'); $names = $this->_wpdb->get_col_info('name'); if(!in_array('tip_enabled', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `tip_enabled` TINYINT( 1 ) NOT NULL AFTER `incorrect_count`'); } if(!in_array('tip_msg', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `tip_msg` TEXT NOT NULL AFTER `tip_enabled`'); } if(!in_array('tip_count', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `tip_count` INT NOT NULL AFTER `tip_msg`'); } } } private function upgradeDbV5() { $this->upgradeFixDbV4(); $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_master' ) . '` ADD `result_grade_enabled` TINYINT( 1 ) NOT NULL AFTER `result_text` '); return 6; } private function upgradeDbV6() { $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_question' ) . '` ADD `points` INT NOT NULL AFTER `title` '); $this->_wpdb->query(' UPDATE `'. LDLMS_DB::get_table_name( 'quiz_question' ) . '` SET `points` = 1 '); $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_master' ) . '` ADD `show_points` TINYINT( 1 ) NOT NULL '); return 7; } private function upgradeDbV7() { $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_master' ) . '` CHANGE `name` `name` VARCHAR( 200 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `text` `text` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `result_text` `result_text` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL '); $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_question' ) . '` CHANGE `title` `title` VARCHAR( 200 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `question` `question` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `correct_msg` `correct_msg` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `incorrect_msg` `incorrect_msg` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `tip_msg` `tip_msg` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `answer_type` `answer_type` VARCHAR( 50 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , CHANGE `answer_json` `answer_json` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL '); $this->_wpdb->query(' ALTER TABLE `' . LDLMS_DB::get_table_name( 'quiz_lock' ) . '` CHANGE `lock_ip` `lock_ip` VARCHAR( 100 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_lock' ) .'` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci '); return 8; } private function upgradeDbV8() { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `btn_restart_quiz_hidden` TINYINT( 1 ) NOT NULL AFTER `title_hidden` , ADD `btn_view_question_hidden` TINYINT( 1 ) NOT NULL AFTER `btn_restart_quiz_hidden` '); return 9; } private function upgradeFixDbV8() { if($this->_wpdb->prefix != 'wp_') { $this->_wpdb->query('SELECT * FROM `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` LIMIT 0,1'); $names = $this->_wpdb->get_col_info('name'); if(!in_array('btn_restart_quiz_hidden', $names)) { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `btn_restart_quiz_hidden` TINYINT( 1 ) NOT NULL AFTER `title_hidden` '); } if(!in_array('btn_view_question_hidden', $names)) { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `btn_view_question_hidden` TINYINT( 1 ) NOT NULL AFTER `btn_restart_quiz_hidden` '); } } } private function upgradeDbV9() { $this->upgradeFixDbV8(); $this->_wpdb->query(' TRUNCATE `'. LDLMS_DB::get_table_name( 'quiz_lock' ) .'` '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_lock' ) .'` ADD `user_id` BIGINT UNSIGNED NOT NULL AFTER `lock_ip` , ADD `lock_type` TINYINT UNSIGNED NOT NULL AFTER `user_id` '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_lock' ) .'` DROP PRIMARY KEY , ADD PRIMARY KEY ( `quiz_id` , `lock_ip` , `user_id` , `lock_type` ) '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `quiz_run_once` TINYINT( 1 ) NOT NULL , ADD `quiz_run_once_type` TINYINT NOT NULL , ADD `quiz_run_once_cookie` TINYINT( 1 ) NOT NULL , ADD `quiz_run_once_time` INT UNSIGNED NOT NULL '); $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS `'. LDLMS_DB::get_table_name( 'quiz_statistic' ) .'` ( `quiz_id` int(11) NOT NULL, `question_id` int(11) NOT NULL, `user_id` bigint(20) unsigned NOT NULL, `correct_count` int(10) unsigned NOT NULL, `incorrect_count` int(10) unsigned NOT NULL, `hint_count` int(10) unsigned NOT NULL, PRIMARY KEY (`quiz_id`,`question_id`,`user_id`) ) DEFAULT CHARSET=utf8; '); $this->_wpdb->query(' INSERT INTO `'. LDLMS_DB::get_table_name( 'quiz_statistic' ) .'` (quiz_id, question_id, user_id, correct_count, incorrect_count, hint_count) SELECT question.quiz_id, id, 0, question.correct_count, question.incorrect_count, tip_count FROM `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` as question WHERE question.correct_count > 0 OR question.incorrect_count > 0 OR tip_count > 0 '); return 10; } private function upgradeDbV10() { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `question_on_single_page` TINYINT( 1 ) NOT NULL , ADD `numbered_answer` TINYINT( 1 ) NOT NULL '); return 11; } private function upgradeDbV11() { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `points_per_answer` TINYINT( 1 ) NOT NULL , ADD `points_answer` INT UNSIGNED NOT NULL , ADD `show_points_in_box` TINYINT( 1 ) NOT NULL '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_statistic' ) .'` ADD `correct_answer_count` INT UNSIGNED NOT NULL '); $this->_wpdb->query('UPDATE `'. LDLMS_DB::get_table_name( 'quiz_statistic' ) .'` SET `correct_answer_count` = `correct_count`'); $this->_wpdb->query('UPDATE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` SET `points_answer` = `points`'); return 12; } private function upgradeDbV12() { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `hide_answer_message_box` TINYINT( 1 ) NOT NULL , ADD `disabled_answer_mark` TINYINT( 1 ) NOT NULL , ADD `show_max_question` TINYINT( 1 ) NOT NULL , ADD `show_max_question_value` INT UNSIGNED NOT NULL , ADD `show_max_question_percent` TINYINT( 1 ) NOT NULL '); return 13; } private function upgradeDbV13() { //WordPress SVN Bug $this->_wpdb->query('SELECT * FROM `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` LIMIT 0,1'); $names = $this->_wpdb->get_col_info('name'); if(!in_array('hide_answer_message_box', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `hide_answer_message_box` TINYINT( 1 ) NOT NULL'); } if(!in_array('disabled_answer_mark', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `disabled_answer_mark` TINYINT( 1 ) NOT NULL'); } if(!in_array('show_max_question', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `show_max_question` TINYINT( 1 ) NOT NULL'); } if(!in_array('show_max_question_value', $names)) { $this->_wpdb->query('ALTER TABLE `'.LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `show_max_question_value` INT UNSIGNED NOT NULL'); } if(!in_array('show_max_question_percent', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `show_max_question_percent` TINYINT( 1 ) NOT NULL'); } return 14; } private function upgradeDbV14() { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` CHANGE `sort` `sort` SMALLINT UNSIGNED NOT NULL '); return 15; } private function upgradeDbV15() { $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `answer_points_activated` tinyint(1) NOT NULL, ADD `answer_data` longtext NOT NULL '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_statistic' ) .'` ADD `points` int(10) unsigned NOT NULL '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `toplist_activated` tinyint(1) NOT NULL, ADD `toplist_data` text NOT NULL, ADD `show_average_result` tinyint(1) NOT NULL, ADD `prerequisite` tinyint(1) NOT NULL '); $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS `'. LDLMS_DB::get_table_name( 'quiz_prerequisite' ) .'` ( `prerequisite_quiz_id` int(11) NOT NULL, `quiz_id` int(11) NOT NULL, PRIMARY KEY (`prerequisite_quiz_id`,`quiz_id`) ) DEFAULT CHARSET=utf8; '); $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS `'. LDLMS_DB::get_table_name( 'quiz_toplist' ) .'` ( `toplist_id` int(11) NOT NULL AUTO_INCREMENT, `quiz_id` int(11) NOT NULL, `date` int(10) unsigned NOT NULL, `user_id` bigint(20) unsigned NOT NULL, `name` varchar(30) NOT NULL, `email` varchar(200) NOT NULL, `points` int(10) unsigned NOT NULL, `result` float unsigned NOT NULL, `ip` varchar(100) NOT NULL, PRIMARY KEY (`toplist_id`,`quiz_id`) ) DEFAULT CHARSET=utf8; '); $results = $this->_wpdb->get_results('SELECT id, answer_type, answer_json, points_per_answer, points_answer FROM `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'`', ARRAY_A); foreach($results as $row) { $data = json_decode($row['answer_json'], true); $newData = array(); if($data === null) { continue; } if($row['answer_type'] == 'single' || $row['answer_type'] == 'multiple') { foreach($data['classic_answer']['answer'] as $k => $v) { $x = new WpProQuiz_Model_AnswerTypes(); $x->setAnswer($v); if(isset($data['classic_answer']['correct']) && in_array($k, $data['classic_answer']['correct'])) { $x->setCorrect(true); if($row['points_per_answer']) { $x->setPoints($row['points_answer']); } } else { $x->setCorrect(false); if($row['points_per_answer']) { $x->setPoints(0); } } if(isset($data['classic_answer']['html']) && in_array($k, $data['classic_answer']['html'])) { $x->setHtml(true); } else { $x->setHtml(false); } $newData[] = $x; } } elseif($row['answer_type'] == 'cloze_answer') { $x = new WpProQuiz_Model_AnswerTypes(); $x->setAnswer($data['answer_cloze']['text']); $newData[] = $x; } elseif($row['answer_type'] == 'matrix_sort_answer') { foreach($data['answer_matrix_sort']['answer'] as $k => $v) { $x = new WpProQuiz_Model_AnswerTypes(); $x->setAnswer($v); $x->setSortString($data['answer_matrix_sort']['sort_string'][$k]); if($row['points_per_answer']) { $x->setPoints($row['points_answer']); } if(isset($data['answer_matrix_sort']['answer_html']) && in_array($k, $data['answer_matrix_sort']['answer_html'])) { $x->setHtml(true); } else { $x->setHtml(false); } if(isset($data['answer_matrix_sort']['sort_string_html']) && in_array($k, $data['answer_matrix_sort']['sort_string_html'])) { $x->setSortStringHtml(true); } else { $x->setSortStringHtml(false); } $newData[] = $x; } } elseif($row['answer_type'] == 'free_answer') { $x = new WpProQuiz_Model_AnswerTypes(); $x->setAnswer($data['free_answer']['correct']); $newData[] = $x; } elseif($row['answer_type'] == 'sort_answer') { foreach($data['answer_sort']['answer'] as $k => $v) { $x = new WpProQuiz_Model_AnswerTypes(); $x->setAnswer($v); if($row['points_per_answer']) { $x->setPoints($row['points_answer']); } if(isset($data['answer_sort']['html']) && in_array($k, $data['answer_sort']['html'])) { $x->setHtml(true); } else { $x->setHtml(false); } $newData[] = $x; } } $this->_wpdb->update( LDLMS_DB::get_table_name( 'quiz_question' ), array( 'answer_data' => serialize($newData) ), array( 'id' => $row['id'] ) ); } $this->_wpdb->query( 'UPDATE '. LDLMS_DB::get_table_name( 'quiz_question' ) .' SET answer_points_activated = points_per_answer WHERE answer_type <> \'free_answer\'' ); //Statistics $this->_wpdb->query( 'UPDATE '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' AS s SET s.points = ( SELECT q.points_answer FROM '. LDLMS_DB::get_table_name( 'quiz_question' ) .' AS q WHERE q.id = s.question_id ) * s.correct_answer_count WHERE s.correct_answer_count > 0' ); return 16; } private function upgradeDbV16() { $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_question' ) .' DROP `correct_count`, DROP `incorrect_count`, DROP `tip_count`, DROP `answer_json`, DROP `points_per_answer`, DROP `points_answer`; '); $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' DROP `correct_answer_count`; '); return 17; } private function upgradeDbV17() { $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS `'. LDLMS_DB::get_table_name( 'quiz_category' ) .'` ( `category_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `category_name` varchar(200) NOT NULL, PRIMARY KEY (`category_id`) ) DEFAULT CHARSET=utf8; '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `quiz_modus` TINYINT UNSIGNED NOT NULL , ADD `show_review_question` TINYINT( 1 ) NOT NULL , ADD `quiz_summary_hide` TINYINT( 1 ) NOT NULL , ADD `skip_question_disabled` TINYINT( 1 ) NOT NULL , ADD `email_notification` TINYINT UNSIGNED NOT NULL '); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `category_id` INT UNSIGNED NOT NULL , ADD INDEX ( `category_id` ) '); $this->_wpdb->update(LDLMS_DB::get_table_name( 'quiz_master' ), array( 'quiz_modus' => WpProQuiz_Model_Quiz::QUIZ_MODUS_SINGLE, 'back_button' => 0, 'check_answer' => 0), array('question_on_single_page' => 1)); $this->_wpdb->update( LDLMS_DB::get_table_name( 'quiz_master' ), array( 'quiz_modus' => WpProQuiz_Model_Quiz::QUIZ_MODUS_CHECK, 'back_button' => 0), array('check_answer' => 1)); $this->_wpdb->update( LDLMS_DB::get_table_name( 'quiz_master' ), array('quiz_modus' => WpProQuiz_Model_Quiz::QUIZ_MODUS_BACK_BUTTON), array('back_button' => 1)); $this->_wpdb->query(' ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` DROP `check_answer`, DROP `back_button`, DROP `question_on_single_page` '); return 18; } private function upgradeDbV18() { //Clear $this->_wpdb->query(' DELETE s FROM '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' AS s LEFT JOIN '. LDLMS_DB::get_table_name( 'quiz_master' ) .' AS m ON ( s.quiz_id = m.id ) LEFT JOIN '. LDLMS_DB::get_table_name( 'quiz_question' ) .' AS q ON ( s.question_id = q.id ) WHERE m.id IS NULL OR q.id IS NULL '); //Start - Update Statistic $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS '. LDLMS_DB::get_table_name( 'quiz_statistic_ref' ) .' ( `statistic_ref_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `quiz_id` int(11) NOT NULL, `user_id` bigint(20) unsigned NOT NULL, `create_time` int(11) NOT NULL, `is_old` tinyint(1) unsigned NOT NULL, PRIMARY KEY (`statistic_ref_id`), KEY `quiz_id` (`quiz_id`,`user_id`), KEY `time` (`create_time`) ) DEFAULT CHARSET=utf8; '); $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' ADD `statistic_ref_id` INT UNSIGNED NOT NULL FIRST '); $this->_wpdb->query(' INSERT INTO '. LDLMS_DB::get_table_name( 'quiz_statistic_ref' ) .' (quiz_id, user_id, create_time, is_old) SELECT s.quiz_id, s.user_id, '.time().' AS create_time, 1 AS is_old FROM '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' AS s GROUP BY quiz_id, user_id '); $this->_wpdb->query(' UPDATE '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' AS s LEFT JOIN '. LDLMS_DB::get_table_name( 'quiz_statistic_ref' ) .' AS sf ON s.quiz_id = sf.quiz_id AND s.user_id = sf.user_id SET s.statistic_ref_id = sf.statistic_ref_id '); $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' DROP PRIMARY KEY , ADD PRIMARY KEY ( `statistic_ref_id` , `question_id` ) , DROP `quiz_id` , DROP `user_id` , ADD `question_time` INT UNSIGNED NOT NULL '); //end //Master $this->_wpdb->query(" ALTER TABLE ". LDLMS_DB::get_table_name( 'quiz_master' ) ." ADD `user_email_notification` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0', ADD `show_category_score` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0', ADD `hide_result_correct_question` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0', ADD `hide_result_quiz_time` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0', ADD `hide_result_points` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT '0' "); $this->_wpdb->query('SELECT * FROM '. LDLMS_DB::get_table_name( 'quiz_master' ) .' LIMIT 0,1'); $names = $this->_wpdb->get_col_info('name'); if(in_array('check_answer', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` DROP `check_answer` '); } if(in_array('back_button', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` DROP `back_button` '); } if(in_array('question_on_single_page', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` DROP `question_on_single_page` '); } return 19; } private function upgradeDbV19() { $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_question' ) .' ADD `answer_points_diff_modus_activated` TINYINT( 1 ) UNSIGNED NOT NULL, ADD `disable_correct` TINYINT( 1 ) UNSIGNED NOT NULL '); $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_master' ) .' ADD `autostart` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\' , ADD `forcing_question_solve` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\', ADD `hide_question_position_overview` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\', ADD `hide_question_numbering` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\' '); return 20; } private function upgradeDbV20() { $this->_wpdb->query('SELECT * FROM '. LDLMS_DB::get_table_name( 'quiz_master' ) .' LIMIT 0,1'); $names = $this->_wpdb->get_col_info('name'); if(!in_array('autostart', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `autostart` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\' '); } if(!in_array('forcing_question_solve', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `forcing_question_solve` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\' '); } if(!in_array('hide_question_position_overview', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `hide_question_position_overview` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\' '); } if(!in_array('hide_question_numbering', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_master' ) .'` ADD `hide_question_numbering` TINYINT( 1 ) UNSIGNED NOT NULL DEFAULT \'0\' '); } $this->_wpdb->query('SELECT * FROM '. LDLMS_DB::get_table_name( 'quiz_question' ) .' LIMIT 0,1'); $names = $this->_wpdb->get_col_info('name'); if(!in_array('answer_points_diff_modus_activated', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `answer_points_diff_modus_activated` TINYINT( 1 ) UNSIGNED NOT NULL '); } if(!in_array('disable_correct', $names)) { $this->_wpdb->query('ALTER TABLE `'. LDLMS_DB::get_table_name( 'quiz_question' ) .'` ADD `disable_correct` TINYINT( 1 ) UNSIGNED NOT NULL '); } return 21; } private function upgradeDbV21() { $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_master' ).' ADD `form_activated` TINYINT( 1 ) UNSIGNED NOT NULL , ADD `form_show_position` TINYINT UNSIGNED NOT NULL , ADD `start_only_registered_user` TINYINT( 1 ) UNSIGNED NOT NULL , ADD `questions_per_page` TINYINT UNSIGNED NOT NULL , ADD `sort_categories` TINYINT( 1 ) UNSIGNED NOT NULL , ADD `show_category` TINYINT( 1 ) UNSIGNED NOT NULL '); $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_statistic' ) .' ADD `answer_data` TEXT NULL DEFAULT NULL '); $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_statistic_ref' ) .' ADD `form_data` TEXT NULL DEFAULT NULL '); $this->_wpdb->query(' ALTER TABLE '. LDLMS_DB::get_table_name( 'quiz_question' ) .' ADD `online` TINYINT( 1 ) UNSIGNED NOT NULL AFTER `quiz_id` , ADD `matrix_sort_answer_criteria_width` TINYINT( 3 ) UNSIGNED NOT NULL '); $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS `'. LDLMS_DB::get_table_name( 'quiz_form' ) .'` ( `form_id` int(11) NOT NULL AUTO_INCREMENT, `quiz_id` int(11) NOT NULL, `fieldname` varchar(100) NOT NULL, `type` tinyint(4) NOT NULL, `required` tinyint(1) unsigned NOT NULL, `sort` tinyint(4) NOT NULL, `data` mediumtext, PRIMARY KEY (`form_id`), KEY `quiz_id` (`quiz_id`) ) DEFAULT CHARSET=utf8; '); $this->_wpdb->query(' CREATE TABLE IF NOT EXISTS `'. LDLMS_DB::get_table_name( 'quiz_template' ) .'` ( `template_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(200) NOT NULL, `type` tinyint(3) unsigned NOT NULL, `data` text NOT NULL, PRIMARY KEY (`template_id`) ) DEFAULT CHARSET=utf8; '); //Check $this->databaseDelta(); $this->_wpdb->query('UPDATE '. LDLMS_DB::get_table_name( 'quiz_question' ) .' SET online = 1'); return 22; } } lib/helper/WpProQuiz_Helper_Until.php 0000666 00000006312 15214236625 0013710 0 ustar 00 <?php class WpProQuiz_Helper_Until { public static function saveUnserialize($str, &$into) { static $serializefalse; if ($serializefalse === null) $serializefalse = serialize(false); $into = @unserialize($str); return $into !== false || rtrim($str) === $serializefalse; } /* public static function saveUnserialize($str, &$into) { static $serializefalse; if ($serializefalse === null) $serializefalse = serialize(false); $into = @unserialize($str); if ( false === $into ) { $str_fixed = learndash_recount_serialized_bytes( $str ); if ( $str_fixed !== $str ) { $into = @unserialize( $str_fixed ); } } return $into !== false || rtrim($str) === $serializefalse; } */ public static function convertTime($time, $format) { $time = $time + get_option('gmt_offset') * 60 * 60; return date_i18n($format, $time); } public static function getDatePicker($format, $namePrefix) { global $wp_locale; $day = ' <select name="'.$namePrefix.'_day"><option value=""></option>'; for($i = 1; $i <= 31; $i++) { $day .= '<option value="'.$i.'">'.$i.'</option>'; } $day .= '</select> '; $monthNumber = ' <select name="'.$namePrefix.'_month"><option value=""></option>'; for($i = 1; $i <= 12; $i++) { $monthNumber .= '<option value="'.$i.'">'.$i.'</option>'; } $monthNumber .= '</select> '; $monthName = ' <select name="'.$namePrefix.'_month"><option value=""></option>'; $names = array_values($wp_locale->month); $index = 1; foreach($names as $name) { $monthName .= '<option value="'.$index++.'">'.esc_html($name).'</option>'; } $monthName .= '</select>'; $year = ' <select name="'.$namePrefix.'_year"><option value=""></option>'; for($i = 1900; $i <= date('Y'); $i++) { $year .= '<option value="'.$i.'">'.$i.'</option>'; } $year .= '</select> '; $t = str_replace(array('j', 'd', 'F', 'm', 'Y'), array('@@j@@', '@@d@@', '@@F@@', '@@m@@', '@@Y@@'), $format); return str_replace(array('@@j@@', '@@d@@', '@@F@@', '@@m@@', '@@Y@@'), array($day, $day, $monthName, $monthNumber, $year), $t); } public static function convertToTimeString($s) { $h = floor($s / 3600); $s -= $h * 3600; $m = floor($s / 60); $s -= $m * 60; return sprintf("%02d:%02d:%02d", $h, $m, $s); } public static function convertPHPDateFormatToJS($format) { $symbolsConvert = array( // day 'd' => 'dd', 'D' => 'D', 'j' => 'd', 'l' => 'DD', 'N' => '', 'S' => '', 'w' => '', 'z' => 'o', // week 'W' => '', // month 'F' => 'MM', 'm' => 'mm', 'M' => 'M', 'n' => 'm', 't' => '', // year 'L' => '', 'o' => '', 'Y' => 'yy', 'y' => 'y', // time 'a' => '', 'A' => '', 'B' => '', 'g' => '', 'G' => '', 'h' => '', 'H' => '', 'i' => '', 's' => '', 'u' => '' ); $jsFormat = ''; $esc = false; for($i = 0, $len = strlen($format); $i < $len; $i++) { $c = $format[ $i ]; //escaping if($c === '\\') { $i++; $c = $format[ $c ]; $jsFormat .= $esc ? $c : '\''.$c; $esc = true; } else { if($esc) { $jsFormat .= "'"; $esc = false; } $jsFormat .= isset($symbolsConvert[$c]) ? $symbolsConvert[$c] : $c; } } return $jsFormat; } } lib/helper/WpProQuiz_Helper_Upgrade.php 0000666 00000007510 15214236625 0014205 0 ustar 00 <?php class WpProQuiz_Helper_Upgrade { public static function upgrade() { WpProQuiz_Helper_Upgrade::updateDb(); $oldVersion = get_option('wpProQuiz_version'); if($oldVersion == '0.20') { WpProQuiz_Helper_Upgrade::updateV21(); } switch($oldVersion) { case '0.17': case '0.18': WpProQuiz_Helper_Upgrade::updateV19(); case '0.19': WpProQuiz_Helper_Upgrade::updateV20(); case '0.20': case '0.21': case '0.22': case '0.23': case '0.24': case '0.25': case '0.26': case '0.27': break; default: WpProQuiz_Helper_Upgrade::install(); break; } if(add_option('wpProQuiz_version', WPPROQUIZ_VERSION) === false) { update_option('wpProQuiz_version', WPPROQUIZ_VERSION); } } private static function install() { $role = get_role('administrator'); if ( ( $role ) && ( $role instanceof WP_Role ) ) { $role->add_cap('wpProQuiz_show'); $role->add_cap('wpProQuiz_add_quiz'); $role->add_cap('wpProQuiz_edit_quiz'); $role->add_cap('wpProQuiz_delete_quiz'); $role->add_cap('wpProQuiz_show_statistics'); $role->add_cap('wpProQuiz_reset_statistics'); $role->add_cap('wpProQuiz_import'); $role->add_cap('wpProQuiz_export'); $role->add_cap('wpProQuiz_change_settings'); $role->add_cap('wpProQuiz_toplist_edit'); } //ACHIEVEMENTS Version 2.x.x if(defined('ACHIEVEMENTS_IS_INSTALLED') && ACHIEVEMENTS_IS_INSTALLED === 1 && defined('ACHIEVEMENTS_VERSION')) { $version = ACHIEVEMENTS_VERSION; if($version[0] == '2') { WpProQuiz_Plugin_BpAchievementsV2::install(); } } } private static function updateV19() { $role = get_role('administrator'); if ( ( $role ) && ( $role instanceof WP_Role ) ) { $role->add_cap('wpProQuiz_toplist_edit'); } } private static function updateDb() { $db = new WpProQuiz_Helper_DbUpgrade(); $v = $db->upgrade(get_option('wpProQuiz_dbVersion', false)); if(add_option('wpProQuiz_dbVersion', $v) === false) update_option('wpProQuiz_dbVersion', $v); } private static function updateV20() { global $wpdb; $results = $wpdb->get_results(" SELECT id, answer_data FROM ". LDLMS_DB::get_table_name( 'quiz_question' ) ." WHERE answer_type = 'cloze_answer' AND answer_points_activated = 1", ARRAY_A); foreach($results as $row) { if(WpProQuiz_Helper_Until::saveUnserialize($row['answer_data'], $into)) { $points = 0; foreach($into as $c) { preg_match_all('#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', $c->getAnswer(), $matches); foreach($matches[2] as $match) { if(empty($match)) $match = 1; $points += $match; } } $wpdb->update( LDLMS_DB::get_table_name( 'quiz_question' ), array('points' => $points), array('id' => $row['id'])); } } } private static function updateV21() { global $wpdb; $results = $wpdb->get_results(" SELECT id, answer_data, answer_type, answer_points_activated, points FROM ". LDLMS_DB::get_table_name( 'quiz_question' ), ARRAY_A); foreach($results as $row) { if($row['points']) continue; if(WpProQuiz_Helper_Until::saveUnserialize($row['answer_data'], $into)) { $points = 0; if($row['answer_points_activated']) { $dPoints = 0; foreach($into as $c) { if($row['answer_type'] == 'cloze_answer') { preg_match_all('#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', $c->getAnswer(), $matches); foreach($matches[2] as $match) { if(empty($match)) $match = 1; $dPoints += $match; } } else { $dPoints += $c->getPoints(); } } $points = $dPoints; } else { $points = 1; } $wpdb->update( LDLMS_DB::get_table_name( 'quiz_question' ), array('points' => $points), array('id' => $row['id'])); } } } public static function deinstall() { } } uninstall.php 0000666 00000001067 15214236625 0007304 0 ustar 00 <?php if(!defined('WP_UNINSTALL_PLUGIN')) exit(); include_once __DIR__ . '/lib/helper/WpProQuiz_Helper_DbUpgrade.php'; $db = new WpProQuiz_Helper_DbUpgrade(); $db->delete(); delete_option('wpProQuiz_dbVersion'); delete_option('wpProQuiz_version'); delete_option('wpProQuiz_addRawShortcode'); delete_option('wpProQuiz_jsLoadInHead'); delete_option('wpProQuiz_touchLibraryDeactivate'); delete_option('wpProQuiz_corsActivated'); delete_option('wpProQuiz_toplistDataFormat'); delete_option('wpProQuiz_emailSettings'); delete_option('wpProQuiz_statisticTimeFormat'); js/wpProQuiz_toplist.js 0000666 00000002703 15214236625 0011270 0 ustar 00 function wpProQuiz_fetchToplist() { var plugin = this; plugin.toplist = { handleRequest: function(json) { jQuery('.wpProQuiz_toplist').each(function() { var $tp = jQuery(this); var data = json[$tp.data('quiz_id')]; var $trs = $tp.find('tbody tr'); var clone = $trs.eq(2); $trs.slice(3).remove(); if(data == undefined) { $trs.eq(0).hide().end().eq(1).show(); return true; } for(var i = 0, c = data.length; i < c; i++) { var td = clone.clone().children(); td.eq(0).text(i+1); td.eq(1).text(data[i].name); td.eq(2).text(data[i].date); td.eq(3).text(data[i].points); td.eq(4).text(data[i].result + ' %'); if(i & 1) { td.addClass('wpProQuiz_toplistTrOdd'); } td.parent().show().appendTo($tp.find('tbody')); } $trs.eq(0).hide(); $trs.eq(1).hide(); }); }, fetchIds: function() { var ids = new Array(); jQuery('.wpProQuiz_toplist').each(function() { ids.push(jQuery(this).data('quiz_id')); }); return ids; }, init: function() { var quizIds = plugin.toplist.fetchIds(); if(quizIds.length == 0) return; jQuery.post(WpProQuizGlobal.ajaxurl, { action: 'wp_pro_quiz_show_front_toplist', quizIds: quizIds }, function(json) { plugin.toplist.handleRequest(json); }, 'json'); } }; plugin.toplist.init(); } jQuery(document).ready(wpProQuiz_fetchToplist); js/wpProQuiz_toplist.min.js 0000666 00000001704 15214236625 0012052 0 ustar 00 function wpProQuiz_fetchToplist(){var t=this;t.toplist={handleRequest:function(t){jQuery(".wpProQuiz_toplist").each(function(){var e=jQuery(this),i=t[e.data("quiz_id")],o=e.find("tbody tr"),n=o.eq(2);if(o.slice(3).remove(),null==i)return o.eq(0).hide().end().eq(1).show(),!0;for(var r=0,u=i.length;r<u;r++){var s=n.clone().children();s.eq(0).text(r+1),s.eq(1).text(i[r].name),s.eq(2).text(i[r].date),s.eq(3).text(i[r].points),s.eq(4).text(i[r].result+" %"),1&r&&s.addClass("wpProQuiz_toplistTrOdd"),s.parent().show().appendTo(e.find("tbody"))}o.eq(0).hide(),o.eq(1).hide()})},fetchIds:function(){var t=new Array;return jQuery(".wpProQuiz_toplist").each(function(){t.push(jQuery(this).data("quiz_id"))}),t},init:function(){var e=t.toplist.fetchIds();0!=e.length&&jQuery.post(WpProQuizGlobal.ajaxurl,{action:"wp_pro_quiz_show_front_toplist",quizIds:e},function(e){t.toplist.handleRequest(e)},"json")}},t.toplist.init()}jQuery(document).ready(wpProQuiz_fetchToplist); js/jquery.ui.touch-punch.min.js 0000666 00000002246 15214236625 0012505 0 ustar 00 /* * jQuery UI Touch Punch 0.2.2 * * Copyright 2011, Dave Furfero * Dual licensed under the MIT or GPL Version 2 licenses. * * Depends: * jquery.ui.widget.js * jquery.ui.mouse.js */ (function(b){b.support.touch="ontouchend" in document;if(!b.support.touch){return;}var c=b.ui.mouse.prototype,e=c._mouseInit,a;function d(g,h){if(g.originalEvent.touches.length>1){return;}g.preventDefault();var i=g.originalEvent.changedTouches[0],f=document.createEvent("MouseEvents");f.initMouseEvent(h,true,true,window,1,i.screenX,i.screenY,i.clientX,i.clientY,false,false,false,false,0,null);g.target.dispatchEvent(f);}c._touchStart=function(g){var f=this;if(a||!f._mouseCapture(g.originalEvent.changedTouches[0])){return;}a=true;f._touchMoved=false;d(g,"mouseover");d(g,"mousemove");d(g,"mousedown");};c._touchMove=function(f){if(!a){return;}this._touchMoved=true;d(f,"mousemove");};c._touchEnd=function(f){if(!a){return;}d(f,"mouseup");d(f,"mouseout");if(!this._touchMoved){d(f,"click");}a=false;};c._mouseInit=function(){var f=this;f.element.bind("touchstart",b.proxy(f,"_touchStart")).bind("touchmove",b.proxy(f,"_touchMove")).bind("touchend",b.proxy(f,"_touchEnd"));e.call(f);};})(jQuery); js/wpProQuiz_front.js 0000666 00000250667 15214236625 0010740 0 ustar 00 (function($) { /** * @memberOf $ */ $.wpProQuizFront = function(element, options) { var $e = $(element); var config = options; var result_settings = {}; var plugin = this; var results = new Object(); var catResults = new Object(); var startTime = 0; var currentQuestion = null; var quizSolved = []; var lastButtonValue = ""; var inViewQuestions = false; var currentPage = 1; var timespent = 0; var sending_timer = null; var cookie_name = ''; var cookie_value = ''; var bitOptions = { randomAnswer: 0, randomQuestion: 0, disabledAnswerMark: 0, checkBeforeStart: 0, preview: 0, cors: 0, isAddAutomatic: 0, quizSummeryHide: 0, skipButton: 0, reviewQustion: 0, autoStart: 0, forcingQuestionSolve: 0, hideQuestionPositionOverview: 0, formActivated: 0, maxShowQuestion: 0, sortCategories: 0 }; var quizStatus = { isQuizStart: 0, isLocked: 0, loadLock: 0, isPrerequisite: 0, isUserStartLocked: 0 }; /* var QuizRepeats = { quizRepeats: 0, userAttemptsTaken: 0, userAttemptsLeft: 0, }; */ var globalNames = { check: 'input[name="check"]', next: 'input[name="next"]', questionList: '.wpProQuiz_questionList', skip: 'input[name="skip"]', singlePageLeft: 'input[name="wpProQuiz_pageLeft"]', singlePageRight: 'input[name="wpProQuiz_pageRight"]' }; var globalElements = { back: $e.find('input[name="back"]'), next: $e.find(globalNames.next), quiz: $e.find('.wpProQuiz_quiz'), questionList: $e.find('.wpProQuiz_list'), results: $e.find('.wpProQuiz_results'), sending: $e.find('.wpProQuiz_sending'), quizStartPage: $e.find('.wpProQuiz_text'), timelimit: $e.find('.wpProQuiz_time_limit'), toplistShowInButton: $e.find('.wpProQuiz_toplistShowInButton'), listItems: $() }; var toplistData = { token: '', isUser: 0 }; var formPosConst = { START: 0, END: 1 }; /** * @memberOf timelimit */ var timelimit = (function() { var _counter = config.timelimit; var _intervalId = 0; var instance = {}; // set cookie for different users and different quizzes var timer_cookie = 'ldadv-time-limit-' + config.user_id + '-' + config.quizId; instance.stop = function() { if(_counter) { $.removeCookie(timer_cookie); window.clearInterval(_intervalId); globalElements.timelimit.hide(); } }; instance.start = function() { if(!_counter) return; $.cookie.raw = true; var full = _counter * 1000; var tick = $.cookie(timer_cookie); var limit = tick ? tick : _counter; var x = limit * 1000; var $timeText = globalElements.timelimit.find('span').text(plugin.methode.parseTime(limit)); var $timeDiv = globalElements.timelimit.find('.wpProQuiz_progress'); globalElements.timelimit.show(); var beforeTime = +new Date(); _intervalId = window.setInterval(function() { var diff = (+new Date() - beforeTime); var remainingTime = x - diff; if(diff >= 500) { tick = remainingTime / 1000; $timeText.text(plugin.methode.parseTime(Math.ceil(tick))); $.cookie(timer_cookie, tick); } $timeDiv.css('width', (remainingTime / full * 100) + '%'); if(remainingTime <= 0) { instance.stop(); plugin.methode.finishQuiz(true); } }, 16); }; return instance; })(); /** * @memberOf reviewBox */ var reviewBox = new function() { var $contain = [], $cursor = [], $list = [], $items = []; var x = 0, offset = 0, diff = 0, top = 0, max = 0; var itemsStatus = []; this.init = function() { $contain = $e.find('.wpProQuiz_reviewQuestion'); $cursor = $contain.find('div'); $list = $contain.find('ol'); $items = $list.children(); $cursor.mousedown(function(e) { e.preventDefault(); e.stopPropagation(); offset = e.pageY - $cursor.offset().top + top; $(document).bind('mouseup.scrollEvent', endScroll); $(document).bind('mousemove.scrollEvent', moveScroll); }); $items.click(function(e) { plugin.methode.showQuestion($(this).index()); }); $e.bind('questionSolved', function(e) { itemsStatus[e.values.index].solved = e.values.solved; setColor(e.values.index); }); $e.bind('changeQuestion', function(e) { // On Matrix sort questions we need to set the sort capture UL to full height. if (e.values.item[0] != 'undefined') { var questionItem = e.values.item[0]; plugin.methode.setupMatrixSortHeights(); } $items.removeClass('wpProQuiz_reviewQuestionTarget'); //$items.removeClass('wpProQuiz_reviewQuestionSolved'); //$items.removeClass('wpProQuiz_reviewQuestionReview'); $items.eq(e.values.index).addClass('wpProQuiz_reviewQuestionTarget'); scroll(e.values.index); }); $e.bind('reviewQuestion', function(e) { //console.log('reviewQuestion: e.values.index[%o]', e.values.index); itemsStatus[e.values.index].review = !itemsStatus[e.values.index].review; setColor(e.values.index); }); /* $contain.bind('mousewheel DOMMouseScroll', function(e) { e.preventDefault(); var ev = e.originalEvent; var w = ev.wheelDelta ? -ev.wheelDelta / 120 : ev.detail / 3; var plus = 20 * w; var x = top - $list.offset().top + plus; if(x > max) x = max; if(x < 0) x = 0; var o = x / diff; $list.attr('style', 'margin-top: ' + (-x) + 'px !important'); $cursor.css({top: o}); return false; }); */ }; this.show = function(save) { if(bitOptions.reviewQustion) $contain.parent().show(); $e.find('.wpProQuiz_reviewDiv .wpProQuiz_button2').show(); if(save) return; $list.attr('style', 'margin-top: 0px !important'); $cursor.css({top: 0}); var h = $list.outerHeight(); var c = $contain.height(); x = c - $cursor.height(); offset = 0; max = h-c; diff = max / x; this.reset(); if(h > 100) { $cursor.show(); } top = $cursor.offset().top; }; this.hide = function() { $contain.parent().hide(); }; this.toggle = function() { if(bitOptions.reviewQustion) { $contain.parent().toggle(); $items.removeClass('wpProQuiz_reviewQuestionTarget'); $e.find('.wpProQuiz_reviewDiv .wpProQuiz_button2').hide(); $list.attr('style', 'margin-top: 0px !important'); $cursor.css({top: 0}); var h = $list.outerHeight(); var c = $contain.height(); x = c - $cursor.height(); offset = 0; max = h-c; diff = max / x; if(h > 100) { $cursor.show(); } top = $cursor.offset().top; } }; this.reset = function() { for(var i = 0, c = $items.length; i < c; i++) { itemsStatus[i] = {}; } //$items.removeClass('wpProQuiz_reviewQuestionTarget').css('background-color', ''); $items.removeClass('wpProQuiz_reviewQuestionTarget'); $items.removeClass('wpProQuiz_reviewQuestionSolved') $items.removeClass('wpProQuiz_reviewQuestionReview') }; function scroll(index) { /* var $item = $items.eq(index); var iTop = $item.offset().top; var cTop = $contain.offset().top; var calc = iTop - cTop; if((calc - 4) < 0 || (calc + 32) > 100) { var x = cTop - $items.eq(0).offset().top - (cTop - $list.offset().top) + $item.position().top; if(x > max) x = max; var o = x / diff; $list.attr('style', 'margin-top: ' + (-x) + 'px !important'); $cursor.css({top: o}); } */ } function setColor(index) { var css_class = ''; var itemStatus = itemsStatus[index]; if(itemStatus.solved) { css_class = "wpProQuiz_reviewQuestionSolved"; } else if (itemStatus.review) { css_class = "wpProQuiz_reviewQuestionReview"; } $items.eq(index).removeClass( 'wpProQuiz_reviewQuestionSolved' ); $items.eq(index).removeClass( 'wpProQuiz_reviewQuestionReview' ); if ( css_class != '' ) { $items.eq(index).addClass( css_class ); } } function moveScroll(e) { e.preventDefault(); var o = e.pageY - offset; if(o < 0) o = 0; if(o > x) o = x; var v = diff * o; $list.attr('style', 'margin-top: ' + (-v) + 'px !important'); $cursor.css({top: o}); } function endScroll(e) { e.preventDefault(); $(document).unbind('.scrollEvent'); } }; function QuestionTimer() { var questionStartTime = 0; var currentQuestionId = -1; var quizStartTimer = 0; var isQuizStart = false; this.questionStart = function(questionId) { if(currentQuestionId != -1) this.questionStop(); currentQuestionId = questionId; questionStartTime = +new Date(); }; this.questionStop = function() { if(currentQuestionId == -1) return; results[currentQuestionId].time += Math.round((new Date() - questionStartTime) / 1000); currentQuestionId = -1; }; this.startQuiz = function() { if(isQuizStart) this.stopQuiz(); quizStartTimer = +new Date(); isQuizStart = true; }; this.stopQuiz = function() { if(!isQuizStart) return; quizEndTimer = +new Date(); results['comp'].quizTime += Math.round((quizEndTimer - quizStartTimer) / 1000); results['comp'].quizEndTimestamp = quizEndTimer; results['comp'].quizStartTimestamp = quizStartTimer; isQuizStart = false; }; this.init = function() { }; }; var questionTimer = new QuestionTimer(); var readResponses = function(name, data, $question, $questionList, lockResponse) { //if (config.ld_script_debug == true) { // console.log('readResponses: name[%o], data[%o], $question[%o], $questionList[%o], lockResponse[%o]', name, data, $question, $questionList, lockResponse); //} if (lockResponse == undefined) lockResponse = true; var response = {}; var func = { singleMulti: function() { var input = $questionList.find('.wpProQuiz_questionInput'); if (lockResponse == true) { $questionList.find('.wpProQuiz_questionInput').attr('disabled', 'disabled'); } //$questionList.children().each(function(i) { // Changed in v2.3 from the above. children() was pickup up some other random HTML elements within the UL like <p></p>. // Now we are targetting specifically the .wpProQuiz_questionListItem HTML elements. jQuery('.wpProQuiz_questionListItem', $questionList).each(function(i) { var $item = $(this); var index = $item.attr('data-pos'); if ( typeof index !== 'undefined' ) { response[index] = input.eq(i).is(':checked'); } }); }, sort_answer: function() { var $items = $questionList.children(); $items.each(function(i, v) { var $this = $(this); response[i] = $this.attr('data-pos'); }); if (lockResponse == true) { $questionList.sortable("destroy"); } }, matrix_sort_answer: function() { var $items = $questionList.children(); var matrix = new Array(); statistcAnswerData = {0:-1}; $items.each(function() { var $this = $(this); var id = $this.attr('data-pos'); var $stringUl = $this.find('.wpProQuiz_maxtrixSortCriterion'); var $stringItem = $stringUl.children(); if($stringItem.length) statistcAnswerData[$stringItem.attr('data-pos')] = id; response = statistcAnswerData; }); if (lockResponse == true) { $question.find('.wpProQuiz_sortStringList, .wpProQuiz_maxtrixSortCriterion').sortable("destroy"); } }, free_answer: function() { var $li = $questionList.children(); var value = $li.find('.wpProQuiz_questionInput').val(); if (lockResponse == true) { $li.find('.wpProQuiz_questionInput').attr('disabled', 'disabled'); } response = value; }, cloze_answer: function() { response = {}; $questionList.find('.wpProQuiz_cloze').each(function(i, v) { var $this = $(this); var cloze = $this.children(); var input = cloze.eq(0); var span = cloze.eq(1); var inputText = plugin.methode.cleanupCurlyQuotes(input.val()); response[i] = inputText; if (lockResponse == true) { input.attr('disabled', 'disabled'); } }); }, assessment_answer: function() { correct = true; var $input = $questionList.find('.wpProQuiz_questionInput'); if (lockResponse == true) { $questionList.find('.wpProQuiz_questionInput').attr('disabled', 'disabled'); } var val = 0; $input.filter(':checked').each(function() { val += parseInt($(this).val()); }); response = val; }, essay: function() { var question_id = $question.find('ul.wpProQuiz_questionList').data('question_id'); if (lockResponse == true) { $questionList.find('.wpProQuiz_questionEssay').attr('disabled', 'disabled'); } var essayText = $questionList.find('.wpProQuiz_questionEssay').val(); var essayFiles = $questionList.find('#uploadEssayFile_' + question_id).val(); if ( typeof essayText != 'undefined' ) { response = essayText; } if ( typeof essayFiles != 'undefined' ) { response = essayFiles; } } }; func[name](); return {response:response}; }; // Called from the Cookie handler logic. If the Quiz is loaded and a cookie is present the values of the cookie are used // to set the Quiz elements here. Once the value is set we call the trigger 'questionSolved' to update the question overview panel. function setResponse(question_data, question_value, question, $questionList) { if ((question_data.type == 'single') || (question_data.type == 'multiple')) { $questionList.children().each(function(i) { var $item = $(this); var index = $item.attr('data-pos'); if (question_value[index] != undefined) { var index_value = question_value[index]; if (index_value == true) { $('.wpProQuiz_questionInput', $item).prop('checked', 'checked'); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } } }); } else if (question_data.type == 'free_answer') { $questionList.children().each(function(i) { var $item = $(this); $('.wpProQuiz_questionInput', this).val(question_value); }); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } else if (question_data.type == 'sort_answer') { jQuery.each(question_value, function(pos, key){ var this_li = $('li.wpProQuiz_questionListItem[data-pos="'+key+'"]', $questionList); var this_li_inner = $('div.wpProQuiz_sortable', this_li); var this_li_inner_value = $(this_li_inner).text(); jQuery($questionList).append(this_li); }); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } else if (question_data.type == 'matrix_sort_answer') { jQuery.each(question_value, function(pos, key){ var question_response_item = $('.wpProQuiz_matrixSortString .wpProQuiz_sortStringList li[data-pos="'+pos+'"]', question); var question_destination_outer_li = $('li.wpProQuiz_questionListItem[data-pos="'+key+'"] ul.wpProQuiz_maxtrixSortCriterion', $questionList); jQuery(question_response_item).appendTo(question_destination_outer_li); }); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } else if (question_data.type == 'cloze_answer') { // Get the input fields within the questionList parent jQuery('span.wpProQuiz_cloze input[type="text"]', $questionList).each( function( index ) { if (typeof question_value[index] !== 'undefined' ) { $(this).val( question_value[index] ); } }); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } else if (question_data.type == 'assessment_answer') { $('input.wpProQuiz_questionInput[value="'+question_value+'"]', $questionList).attr('checked', 'checked'); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } else if (question_data.type == 'essay') { // The 'essay' value is generic. We need to figure out if this is an upload or inline essay. if ( $questionList.find('#uploadEssayFile_' + question_data.id).length ) { var question_input = $questionList.find('#uploadEssayFile_' + question_data.id); $( question_input ).val( question_value ); $('<p>'+basename( question_value )+'</p>').insertAfter( question_input ); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } else if ( $questionList.find('.wpProQuiz_questionEssay').length ) { $questionList.find('.wpProQuiz_questionEssay').html( question_value ); $e.trigger({type: 'questionSolved', values: {item: question, index: question.index(), solved: true}}); } } else { //console.log('unsupported type[%o]', question_data.type); //console.log('setResponse: question_data[%o] question_value[%o] question[%o], $questionList[%o]', question_data, question_value, question, $questionList); } } function basename(path) { if (path != undefined) { return path.split('/').reverse()[0]; } return ''; } /** * @memberOf formClass */ var formClass = new function() { var funcs = { isEmpty: function(str) { str = $.trim(str); return (!str || 0 === str.length); } // testValidate: function(str, type) { // switch (type) { // case 0: //None // return true; // case 1: //Text // return !funcs.isEmpty(str); // case 2: //Number // return !isNaN(str); // case 3: //E-Mail // return new RegExp(/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/) // .test($.trim(str)); // } // } }; var typeConst = { TEXT: 0, TEXTAREA: 1, NUMBER: 2, CHECKBOX: 3, EMAIL: 4, YES_NO: 5, DATE: 6, SELECT: 7, RADIO: 8 }; this.checkForm = function() { var check = true; $e.find('.wpProQuiz_forms input, .wpProQuiz_forms textarea, .wpProQuiz_forms .wpProQuiz_formFields, .wpProQuiz_forms select').each(function() { var $this = $(this); var isRequired = $this.data('required') == 1; var type = $this.data('type'); var test = true; var value = $.trim($this.val()); switch (type) { case typeConst.TEXT: case typeConst.TEXTAREA: case typeConst.SELECT: if(isRequired) test = !funcs.isEmpty(value); break; case typeConst.NUMBER: if(isRequired || !funcs.isEmpty(value)) test = !funcs.isEmpty(value) && !isNaN(value); break; case typeConst.EMAIL: if(isRequired || !funcs.isEmpty(value)) { //test = !funcs.isEmpty(value) && new RegExp(/^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/) // .test(value); // Use the same RegEx as the HTML5 email field. Per https://emailregex.com test = !funcs.isEmpty(value) && new RegExp(/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/) .test(value); } break; case typeConst.CHECKBOX: if(isRequired) test = $this.is(':checked'); break; case typeConst.YES_NO: case typeConst.RADIO: if(isRequired) test = $this.find('input[type="radio"]:checked').val() !== undefined; break; case typeConst.DATE: var num = 0, co = 0; $this.find('select').each(function() { num++; co += funcs.isEmpty($(this).val()) ? 0 : 1; }); if(isRequired || co > 0) test = num == co; break; } if(test) { $this.siblings('.wpProQuiz_invalidate').hide(); } else { check = false; $this.siblings('.wpProQuiz_invalidate').show(); } }); // $('.wpProQuiz_forms input, .wpProQuiz_forms textarea').each(function() { // var $this = $(this); // var isRequired = $this.data('required') == 1; // var validate = $this.data('validate') & 0xFF; // var test = false; // var $infos = $this.parents('div:eq(0)').find('.wpProQuiz_invalidate'); // // if(isRequired) { // if($this.attr('type') == 'checkbox') { // if($this.is(':checked')) // test = true; // // } else { // if(!funcs.isEmpty($this.val())) // test = true; // } // // if(!test) { // check = false; // $infos.eq(0).show(); // } else { // $infos.eq(0).hide(); // } // } // // if(!funcs.testValidate($this.val(), validate)) { // check = false; // $infos.eq(1).show(); // } else { // $infos.eq(1).hide(); // } // // }); // if(!check) // alert(WpProQuizGlobal.fieldsNotFilled); // return check; }; this.getFormData = function() { var data = {}; $e.find('.wpProQuiz_forms input, .wpProQuiz_forms textarea, .wpProQuiz_forms .wpProQuiz_formFields, .wpProQuiz_forms select').each(function() { var $this = $(this); var id = $this.data('form_id'); var type = $this.data('type'); switch (type) { case typeConst.TEXT: case typeConst.TEXTAREA: case typeConst.SELECT: case typeConst.NUMBER: case typeConst.EMAIL: data[id] = $this.val(); break; case typeConst.CHECKBOX: data[id] = $this.is(':checked') ? 1 : 0; break; case typeConst.YES_NO: case typeConst.RADIO: data[id] = $this.find('input[type="radio"]:checked').val(); break; case typeConst.DATE: data[id] = { day: $this.find('select[name="wpProQuiz_field_' + id +'_day"]').val(), month: $this.find('select[name="wpProQuiz_field_' + id +'_month"]').val(), year: $this.find('select[name="wpProQuiz_field_' + id +'_year"]').val() }; break; } }); return data; }; }; var fetchAllAnswerData = function(resultData) { $e.find('.wpProQuiz_questionList').each(function() { var $this = $(this); var questionId = $this.data('question_id'); var type = $this.data('type'); var data = {}; if(type == 'single' || type == 'multiple') { $this.find('.wpProQuiz_questionListItem').each(function() { data[$(this).attr('data-pos')] = +$(this).find('.wpProQuiz_questionInput').is(':checked'); }); } else if(type == 'free_answer') { data[0] = $this.find('.wpProQuiz_questionInput').val(); } else if(type == 'sort_answer') { return true; // $this.find('.wpProQuiz_questionListItem').each(function() { // data[$(this).index()] = $(this).attr('data-pos'); // }); } else if(type == 'matrix_sort_answer') { return true; // $this.find('.wpProQuiz_questionListItem').each(function() { // data[$(this).attr('data-pos')] = $(this).find('.wpProQuiz_answerCorrect').length; // }); } else if(type == 'cloze_answer') { var i = 0; $this.find('.wpProQuiz_cloze input').each(function() { data[i++] = $(this).val(); }); } else if(type == 'assessment_answer') { data[0] = ''; $this.find('.wpProQuiz_questionInput:checked').each(function() { data[$(this).data('index')] = $(this).val(); }); } else if(type == 'essay') { return; } resultData[questionId]['data'] = data; }); }; plugin.methode = { /** * @memberOf plugin.methode */ parseBitOptions: function() { if(config.bo) { bitOptions.randomAnswer = config.bo & (1 << 0); bitOptions.randomQuestion = config.bo & (1 << 1); bitOptions.disabledAnswerMark = config.bo & (1 << 2); bitOptions.checkBeforeStart = config.bo & (1 << 3); bitOptions.preview = config.bo & (1 << 4); bitOptions.isAddAutomatic = config.bo & (1 << 6); bitOptions.reviewQustion = config.bo & ( 1 << 7); bitOptions.quizSummeryHide = config.bo & (1 << 8); bitOptions.skipButton = config.bo & (1 << 9); bitOptions.autoStart = config.bo & (1 << 10); bitOptions.forcingQuestionSolve = config.bo & (1 << 11); bitOptions.hideQuestionPositionOverview = config.bo & (1 << 12); bitOptions.formActivated = config.bo & (1 << 13); bitOptions.maxShowQuestion = config.bo & (1 << 14); bitOptions.sortCategories = config.bo & (1 << 15); var cors = config.bo & (1 << 5); if(cors && jQuery.support != undefined && jQuery.support.cors != undefined && jQuery.support.cors == false) { bitOptions.cors = cors; } } }, setClozeStyle: function() { $e.find('.wpProQuiz_cloze input').each(function() { var $this = $(this); var word = ""; var wordLen = $this.data('wordlen'); for(var i = 0; i < wordLen; i++) word += "w"; var clone = $(document.createElement("span")) .css('visibility', 'hidden') .text(word) .appendTo($('body')); var width = clone.width(); clone.remove(); $this.width(width + 5); }); }, parseTime: function(sec) { var seconds = parseInt(sec % 60); var minutes = parseInt((sec / 60) % 60); var hours = parseInt((sec / 3600) % 24); seconds = (seconds > 9 ? '' : '0') + seconds; minutes = (minutes > 9 ? '' : '0') + minutes; hours = (hours > 9 ? '' : '0') + hours; return hours + ':' + minutes + ':' + seconds; }, cleanupCurlyQuotes: function(str) { str = str.replace(/\u2018/, "'"); str = str.replace(/\u2019/, "'"); str = str.replace(/\u201C/, '"'); str = str.replace(/\u201D/, '"'); //return $.trim(str).toLowerCase(); // Changes in v2.5 to NOT set cloze answers to lowercase return $.trim(str); }, resetMatrix: function(selector) { selector.each(function() { var $this = $(this); var $list = $this.find('.wpProQuiz_sortStringList'); $this.find('.wpProQuiz_sortStringItem').each(function() { $list.append($(this)); }); }); }, marker: function(e, correct) { if(!bitOptions.disabledAnswerMark) { if(correct === true ) { e.addClass('wpProQuiz_answerCorrect'); } else if (correct === false){ e.addClass('wpProQuiz_answerIncorrect'); } else { e.addClass(correct); } } }, startQuiz: function(loadData) { //if (config.ld_script_debug == true) { // console.log('in startQuiz'); //} if(quizStatus.loadLock) { quizStatus.isQuizStart = 1; return; } quizStatus.isQuizStart = 0; if(quizStatus.isLocked) { globalElements.quizStartPage.hide(); $e.find('.wpProQuiz_lock').show(); return; } if(quizStatus.isPrerequisite) { globalElements.quizStartPage.hide(); $e.find('.wpProQuiz_prerequisite').show(); return; } if(quizStatus.isUserStartLocked) { globalElements.quizStartPage.hide(); $e.find('.wpProQuiz_startOnlyRegisteredUser').show(); return; } if(bitOptions.maxShowQuestion && !loadData) { if(config.formPos == formPosConst.START) { if(!formClass.checkForm()) return; } globalElements.quizStartPage.hide(); $e.find('.wpProQuiz_loadQuiz').show(); plugin.methode.loadQuizDataAjax(true); return; } if(bitOptions.formActivated && config.formPos == formPosConst.START) { if(!formClass.checkForm()) return; } plugin.methode.loadQuizData(); if(bitOptions.randomQuestion) { plugin.methode.random(globalElements.questionList); } if(bitOptions.randomAnswer) { plugin.methode.random($e.find(globalNames.questionList)); } if(bitOptions.sortCategories) { plugin.methode.sortCategories(); } // randomize the matrix sort question items plugin.methode.random($e.find('.wpProQuiz_sortStringList')); // randomize the sort question answers plugin.methode.random($e.find('.wpProQuiz_questionList[data-type="sort_answer"]')); $e.find('.wpProQuiz_listItem').each(function(i, v) { var $this = $(this); $this.find('.wpProQuiz_question_page span:eq(0)').text(i+1); $this.find('> h5 span').text(i+1); $this.find('.wpProQuiz_questionListItem').each(function(i, v) { $(this).find('> span:not(.wpProQuiz_cloze)').text(i+1 + '. '); }); }); globalElements.next = $e.find(globalNames.next); switch (config.mode) { case 3: $e.find('input[name="checkSingle"]').show(); break; case 2: $e.find(globalNames.check).show(); if(!bitOptions.skipButton && bitOptions.reviewQustion) $e.find(globalNames.skip).show(); break; case 1: $e.find('input[name="back"]').slice(1).show(); case 0: globalElements.next.show(); break; } if(bitOptions.hideQuestionPositionOverview || config.mode == 3) $e.find('.wpProQuiz_question_page').hide(); //Change last name var $lastButton = globalElements.next.last(); lastButtonValue = $lastButton.val(); $lastButton.val(config.lbn); var $listItem = globalElements.questionList.children(); globalElements.listItems = $e.find('.wpProQuiz_list > li'); if(config.mode == 3) { plugin.methode.showSinglePage(0); // if(config.qpp) { // $listItem.slice(0, config.qpp).show(); // $e.find(globalNames.singlePageRight).show(); // $e.find('input[name="checkSingle"]').hide(); // } else { // $listItem.show(); // } } else { currentQuestion = $listItem.eq(0).show(); var questionId = currentQuestion.find(globalNames.questionList).data('question_id'); questionTimer.questionStart(questionId); } questionTimer.startQuiz(); $e.find('.wpProQuiz_sortable').parents('ul').sortable({ update: function( event, ui ) { var $p = $(this).parents('.wpProQuiz_listItem'); $e.trigger({type: 'questionSolved', values: {item: $p, index: $p.index(), solved: true}}); } }).disableSelection(); $e.find('.wpProQuiz_sortStringList, .wpProQuiz_maxtrixSortCriterion').sortable({ connectWith: '.wpProQuiz_maxtrixSortCriterion:not(:has(li)), .wpProQuiz_sortStringList', placeholder: 'wpProQuiz_placehold', update: function( event, ui ) { var $p = $(this).parents('.wpProQuiz_listItem'); $e.trigger({type: 'questionSolved', values: {item: $p, index: $p.index(), solved: true}}); } }).disableSelection(); quizSolved = []; timelimit.start(); startTime = +new Date(); results = {comp: {points: 0, correctQuestions: 0, quizTime: 0}}; $e.find('.wpProQuiz_questionList').each(function() { var questionId = $(this).data('question_id'); results[questionId] = {time: 0}; }); catResults = {}; $.each(options.catPoints, function(i, v) { catResults[i] = 0; }); globalElements.quizStartPage.hide(); $e.find('.wpProQuiz_loadQuiz').hide(); globalElements.quiz.show(); reviewBox.show(); // Init our Cookie plugin.methode.CookieInit(); //$('li.wpProQuiz_listItem', globalElements.questionList).each( function (idx, questionItem) { plugin.methode.setupMatrixSortHeights(); //}); if(config.mode != 3) { $e.trigger({type: 'changeQuestion', values: {item: currentQuestion, index: currentQuestion.index()}}); } }, viewUserQuizStatistics: function(button) { //console.log('in viewUserQuizStatistics'); var refId = jQuery(button).data('ref_id'); //console.log('refId[%o]', refId); var quizId = jQuery(button).data('quiz_id'); //console.log('quizId[%o]', quizId); var post_data = { 'action': 'wp_pro_quiz_admin_ajax', 'func': 'statisticLoadUser', 'data': { 'quizId': quizId, 'userId': 0, 'refId': refId, 'avg': 0 } } jQuery('#wpProQuiz_user_overlay, #wpProQuiz_loadUserData').show(); var content = jQuery('#wpProQuiz_user_content').hide(); console.log('- wpProQuiz_front.js'); jQuery.ajax({ type: "POST", url: WpProQuizGlobal.ajaxurl, dataType: "json", cache: false, data: post_data, error: function(jqXHR, textStatus, errorThrown ) { }, success: function(reply_data) { if ( typeof reply_data.html !== 'undefined' ) { content.html(reply_data.html); jQuery('#wpProQuiz_user_content').show(); console.log('trigger event change - wpProQuiz_front.js'); jQuery('#wpProQuiz_loadUserData').hide(); content.find('.statistic_data').click(function() { jQuery(this).parents('tr').next().toggle('fast'); return false; }); } } }); jQuery('#wpProQuiz_overlay_close').click(function() { jQuery('#wpProQuiz_user_overlay').hide(); }); }, showSingleQuestion: function(question) { var page = question ? Math.ceil(question / config.qpp) : 1; this.showSinglePage(page); // plugin.methode.scrollTo($element, 1); }, showSinglePage: function(page) { $listItem = globalElements.questionList.children().hide(); if(!config.qpp) { $listItem.show(); return; } page = page ? +page : 1; var maxPage = Math.ceil($e.find('.wpProQuiz_list > li').length / config.qpp); if(page > maxPage) return; var pl = $e.find(globalNames.singlePageLeft).hide(); var pr = $e.find(globalNames.singlePageRight).hide(); var cs = $e.find('input[name="checkSingle"]').hide(); if(page > 1) { pl.val(pl.data('text').replace(/%d/, page-1)).show(); } if(page == maxPage) { cs.show(); } else { pr.val(pr.data('text').replace(/%d/, page+1)).show(); } currentPage = page; var start = config.qpp * (page - 1); $listItem.slice(start, start + config.qpp).show(); plugin.methode.scrollTo(globalElements.quiz); }, nextQuestion: function () { plugin.methode.CookieProcessQuestionResponse(currentQuestion); jQuery(".mejs-pause").trigger("click"); this.showQuestionObject(currentQuestion.next()); }, prevQuestion: function() { this.showQuestionObject(currentQuestion.prev()); }, showQuestion: function(index) { var $element = globalElements.listItems.eq(index); if(config.mode == 3 || inViewQuestions) { if(config.qpp) { plugin.methode.showSingleQuestion(index+1); // questionTimer.startQuiz(); // return; } // plugin.methode.scrollTo($e.find('.wpProQuiz_list > li').eq(index), 1); plugin.methode.scrollTo($element, 1); questionTimer.startQuiz(); return; } // currentQuestion.hide(); // // currentQuestion = $element.show(); // // plugin.methode.scrollTo(globalElements.quiz); // // $e.trigger({type: 'changeQuestion', values: {item: currentQuestion, index: currentQuestion.index()}}); // // if(!currentQuestion.length) // plugin.methode.showQuizSummary(); this.showQuestionObject($element); }, showQuestionObject: function(obj) { if(!obj.length && bitOptions.forcingQuestionSolve && bitOptions.quizSummeryHide && bitOptions.reviewQustion) { // First get all the questions... list = globalElements.questionList.children(); if (list != null) { list.each(function() { var $this = $(this); var $questionList = $this.find(globalNames.questionList); var question_id = $questionList.data('question_id'); var data = config.json[$questionList.data('question_id')]; // Within the following logic. If the question type is 'sort_answer' there is a chance // the sortable answers will be displayed in the correct order. In that case the user will click // the next button. // The trigger to set the question was answered is normally a function of the sort/drag action // by the user. So we need to set the question answered flag in the case the Quiz summary is enabled. if (data.type == 'sort_answer') { $e.trigger({type: 'questionSolved', values: {item: $this, index: $this.index(), solved: true}}); } }); } for(var i = 0, c = $e.find('.wpProQuiz_listItem').length; i < c; i++) { if(!quizSolved[i]) { alert(WpProQuizGlobal.questionsNotSolved); return false; } } } currentQuestion.hide(); currentQuestion = obj.show(); plugin.methode.scrollTo(globalElements.quiz); $e.trigger({type: 'changeQuestion', values: {item: currentQuestion, index: currentQuestion.index()}}); if(!currentQuestion.length) { plugin.methode.showQuizSummary(); } else { var questionId = currentQuestion.find(globalNames.questionList).data('question_id'); questionTimer.questionStart(questionId); } }, skipQuestion: function() { $e.trigger({type: 'skipQuestion', values: {item: currentQuestion, index: currentQuestion.index()}}); plugin.methode.nextQuestion(); }, reviewQuestion: function() { $e.trigger({type: 'reviewQuestion', values: {item: currentQuestion, index: currentQuestion.index()}}); }, uploadFile: function( event ) { var question_id = event.currentTarget.id.replace('uploadEssaySubmit_', ''); var file = $( '#uploadEssay_' + question_id )[0].files[0]; if (typeof file !== 'undefined') { var nonce = $( '#_uploadEssay_nonce_' + question_id ).val(); var uploadEssaySubmit = $('#uploadEssaySubmit_' + question_id ); uploadEssaySubmit.val(config.essayUploading); var data = new FormData(); data.append('action', 'learndash_upload_essay'); data.append('nonce', nonce); data.append('question_id', question_id ); data.append('course_id', config.course_id ); data.append('essayUpload', file); $.ajax({ method: 'POST', type: 'POST', url: WpProQuizGlobal.ajaxurl, data: data, cache: false, contentType: false, processData: false, success: function(response){ if(response.success == true && typeof response.data.filelink != 'undefined' ) { $('#uploadEssayFile_' + question_id ).val(response.data.filelink); uploadEssaySubmit.attr('disabled', 'disabled'); setTimeout( function(){ uploadEssaySubmit.val(config.essaySuccess); }, 1500 ); var $item = $('#uploadEssayFile_' + question_id ).parents('.wpProQuiz_listItem'); $e.trigger({type: 'questionSolved', values: {item: $item, index: $item.index(), solved: true}}); } else { uploadEssaySubmit.removeAttr('disabled'); uploadEssaySubmit.val('Failed. Try again.'); } } }); } event.preventDefault(); }, showQuizSummary: function() { questionTimer.questionStop(); questionTimer.stopQuiz(); if(bitOptions.quizSummeryHide || !bitOptions.reviewQustion) { if(bitOptions.formActivated && config.formPos == formPosConst.END) { reviewBox.hide(); globalElements.quiz.hide(); plugin.methode.scrollTo($e.find('.wpProQuiz_infopage').show()); } else { plugin.methode.finishQuiz(); } return; } var quizSummary = $e.find('.wpProQuiz_checkPage'); quizSummary.find('ol:eq(0)').empty() .append($e.find('.wpProQuiz_reviewQuestion ol li').clone().removeClass('wpProQuiz_reviewQuestionTarget')) .children().click(function(e) { quizSummary.hide(); globalElements.quiz.show(); reviewBox.show(true); plugin.methode.showQuestion($(this).index()); }); var cSolved = 0; for(var i = 0, c = quizSolved.length; i < c; i++) { if(quizSolved[i]) { cSolved++; } } quizSummary.find('span:eq(0)').text(cSolved); reviewBox.hide(); globalElements.quiz.hide(); quizSummary.show(); plugin.methode.scrollTo(quizSummary); }, finishQuiz: function(timeover) { // LEARNDASH-4412 : Disable final buttons on submit. globalElements.next.last().attr('disabled', 'disabled'); $e.find('input[name="checkSingle"]').attr('disabled', 'disabled');; questionTimer.questionStop(); questionTimer.stopQuiz(); timelimit.stop(); var time = (+new Date() - startTime) / 1000; time = (config.timelimit && time > config.timelimit) ? config.timelimit : time; timespent = time; $e.find('.wpProQuiz_quiz_time span').text(plugin.methode.parseTime(time)); if(timeover) { globalElements.results.find('.wpProQuiz_time_limit_expired').show(); } plugin.methode.checkQuestion(globalElements.questionList.children(), true); }, finishQuizEnd: function() { $e.find('.wpProQuiz_correct_answer').text(results.comp.correctQuestions); results.comp.result = Math.round(results.comp.points / config.globalPoints * 100 * 100) / 100; var hasNotGradedQuestion = false; $.each( results, function() { if ( typeof this.graded_status !== 'undefined' && this.graded_status == 'not_graded' ) { hasNotGradedQuestion = true; } }); if(typeof certificate_details !== 'undefined' && certificate_details.certificateLink != undefined && certificate_details.certificateLink != "" ) { var certificateContainer = $e.find('.wpProQuiz_certificate'); if (results.comp.result >= certificate_details.certificate_threshold * 100 ) { //if (true == hasNotGradedQuestion && typeof certificate_pending !== 'undefined') { // certificateContainer.append('<br />'+certificate_pending ); //} certificateContainer.show(); } else if ( true == hasNotGradedQuestion && typeof certificate_pending !== 'undefined') { certificateContainer.html(certificate_pending); certificateContainer.show() } } var quiz_continue_link = $e.find('.quiz_continue_link'); var show_quiz_continue_buttom_on_fail = false; if ( jQuery( quiz_continue_link).hasClass( 'show_quiz_continue_buttom_on_fail' ) ) { show_quiz_continue_buttom_on_fail = true; } if ((typeof options.passingpercentage !== 'undefined') && (parseFloat(options.passingpercentage) >= 0.0)) { if ((results.comp.result >= options.passingpercentage) || (show_quiz_continue_buttom_on_fail)) { //For now, Just append the HTML to the page if(typeof continue_details !== 'undefined') { $e.find('.quiz_continue_link').html(continue_details); $e.find('.quiz_continue_link').show(); } } else { $e.find('.quiz_continue_link').hide(); } } else { if(typeof continue_details !== 'undefined') { $e.find('.quiz_continue_link').html(continue_details); $e.find('.quiz_continue_link').show(); } } $pointFields = $e.find('.wpProQuiz_points span'); $gradedPointsFields = $e.find('.wpProQuiz_graded_points span'); $pointFields.eq(0).text(results.comp.points); $pointFields.eq(1).text(config.globalPoints); $pointFields.eq(2).text(results.comp.result + '%'); $gradedQuestionCount = 0; $gradedQuestionPoints = 0; $.each( results, function( question_id, result ) { if ( $.isNumeric( question_id ) && result.graded_id ) { var possible = result.possiblePoints - result.points; if (possible > 0) { $gradedQuestionPoints += possible; $gradedQuestionCount++; } } }); if ( $gradedQuestionCount > 0 ) { $('.wpProQuiz_points').hide(); $('.wpProQuiz_graded_points').show(); $gradedPointsFields.eq(0).text(results.comp.points); $gradedPointsFields.eq(1).text(config.globalPoints); $gradedPointsFields.eq(2).text(results.comp.result + '%'); $gradedPointsFields.eq(3).text($gradedQuestionCount); $gradedPointsFields.eq(4).text($gradedQuestionPoints); } $e.find('.wpProQuiz_resultsList > li').eq(plugin.methode.findResultIndex(results.comp.result)).show(); plugin.methode.setAverageResult(results.comp.result, false); this.setCategoryOverview(); plugin.methode.sendCompletedQuiz(); if(bitOptions.isAddAutomatic && toplistData.isUser) { plugin.methode.addToplist(); } reviewBox.hide(); $e.find('.wpProQuiz_checkPage, .wpProQuiz_infopage').hide(); globalElements.quiz.hide(); }, sending: function(start, end, step_size) { globalElements.sending.show(); var sending_progress_bar = globalElements.sending.find('.sending_progress_bar'); var i; if(typeof start == undefined || start == null) { i = parseInt(sending_progress_bar.width()*100/sending_progress_bar.offsetParent().width()) + 156; } else i = start; if(end == undefined) var end = 80; if(step_size == undefined) step_size = 1; if(sending_timer != null && typeof sending_timer != undefined) { clearInterval(sending_timer); } sending_timer = setInterval(function(){ var currentWidth = parseInt(sending_progress_bar.width()*100/sending_progress_bar.offsetParent().width()); if(currentWidth >= end) { clearInterval(sending_timer); if(currentWidth >= 100) { setTimeout(plugin.methode.showResults(), 2000); } } sending_progress_bar.css("width", i + "%"); i = i + step_size; }, 300); }, showResults: function() { globalElements.sending.hide(); globalElements.results.show(); plugin.methode.scrollTo(globalElements.results); }, setCategoryOverview: function() { results.comp.cats = {}; $e.find('.wpProQuiz_catOverview li').each(function() { var $this = $(this); var catId = $this.data('category_id'); if(config.catPoints[catId] === undefined) { $this.hide(); return true; } var r = Math.round(catResults[catId] / config.catPoints[catId] * 100 * 100) / 100; results.comp.cats[catId] = r; $this.find('.wpProQuiz_catPercent').text(r + '%'); $this.show(); }); }, questionSolved: function(e) { //if (config.ld_script_debug == true) { // console.log('questionSolved: e.values[%o]', e.values); //} quizSolved[e.values.index] = e.values.solved; }, sendCompletedQuiz: function() { if(bitOptions.preview) return; //console.log('sendCompletedQuiz: results[%o]', results); fetchAllAnswerData(results); var formData = formClass.getFormData(); jQuery.ajax({ type: 'POST', url: WpProQuizGlobal.ajaxurl, dataType: "json", cache: false, data: { action: 'wp_pro_quiz_completed_quiz', course_id: config.course_id, lesson_id: config.lesson_id, topic_id: config.topic_id, quiz: config.quiz, quizId: config.quizId, results: JSON.stringify(results), timespent: timespent, forms: formData, quiz_nonce: config.quiz_nonce, }, success: function (json) { if (json != null) { if (typeof config['quizId'] !== 'undefined') { var quiz_pro_id = parseInt( config['quizId'] ); if ((typeof json[quiz_pro_id] !== 'undefined') && (typeof json[quiz_pro_id]['quiz_result_settings'] !== 'undefined')) { result_settings = json[quiz_pro_id]['quiz_result_settings']; plugin.methode.afterSendUpdateIU(result_settings ); } } } plugin.methode.sending(null, 100, 15); //Complete the remaining progress bar faster and show results // Clear Cookie on restart plugin.methode.CookieDelete(); } }); }, afterSendUpdateIU: function( quiz_result_settings ) { if (typeof quiz_result_settings['showAverageResult'] !== 'undefined') { if (!quiz_result_settings['showAverageResult']) { $e.find('.wpProQuiz_resultTable').remove(); } } if (typeof quiz_result_settings['showCategoryScore'] !== 'undefined') { if (!quiz_result_settings['showCategoryScore']) { $e.find('.wpProQuiz_catOverview').remove(); } } if (typeof quiz_result_settings['showRestartQuizButton'] !== 'undefined') { if (!quiz_result_settings['showRestartQuizButton']) { $e.find('input[name="restartQuiz"]').remove(); } } if (typeof quiz_result_settings['showResultPoints'] !== 'undefined') { if (!quiz_result_settings['showResultPoints']) { $e.find('.wpProQuiz_points').remove(); } } if (typeof quiz_result_settings['showResultQuizTime'] !== 'undefined') { if (!quiz_result_settings['showResultQuizTime']) { $e.find('.wpProQuiz_quiz_time').remove(); } } if ( typeof quiz_result_settings['showViewQuestionButton'] !== 'undefined') { if ( ! quiz_result_settings['showViewQuestionButton'] ) { $e.find('input[name="reShowQuestion"]').remove(); } } if ( typeof quiz_result_settings['showContinueButton'] !== 'undefined' ) { if ( ! quiz_result_settings['showContinueButton'] ) { $e.find('.quiz_continue_link').remove(); } } }, findResultIndex: function(p) { var r = config.resultsGrade; var index = -1; var diff = 999999; for(var i = 0; i < r.length; i++){ var v = r[i]; if((p >= v) && ((p-v) < diff)) { diff = p-v; index = i; } } return index; }, showQustionList: function() { inViewQuestions = !inViewQuestions; globalElements.toplistShowInButton.hide(); globalElements.quiz.toggle(); $e.find('.wpProQuiz_QuestionButton').hide(); globalElements.questionList.children().show(); reviewBox.toggle(); $e.find('.wpProQuiz_question_page').hide(); }, random: function(group) { group.each(function() { var e = $(this).children().get().sort(function() { return Math.round(Math.random()) - 0.5; }); $(e).appendTo(e[0].parentNode); }); }, sortCategories: function() { var e = $('.wpProQuiz_list').children().get().sort(function(a, b) { var aQuestionId = $(a).find('.wpProQuiz_questionList').data('question_id'); var bQuestionId = $(b).find('.wpProQuiz_questionList').data('question_id'); return config.json[aQuestionId].catId - config.json[bQuestionId].catId; }); $(e).appendTo(e[0].parentNode); }, restartQuiz: function() { globalElements.results.hide(); //globalElements.quizStartPage.show(); globalElements.questionList.children().hide(); globalElements.toplistShowInButton.hide(); reviewBox.hide(); $e.find('.wpProQuiz_questionInput, .wpProQuiz_cloze input').removeAttr('disabled').removeAttr('checked') .css('background-color', ''); // Reset all the question types to empty values. This really should be moved into a reset function to be called at other times like at Quiz Init. // $e.find('.wpProQuiz_cloze input').val(''); $e.find('.wpProQuiz_questionListItem input[type="text"]').val(''); $e.find('.wpProQuiz_answerCorrect, .wpProQuiz_answerIncorrect').removeClass('wpProQuiz_answerCorrect wpProQuiz_answerIncorrect'); $e.find('.wpProQuiz_listItem').data('check', false); $e.find('textarea.wpProQuiz_questionEssay').val(''); $e.find('input.uploadEssayFile').val(''); $e.find('input.wpProQuiz_upload_essay').val(''); $e.find('.wpProQuiz_response').hide().children().hide(); plugin.methode.resetMatrix($e.find('.wpProQuiz_listItem')); $e.find('.wpProQuiz_sortStringItem, .wpProQuiz_sortable').removeAttr('style'); $e.find('.wpProQuiz_clozeCorrect, .wpProQuiz_QuestionButton, .wpProQuiz_resultsList > li').hide(); $e.find('.wpProQuiz_question_page, input[name="tip"]').show(); $e.find(".wpProQuiz_certificate").attr('style', 'display: none !important'); globalElements.results.find('.wpProQuiz_time_limit_expired').hide(); globalElements.next.last().val(lastButtonValue); inViewQuestions = false; // Clear Cookie on restart //plugin.methode.CookieDelete(); // LEARNDASH-3201 - Added reload to force check on Quiz Repeats / Run Once logic. window.location.reload(true); }, showSpinner: function() { $e.find(".wpProQuiz_spinner").show(); }, hideSpinner: function() { $e.find(".wpProQuiz_spinner").hide(); }, checkQuestion: function(list, endCheck) { var finishQuiz = (list == undefined) ? false : true; var responses = {}; var r = {}; list = (list == undefined) ? currentQuestion : list; list.each(function() { var $this = $(this); var question_index = $this.index(); var $questionList = $this.find(globalNames.questionList); var question_id = $questionList.data('question_id'); var data = config.json[$questionList.data('question_id')]; var name = data.type; questionTimer.questionStop(); if($this.data('check')) { return true; } if(data.type == 'single' || data.type == 'multiple') { name = 'singleMulti'; } //if (config.ld_script_debug == true) { // console.log('checkQuestion: calling readResponses'); //} responses[question_id] = readResponses(name, data, $this, $questionList, true); responses[question_id]['question_pro_id'] = data['id']; responses[question_id]['question_post_id'] = data['question_post_id']; plugin.methode.CookieSaveResponse(question_id, question_index, data.type, responses[question_id]); }); //console.log('responses[%o]', responses); config.checkAnswers = {list: list, responses: responses, endCheck:endCheck, finishQuiz:finishQuiz}; if(finishQuiz) { plugin.methode.sending(1, 80, 3); } else { plugin.methode.showSpinner(); } //console.log('config.json[%o]', config.json); plugin.methode.ajax({ action: 'ld_adv_quiz_pro_ajax', func: 'checkAnswers', data: { quizId: config.quizId, quiz : config.quiz, course_id: config.course_id, quiz_nonce: config.quiz_nonce, responses: JSON.stringify(responses) } }, function(json) { plugin.methode.hideSpinner(); var list = config.checkAnswers.list; var responses = config.checkAnswers.responses; var r = config.checkAnswers.r; var endCheck = config.checkAnswers.endCheck; var finishQuiz = config.checkAnswers.finishQuiz; list.each(function() { var $this = $(this); var $questionList = $this.find(globalNames.questionList); var question_id = $questionList.data('question_id'); //var data = {id: question_id}; if($this.data('check')) { return true; } if ( typeof json[question_id] !== 'undefined' ) { var result = json[question_id]; data = config.json[$questionList.data('question_id')]; $this.find('.wpProQuiz_response').show(); $this.find(globalNames.check).hide(); $this.find(globalNames.skip).hide(); $this.find(globalNames.next).show(); results[data.id].points = result.p; if ( typeof result.p_nonce !== 'undefined' ) results[data.id].p_nonce = result.p_nonce; else results[data.id].p_nonce = ''; results[data.id].correct = Number(result.c); results[data.id].data = result.s; if ( typeof result.a_nonce !== 'undefined' ) results[data.id].a_nonce = result.a_nonce; else results[data.id].a_nonce = ''; results[data.id].possiblePoints = result.e.possiblePoints; // If the sort_answer or matrix_sort_answer question type is not 100% correct then the returned // result.s object will be empty. So in order to pass the user's answers to the server for the // sendCompletedQuiz AJAX call we need to grab the result.e.r object and store into results. if (jQuery.isEmptyObject(results[data.id].data)) { if ((result.e.type != undefined) && ((result.e.type == 'sort_answer') || (result.e.type == 'matrix_sort_answer'))) { results[data.id].data = result.e.r; } } if ( typeof result.e.graded_id !== 'undefined' && result.e.graded_id > 0 ) { results[data.id].graded_id = result.e.graded_id; } if ( typeof result.e.graded_status !== 'undefined' ) { results[data.id].graded_status = result.e.graded_status; } results['comp'].points += result.p; $this.find('.wpProQuiz_response').show(); $this.find(globalNames.check).hide(); $this.find(globalNames.skip).hide(); $this.find(globalNames.next).show(); //results[data.id].points = result.p; //results[data.id].correct = Number(result.c); //results[data.id].data = result.s; // If the sort_answer or matrix_sort_answer question type is not 100% correct then the returned // result.s object will be empty. So in order to pass the user's answers to the server for the // sendCompletedQuiz AJAX call we need to grab the result.e.r object and store into results. if (jQuery.isEmptyObject(results[data.id].data)) { if ( typeof result.e.type !== 'undefined' ) { if ( (result.e.type == 'sort_answer' ) || ( result.e.type == 'matrix_sort_answer' ) ) { if ( typeof result.e.r !== 'undefined' ) { results[data.id].data = result.e.r; } } if ( result.e.type == 'essay' ) { if ( typeof result.e.graded_id !== 'undefined' ) { results[data.id].data = { "graded_id": result.e.graded_id }; } } } } //results['comp'].points += result.p; catResults[data.catId] += result.p; //Marker plugin.methode.markCorrectIncorrect(result, $this, $questionList); if(result.c) { if(typeof result.e.AnswerMessage !== "undefined") { $this.find('.wpProQuiz_correct').find(".wpProQuiz_AnswerMessage").html(result.e.AnswerMessage); $this.find('.wpProQuiz_correct').trigger('learndash-quiz-answer-response-contentchanged'); } $this.find('.wpProQuiz_correct').show(); results['comp'].correctQuestions += 1; } else { if(typeof result.e.AnswerMessage !== "undefined") { $this.find('.wpProQuiz_incorrect').find(".wpProQuiz_AnswerMessage").html(result.e.AnswerMessage); $this.find('.wpProQuiz_incorrect').trigger('learndash-quiz-answer-response-contentchanged'); } $this.find('.wpProQuiz_incorrect').show(); } $this.find('.wpProQuiz_responsePoints').text(result.p); $this.data('check', true); if(!endCheck) $e.trigger({type: 'questionSolved', values: {item: $this, index: $this.index(), solved: true}}); } }); // Set a default just in case. //results.comp.p_nonce = ''; //if ( typeof json['comp'] !== 'undefined' ) { // if ( ( typeof json['comp']['p'] !== 'undefined' ) && ( typeof json['comp']['p_nonce'] !== 'undefined' ) ) { // results.comp.points = json['comp']['p']; // results.comp.p_nonce = json['comp']['p_nonce']; // } //} if(finishQuiz) plugin.methode.finishQuizEnd(); }); }, markCorrectIncorrect: function(result, $question, $questionList) { if(typeof result.e.c == "undefined") return; switch(result.e.type) { case 'single': case 'multiple': $questionList.children().each(function(i) { var $item = $(this); var index = $item.attr('data-pos'); if(result.e.c[index]) { var checked = $('input.wpProQuiz_questionInput', $item).is(':checked'); if (checked) { plugin.methode.marker($item, true); } else { plugin.methode.marker($item, 'wpProQuiz_answerCorrectIncomplete'); } } else { if(!result.c && result.e.r[index]) plugin.methode.marker($item, false); } }); break; case 'free_answer': var $li = $questionList.children(); if(result.c) plugin.methode.marker($li, true); else plugin.methode.marker($li, false); break; case 'cloze_answer': $questionList.find('.wpProQuiz_cloze').each(function(i, v) { var $this = $(this); var cloze = $this.children(); var input = cloze.eq(0); var span = cloze.eq(1); var inputText = plugin.methode.cleanupCurlyQuotes(input.val()); if(result.s[i]) { //input.css('background-color', '#B0DAB0'); input.addClass('wpProQuiz_answerCorrect'); } else { input.addClass('wpProQuiz_answerIncorrect'); //input.css('background-color', '#FFBABA'); if(typeof result.e.c[i] != "undefined" ) { span.html("(" + result.e.c[i].join() + ")"); span.show(); } } input.attr('disabled', 'disabled'); }); break; case 'sort_answer': var $items = $questionList.children(); $items.each(function(i, v) { var $this = $(this); if(result.e.c[i] == $this.attr('data-pos')) { plugin.methode.marker($this, true); } else { plugin.methode.marker($this, false); } }); $items.children().css({'box-shadow': '0 0', 'cursor': 'auto'}); // $questionList.sortable("destroy"); var index = new Array(); jQuery.each(result.e.c, function(i,v) { index[v] = i; }); $items.sort(function(a, b) { return index[$(a).attr('data-pos')] > index[$(b).attr('data-pos')] ? 1 : -1; }); $questionList.append($items); break; case 'matrix_sort_answer': var $items = $questionList.children(); var matrix = new Array(); statistcAnswerData = {0:-1}; $items.each(function() { var $this = $(this); var id = $this.attr('data-pos'); var $stringUl = $this.find('.wpProQuiz_maxtrixSortCriterion'); var $stringItem = $stringUl.children(); var i = $stringItem.attr('data-pos'); if($stringItem.length && result.e.c[i] == $this.attr('data-pos')) { plugin.methode.marker($this, true); } else { plugin.methode.marker($this, false); } matrix[i] = $stringUl; }); plugin.methode.resetMatrix($question); $question.find('.wpProQuiz_sortStringItem').each(function() { var x = matrix[$(this).attr('data-pos')]; if(x != undefined) x.append(this); }).css({'box-shadow': '0 0', 'cursor': 'auto'}); // $question.find('.wpProQuiz_sortStringList, .wpProQuiz_maxtrixSortCriterion').sortable("destroy"); break; } }, showTip: function() { var $this = $(this); var id = $this.siblings('.wpProQuiz_question').find(globalNames.questionList).data('question_id'); $this.siblings('.wpProQuiz_tipp').toggle('fast'); results[id].tip = 1; $(document).bind('mouseup.tipEvent', function(e) { var $tip = $e.find('.wpProQuiz_tipp'); var $btn = $e.find('input[name="tip"]'); if(!$tip.is(e.target) && $tip.has(e.target).length == 0 && !$btn.is(e.target)) { $tip.hide('fast'); $(document).unbind('.tipEvent'); } }); }, ajax: function(data, success, dataType) { dataType = dataType || 'json'; if(bitOptions.cors) { jQuery.support.cors = true; } if (data['quiz'] === undefined) { data['quiz'] = config.quiz; } if (data['course_id'] === undefined) { data['course_id'] = config.course_id; } if (data['quiz_nonce'] === undefined) { data['quiz_nonce'] = config.quiz_nonce; } $.ajax({ method: 'POST', type: 'POST', url: WpProQuizGlobal.ajaxurl, data: data, success: success, dataType: dataType, }); if(bitOptions.cors) { jQuery.support.cors = false; } }, checkQuizLock: function() { quizStatus.loadLock = 1; plugin.methode.ajax({ action: 'wp_pro_quiz_check_lock', quizId: config.quizId }, function(json) { if(json.lock != undefined) { quizStatus.isLocked = json.lock.is; /** * Removed as part of LEARNDASH-4027 * The restart button does not need to be removed. It can be hidden * via the Quiz setting. */ /* if(json.lock.pre) { $e.find('input[name="restartQuiz"]').hide(); } */ } if(json.prerequisite != undefined) { quizStatus.isPrerequisite = 1; $e.find('.wpProQuiz_prerequisite span').text(json.prerequisite); } if(json.startUserLock != undefined) { quizStatus.isUserStartLocked = json.startUserLock; } quizStatus.loadLock = 0; if(quizStatus.isQuizStart) { plugin.methode.startQuiz(); } }); }, loadQuizData: function() { plugin.methode.ajax({ action: 'wp_pro_quiz_load_quiz_data', quizId: config.quizId }, function(json) { if(json.toplist) { plugin.methode.handleToplistData(json.toplist); } if(json.averageResult != undefined) { plugin.methode.setAverageResult(json.averageResult, true); } }); }, setAverageResult: function(p, g) { var v = $e.find('.wpProQuiz_resultValue:eq(' + (g ? 0 : 1) + ') > * '); v.eq(1).text(p + '%'); v.eq(0).css('width', (240 * p / 100) + 'px'); }, handleToplistData: function(json) { var $tp = $e.find('.wpProQuiz_addToplist'); var $addBox = $tp.find('.wpProQuiz_addBox').show().children('div'); if(json.canAdd) { $tp.show(); $tp.find('.wpProQuiz_addToplistMessage').hide(); $tp.find('.wpProQuiz_toplistButton').show(); toplistData.token = json.token; toplistData.isUser = 0; if(json.userId) { $addBox.hide(); toplistData.isUser = 1; if(bitOptions.isAddAutomatic) { $tp.hide(); } } else { $addBox.show(); var $captcha = $addBox.children().eq(1); if(json.captcha) { $captcha.find('input[name="wpProQuiz_captchaPrefix"]').val(json.captcha.code); $captcha.find('.wpProQuiz_captchaImg').attr('src', json.captcha.img); $captcha.find('input[name="wpProQuiz_captcha"]').val(''); $captcha.show(); } else { $captcha.hide(); } } } else { $tp.hide(); } }, scrollTo: function(e, h) { var x = e.offset().top - 100; if(h || (window.pageYOffset || document.body.scrollTop) > x) { $('html,body').animate({scrollTop: x}, 300); } }, addToplist: function() { if(bitOptions.preview) return; var $addToplistMessage = $e.find('.wpProQuiz_addToplistMessage').text(WpProQuizGlobal.loadData).show(); var $addBox = $e.find('.wpProQuiz_addBox').hide(); plugin.methode.ajax({ action: 'wp_pro_quiz_add_toplist', quizId: config.quizId, quiz : config.quiz, token: toplistData.token, name: $addBox.find('input[name="wpProQuiz_toplistName"]').val(), email: $addBox.find('input[name="wpProQuiz_toplistEmail"]').val(), captcha: $addBox.find('input[name="wpProQuiz_captcha"]').val(), prefix: $addBox.find('input[name="wpProQuiz_captchaPrefix"]').val(), //points: 99, //results.comp.points, // LD v2.4.3 Calculated on server results: results, //p_nonce: results.comp.p_nonce, // LD v2.4.3 Calculated on server //totalPoints:config.globalPoints, // LD v2.4.3 Calculated on server timespent:timespent }, function(json) { $addToplistMessage.text(json.text); if(json.clear) { $addBox.hide(); plugin.methode.updateToplist(); } else { $addBox.show(); } if(json.captcha) { $addBox.find('.wpProQuiz_captchaImg').attr('src', json.captcha.img); $addBox.find('input[name="wpProQuiz_captchaPrefix"]').val(json.captcha.code); $addBox.find('input[name="wpProQuiz_captcha"]').val(''); } }); }, updateToplist: function() { if(typeof(wpProQuiz_fetchToplist) == "function") { wpProQuiz_fetchToplist(); } }, registerSolved: function() { // Free Input field $e.find('.wpProQuiz_questionInput[type="text"]').change(function(e) { var $this = $(this); var $p = $this.parents('.wpProQuiz_listItem'); var s = false; if($this.val() != '') { s = true; } $e.trigger({type: 'questionSolved', values: {item: $p, index: $p.index(), solved: s}}); }); // Single Choice field $e.find('.wpProQuiz_questionList[data-type="single"] .wpProQuiz_questionInput, .wpProQuiz_questionList[data-type="assessment_answer"] .wpProQuiz_questionInput').change(function(e) { var $this = $(this); var $p = $this.parents('.wpProQuiz_listItem'); var s = this.checked; $e.trigger({type: 'questionSolved', values: {item: $p, index: $p.index(), solved: s}}); }); // Cloze field $e.find('.wpProQuiz_cloze input').change(function() { var $this = $(this); var $p = $this.parents('.wpProQuiz_listItem'); var s = true; $p.find('.wpProQuiz_cloze input').each(function() { if($(this).val() == '') { s = false; return false; } }); $e.trigger({type: 'questionSolved', values: {item: $p, index: $p.index(), solved: s}}); }); // ?? field $e.find('.wpProQuiz_questionList[data-type="multiple"] .wpProQuiz_questionInput').change(function(e) { var $this = $(this); var $p = $this.parents('.wpProQuiz_listItem'); var c = 0; $p.find('.wpProQuiz_questionList[data-type="multiple"] .wpProQuiz_questionInput').each(function(e) { if(this.checked) c++; }); $e.trigger({type: 'questionSolved', values: {item: $p, index: $p.index(), solved: (c) ? true : false}}); }); // Essay textarea field. For Essay file uploads look into uploadFile() function $e.find('.wpProQuiz_questionList[data-type="essay"] textarea.wpProQuiz_questionEssay').change(function(e) { var $this = $(this); var $p = $this.parents('.wpProQuiz_listItem'); var s = false; if($this.val() != '') { s = true; } $e.trigger({type: 'questionSolved', values: {item: $p, index: $p.index(), solved: s}}); }); }, loadQuizDataAjax: function(quizStart) { plugin.methode.ajax({ action: 'wp_pro_quiz_admin_ajax', func: 'quizLoadData', data: { quizId: config.quizId, quiz : config.quiz, quiz_nonce: config.quiz_nonce, } }, function(json) { config.globalPoints = json.globalPoints; config.catPoints = json.catPoints; config.json = json.json; globalElements.quiz.remove(); $e.find('.wpProQuiz_quizAnker').after(json.content); $('table.wpProQuiz_toplistTable caption span.wpProQuiz_max_points').html(config.globalPoints); //Reinit globalElements globalElements = { back: $e.find('input[name="back"]'), next: $e.find(globalNames.next), quiz: $e.find('.wpProQuiz_quiz'), questionList: $e.find('.wpProQuiz_list'), results: $e.find('.wpProQuiz_results'), sending: $e.find('.wpProQuiz_sending'), quizStartPage: $e.find('.wpProQuiz_text'), timelimit: $e.find('.wpProQuiz_time_limit'), toplistShowInButton: $e.find('.wpProQuiz_toplistShowInButton'), listItems: $() }; plugin.methode.initQuiz(); if(quizStart) plugin.methode.startQuiz(true); // load script to show player for ajax content var data = json.content; var audiotag = data.search("wp-audio-shortcode"); var videotag = data.search("wp-video-shortcode"); if(audiotag != '-1' || videotag != '-1') { $.getScript(json.site_url+"/wp-includes/js/mediaelement/mediaelement-and-player.min.js"); $.getScript(json.site_url+"/wp-includes/js/mediaelement/wp-mediaelement.js"); $("<link/>", { rel: "stylesheet", type: "text/css", href: json.site_url+"/wp-includes/js/mediaelement/mediaelementplayer.min.css"}).appendTo("head"); } }); }, nextQuestionClicked: function() { var $questionList = currentQuestion.find(globalNames.questionList); var data = config.json[$questionList.data('question_id')]; // Within the following logic. If the question type is 'sort_answer' there is a chance // the sortable answers will be displayed in the correct order. In that case the user will click // the next button. // The trigger to set the question was answered is normally a function of the sort/drag action // by the user. So we need to set the question answered flag in the case the Quiz summary is enabled. if (data.type == 'sort_answer') { var question_index = currentQuestion.index(); if ( typeof quizSolved[question_index] === 'undefined') { $e.trigger({type: 'questionSolved', values: {item: currentQuestion, index: question_index, solved: true}}); } } if ( bitOptions.forcingQuestionSolve && !quizSolved[currentQuestion.index()] && ( bitOptions.quizSummeryHide || !bitOptions.reviewQustion ) ) { // Would really like to do something more stylized instead of a simple alert popup. yuk! alert(WpProQuizGlobal.questionNotSolved); return false; } plugin.methode.nextQuestion(); }, initQuiz: function() { //if (config.ld_script_debug == true) { // console.log('in initQuiz'); //} plugin.methode.setClozeStyle(); plugin.methode.registerSolved(); globalElements.next.click(plugin.methode.nextQuestionClicked); globalElements.back.click(function() { plugin.methode.prevQuestion(); }); $e.find(globalNames.check).click(function() { if(bitOptions.forcingQuestionSolve && !quizSolved[currentQuestion.index()] && (bitOptions.quizSummeryHide || !bitOptions.reviewQustion)) { alert(WpProQuizGlobal.questionNotSolved); return false; } plugin.methode.checkQuestion(); }); $e.find('input[name="checkSingle"]').click(function() { // First get all the questions... list = globalElements.questionList.children(); if (list != null) { list.each(function() { var $this = $(this); var $questionList = $this.find(globalNames.questionList); var question_id = $questionList.data('question_id'); var data = config.json[$questionList.data('question_id')]; // Within the following logic. If the question type is 'sort_answer' there is a chance // the sortable answers will be displayed in the correct order. In that case the user will click // the next button. // The trigger to set the question was answered is normally a function of the sort/drag action // by the user. So we need to set the question answered flag in the case the Quiz summary is enabled. if (data.type == 'sort_answer') { //var question_index = $this.index(); //if ( typeof quizSolved[question_index] === 'undefined') { $e.trigger({type: 'questionSolved', values: {item: $this, index: $this.index(), solved: true}}); //} } }); } if (bitOptions.forcingQuestionSolve && (bitOptions.quizSummeryHide || !bitOptions.reviewQustion)) { for(var i = 0, c = $e.find('.wpProQuiz_listItem').length; i < c; i++) { if(!quizSolved[i]) { alert(WpProQuizGlobal.questionsNotSolved); return false; } } } plugin.methode.showQuizSummary(); }); $e.find('input[name="tip"]').click(plugin.methode.showTip); $e.find('input[name="skip"]').click(plugin.methode.skipQuestion); $e.find('input[name="wpProQuiz_pageLeft"]').click(function() { plugin.methode.showSinglePage(currentPage-1); plugin.methode.setupMatrixSortHeights(); }); $e.find('input[name="wpProQuiz_pageRight"]').click(function() { plugin.methode.showSinglePage(currentPage+1); plugin.methode.setupMatrixSortHeights(); }); $e.find('input[id^="uploadEssaySubmit"]').click(plugin.methode.uploadFile); // Added in LD v2.4 to allow external notification when quiz init happens. $e.trigger('learndash-quiz-init'); }, // Setup the Cookie specific to the Quiz ID. CookieInit: function() { if (config.timelimitcookie == 0) return; cookie_name = 'ld_' + config.quizId + '_quiz_responses'; // Comment out to force clear cookie on init. //jQuery.cookie(cookie_name, ''); cookie_value = jQuery.cookie(cookie_name); if ((cookie_value == '') || (cookie_value == undefined)) { cookie_value = {}; } else { cookie_value = JSON.parse(cookie_value); } //if (config.ld_script_debug == true) { // console.log('CookieInit: cookie_name[%o] cookie_value[%o]', cookie_name, cookie_value); //} plugin.methode.CookieSetResponses(); plugin.methode.CookieResponseTimer(); }, CookieDelete: function() { if (config.timelimitcookie == 0) { //if (config.ld_script_debug == true) { // console.log('CookieDelete: config.timelimitcookie[%o]', config.timelimitcookie); //} return; } cookie_name = 'ld_' + config.quizId + '_quiz_responses'; //if (config.ld_script_debug == true) { // console.log('CookieDelete: cookie_name[%o]', cookie_name); //} jQuery.cookie(cookie_name, ''); }, CookieProcessQuestionResponse: function(list) { if (list != null) { list.each(function() { var $this = $(this); var question_index = $this.index(); var $questionList = $this.find(globalNames.questionList); var question_id = $questionList.data('question_id'); var data = config.json[$questionList.data('question_id')]; var name = data.type; if(data.type == 'single' || data.type == 'multiple') { name = 'singleMulti'; } var question_response = readResponses(name, data, $this, $questionList, false); plugin.methode.CookieSaveResponse(question_id, question_index, data.type, question_response); }); } }, // Save the answer(response) to the cookie. This is called from 'checkQuestion' and cookie timer functions. CookieSaveResponse: function(question_id, question_index, question_type, question_response) { if (config.timelimitcookie == 0) { return; } // set the value cookie_value[question_id] = {'index': question_index, 'value': question_response['response'], 'type': question_type}; // store the values. // Calculate the cookie date to expire var cookie_expire_date = new Date(); cookie_expire_date.setTime(cookie_expire_date.getTime() + (config.timelimitcookie * 1000)); jQuery.cookie(cookie_name, JSON.stringify(cookie_value), { expires:cookie_expire_date }); }, // The cookie timer loops every 5 seconds to save the last response from the user. // This only effect Essay questions as there is some current logic where once // 'readResponses' is called the question is locked. CookieResponseTimer: function() { if (config.timelimitcookie == 0) return; /* var list = null; var poll_interval = 5; // If mode is 3 we are display ALL questions. So we do this on an interval of 60 seconds. if (config.mode == 3) { list = globalElements.questionList.children(); var poll_interval = 60; } else { if (currentQuestion != null) { list = currentQuestion; } } if (list != null) { if (config.ld_script_debug == true) { console.log('CookieResponseTimer: liist[%o] ', list); } plugin.methode.CookieProcessQuestionResponse( list ); } setTimeout(function() { plugin.methode.CookieResponseTimer(); }, poll_interval*1000); */ // Hook into the 'questionSolved' triggered event. This is much better than // a timer to grab the answer values. With the event trigger we only process the // single question when the user makes a change. $e.bind('questionSolved', function(e) { //if (config.ld_script_debug == true) { // console.log('CookieResponseTimer: e.values[%o]', e.values); //} plugin.methode.CookieProcessQuestionResponse( e.values.item ); }); }, // Load the Cookie (if present) and sets the values of the Quiz questions to the cookie saved value CookieSetResponses: function() { if (config.timelimitcookie == 0) return; if (( cookie_value == undefined ) || ( !Object.keys(cookie_value).length )) { return; } var list = globalElements.questionList.children() list.each(function() { var $this = $(this); var $questionList = $this.find(globalNames.questionList); var form_question_id = $questionList.data('question_id'); if (cookie_value[form_question_id] != undefined) { var cookie_question_data = cookie_value[form_question_id]; var form_question_data = config.json[$questionList.data('question_id')]; if (form_question_data.type === cookie_question_data.type) { //if (config.ld_script_debug == true) { // console.log('CookieSetResponses: form_question_data[%o] cookie_question_data.value[%o]', form_question_data, cookie_question_data.value); //} setResponse(form_question_data, cookie_question_data.value, $this, $questionList); } } }); return; }, setupMatrixSortHeights: function ( ) { /** Here we have to do all the questions because the current logic when using X questions * per page doesn't allow that information. */ $('li.wpProQuiz_listItem', globalElements.questionList).each(function (idx, questionItem) { var question_type = $(questionItem).data('type'); if ('matrix_sort_answer' === question_type) { // On the draggable items get the items max height and set the parent ul to that. var sortitems_height = 0; $('ul.wpProQuiz_sortStringList li', questionItem).each(function (idx, el) { var el_height = $(el).outerHeight(); if (el_height > sortitems_height) { sortitems_height = el_height; } }); if (sortitems_height > 0) { $('ul.wpProQuiz_sortStringList', questionItem).css('min-height', sortitems_height); } $('ul.wpProQuiz_maxtrixSortCriterion', questionItem).each(function (idx, el) { var parent_td = $(el).parent('td'); if (typeof parent_td !== 'undefined') { var parent_td_height = $(parent_td).height(); $(el).css('height', parent_td_height); $(el).css('min-height', parent_td_height); } }); } }); }, }; /** * @memberOf plugin */ plugin.preInit = function() { plugin.methode.parseBitOptions(); reviewBox.init(); $e.find('input[name="startQuiz"]').click(function() { plugin.methode.startQuiz(); return false; }); /* $e.find('input[name="viewUserQuizStatistics"]').click(function() { plugin.methode.viewUserQuizStatistics(this); return false; }); */ if(bitOptions.checkBeforeStart && !bitOptions.preview) { plugin.methode.checkQuizLock(); } $e.find('input[name="reShowQuestion"]').click(function() { plugin.methode.showQustionList(); }); $e.find('input[name="restartQuiz"]').click(function() { plugin.methode.restartQuiz(); }); $e.find('input[name="review"]').click(plugin.methode.reviewQuestion); $e.find('input[name="wpProQuiz_toplistAdd"]').click(plugin.methode.addToplist); $e.find('input[name="quizSummary"]').click(plugin.methode.showQuizSummary); $e.find('input[name="endQuizSummary"]').click(function() { if(bitOptions.forcingQuestionSolve) { // First get all the questions... list = globalElements.questionList.children(); if (list != null) { list.each(function() { var $this = $(this); var $questionList = $this.find(globalNames.questionList); var question_id = $questionList.data('question_id'); var data = config.json[$questionList.data('question_id')]; // Within the following logic. If the question type is 'sort_answer' there is a chance // the sortable answers will be displayed in the correct order. In that case the user will click // the next button. // The trigger to set the question was answered is normally a function of the sort/drag action // by the user. So we need to set the question answered flag in the case the Quiz summary is enabled. if (data.type == 'sort_answer') { var question_index = $this.index(); if ( typeof quizSolved[question_index] === 'undefined') { $e.trigger({type: 'questionSolved', values: {item: $this, index: question_index, solved: true}}); } } }); } for(var i = 0, c = $e.find('.wpProQuiz_listItem').length; i < c; i++) { if(!quizSolved[i]) { alert(WpProQuizGlobal.questionsNotSolved); return false; } } } if(bitOptions.formActivated && config.formPos == formPosConst.END && !formClass.checkForm()) return; plugin.methode.finishQuiz(); }); $e.find('input[name="endInfopage"]').click(function() { if(formClass.checkForm()) plugin.methode.finishQuiz(); }); $e.find('input[name="showToplist"]').click(function() { globalElements.quiz.hide(); globalElements.toplistShowInButton.toggle(); }); $e.bind('questionSolved', plugin.methode.questionSolved); if(!bitOptions.maxShowQuestion) { plugin.methode.initQuiz(); } if(bitOptions.autoStart) plugin.methode.startQuiz(); }; plugin.preInit(); }; $.fn.wpProQuizFront = function(options) { return this.each(function() { if(undefined == $(this).data('wpProQuizFront')) { $(this).data('wpProQuizFront', new $.wpProQuizFront(this, options)); } }); }; })(jQuery); js/wpProQuiz_admin.min.js 0000666 00000136370 15214236625 0011454 0 ustar 00 jQuery(document).ready(function(e){function t(){function t(t){""!=t&&(e(t).css("float","none"),e(t).css("visibility","visible"),e(t).show())}function a(t){""!=t&&(e(t).hide(),e(t).css("visibility","hidden"))}function n(t){""!=t&&e(t).show().fadeOut(1500)}var o=this;o={displayChecked:function(e,t,i,a){var n=i?!e.checked:e.checked;a?n?t.attr("disabled","disabled"):t.removeAttr("disabled"):n?t.show():t.hide()},isEmpty:function(t){return t=e.trim(t),!t||0===t.length},isNumber:function(t){return t=e.trim(t),!o.isEmpty(t)&&!isNaN(t)},getMceContent:function(t){if("undefined"==typeof tinymce||null==typeof tinymce||void 0===tinymce.editors)return e("#"+t).val();var i=tinymce.editors[t];return null==i||i.isHidden()?e("#"+t).val():i.getContent()},ajaxPost:function(t,i,a){var n={action:"wp_pro_quiz_admin_ajax",func:t,data:i};e.post(ajaxurl,n,a,"json")}};var r=function(){e(".wpProQuiz_tab_wrapper a").click(function(){var t=e(this),i=t.data("tab"),a=t.siblings(".button-primary").removeClass("button-primary").addClass("button-secondary");return t.removeClass("button-secondary").addClass("button-primary"),e(a.data("tab")).hide("fast"),e(i).show("fast"),e(document).trigger({type:"changeTab",tabId:i}),!1})},c={gobalSettings:function(){var i={categoryDelete:function(i){var r={categoryId:i};t(".categorySpinner"),o.ajaxPost("categoryDelete",r,function(t){t.err||(a(".categorySpinner"),n(".categoryDeleteUpdate"),e('select[name="category"] option[value="'+i+'"]').remove(),e('select[name="category"]').change())})},categoryEdit:function(i,r){var c={categoryId:i,categoryName:e.trim(r)};o.isEmpty(r)?alert(wpProQuizLocalize.category_no_name):(t(".categorySpinner"),o.ajaxPost("categoryEdit",c,function(t){t.err||(a(".categorySpinner"),n(".categoryEditUpdate"),e('select[name="category"] option[value="'+i+'"]').text(c.categoryName),e('select[name="category"]').val(""),e('select[name="category"]').change())}))},changeTimeFormat:function(t,i){"0"!=i.val()&&e('input[name="'+t+'"]').val(i.val())},templateDelete:function(i,r){var c={templateId:i,type:r};t(r?".templateQuestionSpinner":".templateQuizSpinner"),o.ajaxPost("templateDelete",c,function(t){t.err||(r?(a(".templateQuestionSpinner"),n(".templateQuestionDeleteUpdate"),e('select[name="templateQuestion"] option[value="'+i+'"]').remove(),e('select[name="templateQuestion"]').val(""),e('select[name="templateQuestion"]').change()):(a(".templateQuizSpinner"),n(".templateQuizDeleteUpdate"),e('select[name="templateQuiz"] option[value="'+i+'"]').remove(),e('select[name="templateQuiz"]').val(""),e('select[name="templateQuiz"]').change()))})},templateEdit:function(i,r,c){if(o.isEmpty(r))alert(wpProQuizLocalize.category_no_name);else{var s={templateId:i,name:e.trim(r),type:c};t(c?".templateQuestionSpinner":".templateQuizSpinner"),o.ajaxPost("templateEdit",s,function(t){t.err||(c?(a(".templateQuestionSpinner"),n(".templateQuestionEditUpdate"),e('select[name="templateQuestion"] option[value="'+i+'"]').text(s.name),e('select[name="templateQuestion"]').val(""),e('select[name="templateQuestion"]').change()):(a(".templateQuizSpinner"),n(".templateQuizEditUpdate"),e('select[name="templateQuiz"] option[value="'+i+'"]').text(s.name),e('select[name="templateQuiz"]').val(""),e('select[name="templateQuiz"]').change()))})}}},r=function(){e('select[name="category"]').change(function(){""!=e(this).val()?e('input[name="categoryEditText"]').val(e("option:selected",this).text()):e('input[name="categoryEditText"]').val("")}),e('input[name="categoryDelete"]').click(function(){var t=e('select[name="category"] option:selected').val();""!=t&&i.categoryDelete(t)}),e('input[name="categoryEdit"]').click(function(){var t=e('select[name="category"] option:selected').val();if(""!=t){var a=e('input[name="categoryEditText"]').val();i.categoryEdit(t,a)}}),e('select[name="templateQuiz"]').change(function(){""!=e(this).val()?e('input[name="templateQuizEditText"]').val(e("option:selected",this).text()):e('input[name="templateQuizEditText"]').val("")}),e('input[name="templateQuizEdit"]').click(function(){var t=e('select[name="templateQuiz"] option:selected').val();if(""!=t){var a=e('input[name="templateQuizEditText"]').val();i.templateEdit(t,a,0)}}),e('input[name="templateQuizDelete"]').click(function(){var t=e('select[name="templateQuiz"] option:selected').val();""!=t&&i.templateDelete(t,0)}),e('select[name="templateQuestion"]').change(function(){""!=e(this).val()?e('input[name="templateQuestionEditText"]').val(e("option:selected",this).text()):e('input[name="templateQuestionEditText"]').val("")}),e('input[name="templateQuestionEdit"]').click(function(){var t=e('select[name="templateQuestion"] option:selected').val();if(""!=t){var a=e('input[name="templateQuestionEditText"]').val();i.templateEdit(t,a,1)}}),e('input[name="templateQuestionDelete"]').click(function(){var t=e('select[name="templateQuestion"] option:selected').val();""!=t&&i.templateDelete(t,1)}),e("#statistic_time_format_select").change(function(){i.changeTimeFormat("statisticTimeFormat",e(this))}),e(document).bind("changeTab",function(t){switch(e("#problemInfo").hide("fast"),t.tabId){case"#problemContent":e("#problemInfo").show("fast")}})};r()},questionEdit:function(){var t=this,i=(e.noop(),{answerChildren:e(".answer_felder > div"),pointsModus:e('input[name="answerPointsActivated"]'),gPoints:e('input[name="points"]')});t={generateArrayIndex:function(){var t=e('input[name="answerType"]:checked').val();t="single"==t||"multiple"==t?"classic_answer":t,e(".answerList").each(function(){var i=e(this).parent().attr("class");e(this).children().each(function(a,n){e(this).find('[name^="answerData"]').each(function(){var e=this.name,n=e.search(/\](\[\w+\])+$/),o=t==i?a:"none";n>0&&(this.name="answerData["+o+e.substring(n,e.length))})})})},globalValidate:function(){if("undefined"!==typenow&&"sfwd-question"==typenow){if(o.isEmpty(o.getMceContent("content")))return alert(wpProQuizLocalize.no_question_msg),!1}else if(o.isEmpty(o.getMceContent("question")))return alert(wpProQuizLocalize.no_question_msg),!1;if(i.pointsModus.is(":checked")){if("free_answer"==e('input[name="answerType"]:checked').val())return alert(wpProQuizLocalize.dif_points),!1}else{var t=i.gPoints.val();if(!o.isNumber(t)||t<1)return alert(wpProQuizLocalize.no_nummber_points),!1}return!0},answerRemove:function(){var t=e(this).parent();return t.parent().children().length>1?t.remove():alert(wpProQuizLocalize.no_delete_answer),!1},addCategory:function(){var t=e.trim(e('input[name="categoryAdd"]').val());if(!o.isEmpty(t)){var i={categoryName:t};o.ajaxPost("categoryAdd",i,function(t){if(t.err)e("#categoryMsgBox").text(t.err).show("fast").delay(2e3).hide("fast");else{var i=e(document.createElement("option")).val(t.categoryId).text(t.categoryName).attr("selected","selected");e('select[name="category"]').append(i).change()}})}},addMediaClick:function(){var t,i=e(this).closest("li"),a=i.find('input[name="answerData[][html]"]:eq(0)'),n=i.find(".wpProQuiz_text:eq(0)");void 0===t?(t=wp.media.frames.media_upload_frame=wp.media({frame:"select",library:{type:["image","audio","video"]},multiple:!1}),t.on("select",function(){var e=t.state().get("selection").first().toJSON();"image"===e.type&&(n.val(n.val()+'<img src="'+e.url+'" alt="'+e.alt+'" />'),a.attr("checked",!0)),"audio"===e.type&&(n.val(n.val()+'[audio src="'+e.url+'"][/audio]'),a.attr("checked",!0)),"video"===e.type&&(n.val(n.val()+'[video src="'+e.url+'"][/video]'),a.attr("checked",!0))}),t.open()):t.open()}};var a={classic_answer:function(){var t=0,a=0,n=0;return e(".classic_answer .answerList").children().each(function(){var i=e(this);if(!o.isEmpty(i.find('textarea[name="answerData[][answer]"]').val())){t++,i.find('input[name="answerData[][correct]"]:checked').length&&a++;var r=i.find('input[name="answerData[][points]"]').val();o.isNumber(r)&&r>=0&&n++}}),t?a||e('input[name="disableCorrect"]').is(":checked")&&e('input[name="answerPointsDiffModusActivated"]').is(":checked")&&e('input[name="answerPointsActivated"]').is(":checked")&&"single"==e('input[name="answerType"]:checked').val()?n==t||!i.pointsModus.is(":checked")||(alert(wpProQuizLocalize.no_nummber_points_new),!1):(alert(wpProQuizLocalize.no_correct_msg),!1):(alert(wpProQuizLocalize.no_answer_msg),!1)},free_answer:function(){return!o.isEmpty(e('.free_answer textarea[name="answerData[][answer]"]').val())||(alert(wpProQuizLocalize.no_answer_msg),!1)},cloze_answer:function(){return!o.isEmpty(o.getMceContent("cloze"))||(alert(wpProQuizLocalize.no_answer_msg),!1)},sort_answer:function(){var t=0,a=0;return e(".sort_answer .answerList").children().each(function(){var i=e(this);if(!o.isEmpty(i.find('textarea[name="answerData[][answer]"]').val())){t++;var n=i.find('input[name="answerData[][points]"]').val();o.isNumber(n)&&n>=0&&a++}}),t?a==t||!i.pointsModus.is(":checked")||(alert(wpProQuizLocalize.no_nummber_points_new),!1):(alert(wpProQuizLocalize.no_answer_msg),!1)},matrix_sort_answer:function(){var t=0,a=0,n=!0,r=0;return e(".matrix_sort_answer .answerList").children().each(function(){var i=e(this),c=i.find('input[name="answerData[][points]"]').val();o.isEmpty(i.find('textarea[name="answerData[][answer]"]').val())?o.isEmpty(i.find('textarea[name="answerData[][sort_string]"]').val())||(r++,o.isNumber(c)&&c>=0&&a++):(t++,r++,o.isEmpty(i.find('textarea[name="answerData[][sort_string]"]').val())&&(n=!1),o.isNumber(c)&&c>=0&&a++)}),t?n?a==r||!i.pointsModus.is(":checked")||(alert(wpProQuizLocalize.no_nummber_points_new),!1):(alert(wpProQuizLocalize.no_sort_element_criterion),!1):(alert(wpProQuizLocalize.no_answer_msg),!1)},assessment_answer:function(){return!o.isEmpty(o.getMceContent("assessment"))||(alert(wpProQuizLocalize.no_answer_msg),!1)}},n=function(){e("#wpProQuiz_tip").change(function(){o.displayChecked(this,e("#wpProQuiz_tipBox"))}).change(),e("#wpProQuiz_correctSameText").change(function(){o.displayChecked(this,e("#wpProQuiz_incorrectMassageBox"),!0),o.displayChecked(this,e("#learndash_question_message_incorrect_answer"),!0)}),e('input[name="answerType"]').click(function(){i.answerChildren.hide();var t=this.value;if("single"==t?("undefined"!==typenow&&"sfwd-question"==typenow?e("#learndash_question_single_choice_options").show():e("#singleChoiceOptions").show(),e('input[name="disableCorrect"]').change()):("undefined"!==typenow&&"sfwd-question"==typenow?e("#learndash_question_single_choice_options").hide():e("#singleChoiceOptions").hide(),e(".classic_answer .wpProQuiz_classCorrect").parent().parent().show()),"single"==t||"multiple"==t){var n="single"==t?"radio":"checkbox";t="classic_answer",e(".wpProQuiz_classCorrect").each(function(){e("<input type="+n+" />").attr({name:this.name,value:this.value,checked:this.checked}).addClass("wpProQuiz_classCorrect wpProQuiz_checkbox").insertBefore(this)}).remove()}"essay"==t?(e('input[name="answerPointsActivated"]').attr("checked",!1),e('input[name="showPointsInBox"]').attr("checked",!1),e('input[name="points"]').attr("disabled",!1),e("#wpProQuiz_answerPointsActivated").hide(),e("#wpProQuiz_correctMessageBox").hide(),e("#learndash_question_message_correct_answer").hide(),e('input[name="correctSameText"]').attr("checked",!1),e('textarea[name="correctMsg"]').val(""),e("#wpProQuiz_incorrectMassageBox").hide(),e("#learndash_question_message_incorrect_answer").hide(),e('textarea[name="incorrectMsg"]').val(""),e("#wpProQuiz_showPointsBox").hide()):(e("#wpProQuiz_answerPointsActivated").show(),e("#wpProQuiz_correctMessageBox").show(),e("#learndash_question_message_correct_answer").show(),e("#wpProQuiz_incorrectMassageBox").show(),e("#learndash_question_message_incorrect_answer").show()),null!=a[t]?a[t]:e.noop(),e("."+t).show()}),e('input[name="answerType"]:checked').click(),e("#wpProQuiz_correctSameText").change(),e(".deleteAnswer").click(t.answerRemove),e(".addAnswer").click(function(){var i=e(this).attr("data-default-value");null==i&&(i=0);var a=e(this).siblings("ul"),n=a.find("li:eq(0)").clone();return n.find(".wpProQuiz_checkbox").removeAttr("checked"),n.find(".wpProQuiz_text").val(""),n.find(".wpProQuiz_points").val(i),n.find(".deleteAnswer").click(t.answerRemove),n.find(".addMedia").click(t.addMediaClick),n.appendTo(a),!1}),e(".sort_answer ul, .classic_answer ul, .matrix_sort_answer ul").sortable({handle:".wpProQuiz_move"}),e("#saveQuestion").click(function(){return!!t.globalValidate()&&(t.generateArrayIndex(),!0)}),e("#publish").click(function(){return!!t.globalValidate()&&(t.generateArrayIndex(),!0)}),e("#save-post").click(function(){return!!t.globalValidate()&&(t.generateArrayIndex(),!0)}),e(i.pointsModus).change(function(){o.displayChecked(this,e(".wpProQuiz_answerPoints")),o.displayChecked(this,e("#wpProQuiz_showPointsBox")),o.displayChecked(this,i.gPoints,!1,!0),o.displayChecked(this,e('input[name="answerPointsDiffModusActivated"]'),!0,!0),this.checked?(e('input[name="answerPointsDiffModusActivated"]').change(),e('input[name="disableCorrect"]').change()):(e(".classic_answer .wpProQuiz_classCorrect").parent().parent().show(),e('input[name="disableCorrect"]').attr("disabled","disabled"))}).change(),e('select[name="category"]').change(function(){var t=e(this),i=e("#categoryAddBox").hide();"-1"==t.val()&&i.show()}).change(),e("#categoryAddBtn").click(function(){t.addCategory()}),e(".addMedia").click(t.addMediaClick),e('input[name="answerPointsDiffModusActivated"]').change(function(){o.displayChecked(this,e('input[name="disableCorrect"]'),!0,!0),this.checked?e('input[name="disableCorrect"]').change():e(".classic_answer .wpProQuiz_classCorrect").parent().parent().show()}).change(),e('input[name="disableCorrect"]').change(function(){o.displayChecked(this,e(".classic_answer .wpProQuiz_classCorrect").parent().parent(),!0)}).change(),e("#clickPointDia").click(function(){return e(".pointDia").toggle("fast"),!1}),e('input[name="template"]').click(function(i){if("0"==e('select[name="templateSaveList"]').val()&&o.isEmpty(e('input[name="templateName"]').val()))return alert(wpProQuizLocalize.temploate_no_name),i.preventDefault(),!1;t.generateArrayIndex()}),e('select[name="templateSaveList"]').change(function(){var t=e('input[name="templateName"]');"0"==e(this).val()?t.show():t.hide()}).change()},r=function(){i.answerChildren.hide(),n()};r()},statistic:function(){var t=this,i=e("#quizId").val(),a="users",n={currentPage:e("#wpProQuiz_currentPage"),pageLeft:e("#wpProQuiz_pageLeft"),pageRight:e("#wpProQuiz_pageRight"),testSelect:e("#testSelect")};t={loadStatistic:function(e,t){var i={userId:e};o.ajaxPost("statisticLoad",i,function(e){})},loadUsersStatistic:function(){var a=e("#userSelect").val(),n={userId:a,quizId:i,testId:e("#testSelect").val()};t.toggleLoadBox(!1),o.ajaxPost("statisticLoad",n,function(i){e.each(i.question,function(){var i=e("#wpProQuiz_tr_"+this.questionId);t.setStatisticData(i,this)}),e.each(i.category,function(i,a){var n=e("#wpProQuiz_ctr_"+i);t.setStatisticData(n,a)}),e("#testSelect option:gt(0)").remove();var a=e("#testSelect");e.each(i.tests,function(){var t=e(document.createElement("option"));t.val(this.id),t.text(this.date),i.testId==this.id&&t.attr("selected",!0),a.append(t)}),t.parseFormData(i.formData),t.toggleLoadBox(!0)})},loadUsersStatistic_:function(a,n){var r={userId:a,quizId:i,testId:n};t.toggleLoadBox(!1),o.ajaxPost("statisticLoad",r,function(i){e.each(i.question,function(){var i=e("#wpProQuiz_tr_"+this.questionId);t.setStatisticData(i,this)}),e.each(i.category,function(i,a){var n=e("#wpProQuiz_ctr_"+i);t.setStatisticData(n,a)}),e("#testSelect option:gt(0)").remove();var o=e("#testSelect");e.each(i.tests,function(){var t=e(document.createElement("option"));t.val(this.id),t.text(this.date),i.testId==this.id&&t.attr("selected",!0),o.append(t)}),t.parseFormData(i.formData),e("#userSelect").val(a),e("#testSelect").val(n),t.toggleLoadBox(!0)})},parseFormData:function(t){var i=e("#wpProQuiz_form_box");null!=t?(e.each(t,function(t,i){e("#form_id_"+t).text(i)}),i.show()):i.hide()},setStatisticData:function(e,t){e.find(".wpProQuiz_cCorrect").text(t.correct),e.find(".wpProQuiz_cIncorrect").text(t.incorrect),e.find(".wpProQuiz_cTip").text(t.hint),e.find(".wpProQuiz_cPoints").text(t.points),e.find(".wpProQuiz_cResult").text(t.result),e.find(".wpProQuiz_cTime").text(t.questionTime),e.find(".wpProQuiz_cCreateTime").text(t.date)},toggleLoadBox:function(t){var i=e("#wpProQuiz_loadData"),a=e("#wpProQuiz_content");t?(i.hide(),a.show()):(a.hide(),i.show())},reset:function(a){var r=e("#userSelect").val();if(confirm(wpProQuizLocalize.reset_statistics_msg)){var c={quizId:i,userId:r,testId:n.testSelect.val(),type:a};t.toggleLoadBox(!1),o.ajaxPost("statisticReset",c,function(){t.loadUsersStatistic()})}},loadStatisticOverview:function(a){var r={quizId:i,pageLimit:e("#wpProQuiz_pageLimit").val(),onlyCompleted:Number(e("#wpProQuiz_onlyCompleted").is(":checked")),page:n.currentPage.val(),nav:Number(a)};t.toggleLoadBox(!1),o.ajaxPost("statisticLoadOverview",r,function(i){var a=e("#wpProQuiz_statistics_overview_data"),n=a.children(),o=n.first().clone();n.slice(1).remove(),e.each(i.items,function(){var i=o.clone();t.setStatisticData(i,this),i.find("a").text(this.userName).data("userId",this.userId).click(function(){return e("#userSelect").val(e(this).data("userId")),e("#wpProQuiz_typeUser").click(),!1}),i.show().appendTo(a)}),o.remove(),t.toggleLoadBox(!0),null!=i.page&&t.handleNav(i.page)})},handleNav:function(i){for(var a=e("#wpProQuiz_currentPage").empty(),n=1;n<=i;n++)e(document.createElement("option")).val(n).text(n).appendTo(a);t.checkNavBar()},checkNavBar:function(){var e=n.currentPage.val();1==e?n.pageLeft.hide():n.pageLeft.show(),e==n.currentPage.children().length?n.pageRight.hide():n.pageRight.show()},refresh:function(){"users"==a?t.loadUsersStatistic():"formOverview"==a?t.loadFormsOverview(!0):t.loadStatisticOverview(!0)},loadFormsOverview:function(a){var n={quizId:i,pageLimit:e("#wpProQuiz_fromPageLimit").val(),onlyUser:e("#wpProQuiz_formUser").val(),page:e("#wpProQuiz_formCurrentPage").val(),nav:Number(a)};t.toggleLoadBox(!1),o.ajaxPost("statisticLoadFormOverview",n,function(i){var a=e("#wpProQuiz_statistics_form_data"),n=a.children(),o=n.first().clone();n.slice(1).remove(),e.each(i.items,function(){var i=o.clone();t.setStatisticData(i,this),i.find("a").text(this.userName).data("userId",this.userId).data("testId",this.testId).click(function(){return t.switchTabOnLoad("users"),t.loadUsersStatistic_(e(this).data("userId"),e(this).data("testId")),!1}),i.show().appendTo(a)}),o.remove(),t.toggleLoadBox(!0),null!=i.page&&t.handleFormNav(i.page)})},handleFormNav:function(i){for(var a=e("#wpProQuiz_formCurrentPage").empty(),n=1;n<=i;n++)e(document.createElement("option")).val(n).text(n).appendTo(a);t.checkFormNavBar()},checkFormNavBar:function(){var t=e("#wpProQuiz_formCurrentPage").val();1==t?e("#wpProQuiz_formPageLeft").hide():e("#wpProQuiz_formPageLeft").show(),t==e("#wpProQuiz_formCurrentPage").children().length?e("#wpProQuiz_formPageRight").hide():e("#wpProQuiz_formPageRight").show()},switchTabOnLoad:function(t){e(".wpProQuiz_tab").removeClass("button-primary").addClass("button-secondary"),e(".wpProQuiz_tabContent").hide();var i=e("#wpProQuiz_typeOverview");"users"==t?(a="users",e("#wpProQuiz_tabUsers").show(),i=e("#wpProQuiz_typeUser")):"formOverview"==t?(a="formOverview",e("#wpProQuiz_tabFormOverview").show(),i=e("#wpProQuiz_typeForm")):(a="overview",e("#wpProQuiz_tabOverview").show()),i.removeClass("button-secondary").addClass("button-primary")}};var r=function(){e("#userSelect, #testSelect").change(function(){t.loadUsersStatistic()}),e(".wpProQuiz_update").click(function(){t.refresh()}),e("#wpProQuiz_reset").click(function(){t.reset(0)}),e("#wpProQuiz_resetUser").click(function(){t.reset(1)}),e(".wpProQuiz_resetComplete").click(function(){t.reset(2)}),e(".wpProQuiz_tab").click(function(){var i=e(this);return e(".wpProQuiz_tab").removeClass("button-primary").addClass("button-secondary"),i.removeClass("button-secondary").addClass("button-primary"),e(".wpProQuiz_tabContent").hide(),"wpProQuiz_typeUser"==i.attr("id")?(a="users",e("#wpProQuiz_tabUsers").show(),t.loadUsersStatistic()):"wpProQuiz_typeForm"==i.attr("id")?(a="formOverview",e("#wpProQuiz_tabFormOverview").show(),t.loadFormsOverview(!0)):(a="overview",e("#wpProQuiz_tabOverview").show(),t.loadStatisticOverview(!0)),!1}),e("#wpProQuiz_onlyCompleted").change(function(){n.currentPage.val(1),t.loadStatisticOverview(!0)}),e("#wpProQuiz_pageLimit").change(function(){n.currentPage.val(1),t.loadStatisticOverview(!0)}),n.pageLeft.click(function(){n.currentPage.val(Number(n.currentPage.val())-1),t.loadStatisticOverview(!1),t.checkNavBar()}),n.pageRight.click(function(){n.currentPage.val(Number(n.currentPage.val())+1),t.loadStatisticOverview(!1),t.checkNavBar()}),n.currentPage.change(function(){t.loadStatisticOverview(!1),t.checkNavBar()}),e("#wpProQuiz_formUser, #wpProQuiz_fromPageLimit").change(function(){e("#wpProQuiz_formCurrentPage").val(1),t.loadFormsOverview(!0)}),e("#wpProQuiz_formPageLeft").click(function(){e("#wpProQuiz_formCurrentPage").val(Number(n.currentPage.val())-1),t.loadFormsOverview(!1),t.checkFormNavBar()}),e("#wpProQuiz_formPageRight").click(function(){e("#wpProQuiz_formCurrentPage").val(Number(n.currentPage.val())+1),t.loadFormsOverview(!1),t.checkFormNavBar()}),e("#wpProQuiz_formCurrentPage").change(function(){t.loadFormsOverview(!1),t.checkFormNavBar()}),t.loadUsersStatistic()};r()},statisticNew:function(){var t=e("#quizId").val(),a=null,n=null,r={data:{quizId:t,users:-1,pageLimit:100,dateFrom:0,dateTo:0,generateNav:0},changeFilter:function(){var t=function(e){var t=e.datepicker("getDate");return null===t?0:t.getTime()/1e3};return e.extend(this.data,{users:e("#wpProQuiz_historyUser").val(),pageLimit:e("#wpProQuiz_historyPageLimit").val(),dateFrom:t(e("#datepickerFrom")),dateTo:t(e("#datepickerTo")),generateNav:1}),this.data}},c={data:{pageLimit:100,onlyCompleted:0,generateNav:0,quizId:t},changeFilter:function(){e.extend(this.data,{pageLimit:e("#wpProQuiz_overviewPageLimit").val(),onlyCompleted:Number(e("#wpProQuiz_overviewOnlyCompleted").is(":checked")),generateNav:1})}},s={deleteUserStatistic:function(i,a){if(!confirm(wpProQuizLocalize.reset_statistics_msg))return!1;var n={refId:i,userId:a,quizId:t,type:0};o.ajaxPost("statisticResetNew",n,function(){e("#wpProQuiz_user_overlay").hide(),r.changeFilter(),u.loadHistoryAjax(),c.changeFilter(),u.loadOverviewAjax()})},deleteAll:function(){if(!confirm(wpProQuizLocalize.reset_statistics_msg))return!1;var e={quizId:t,type:1};o.ajaxPost("statisticResetNew",e,function(){r.changeFilter(),u.loadHistoryAjax(),c.changeFilter(),u.loadOverviewAjax()})}},u={loadHistoryAjax:function(){var t=e.extend({page:r.data.generateNav?1:a.getCurrentPage()},r.data);u.loadBox(!0);var i=e("#wpProQuiz_historyLoadContext").hide();o.ajaxPost("statisticLoadHistory",t,function(t){i.html(t.html).show(),t.navi&&a.setNumPage(t.navi),r.data.generateNav=0,i.find(".user_statistic").click(function(){return u.loadUserAjax(0,e(this).data("ref_id"),!1),!1}),i.find(".wpProQuiz_delete").click(function(){return s.deleteUserStatistic(e(this).parents("tr").find(".user_statistic").data("ref_id"),0),!1}),u.loadBox(!1)})},loadUserAjax:function(i,a,n){e("#wpProQuiz_user_overlay, #wpProQuiz_loadUserData").show();var r=e("#wpProQuiz_user_content").hide(),c={quizId:t,userId:i,refId:a,avg:Number(n)};o.ajaxPost("statisticLoadUser",c,function(t){r.html(t.html),r.find(".wpProQuiz_update").click(function(){return u.loadUserAjax(i,a,n),!1}),r.find("#wpProQuiz_resetUserStatistic").click(function(){s.deleteUserStatistic(a,i)}),r.find(".statistic_data").click(function(){return e(this).parents("tr").next().toggle("fast"),!1}),e("#wpProQuiz_loadUserData").hide(),jQuery("body").trigger("learndash-statistics-contentchanged"),r.show()})},loadBox:function(t,i){t?e("#wpProQuiz_loadDataHistory").show():e("#wpProQuiz_loadDataHistory").hide()},loadOverviewAjax:function(){var t=e.extend({page:c.data.generateNav?1:n.getCurrentPage()},c.data);e("#wpProQuiz_loadDataOverview").show();var i=e("#wpProQuiz_overviewLoadContext").hide();o.ajaxPost("statisticLoadOverviewNew",t,function(t){i.html(t.html).show(),t.navi&&n.setNumPage(t.navi),c.data.generateNav=0,i.find(".user_statistic").click(function(){return u.loadUserAjax(e(this).data("user_id"),0,!0),!1}),i.find(".wpProQuiz_delete").click(function(){return s.deleteUserStatistic(0,e(this).parents("tr").find(".user_statistic").data("user_id")),!1}),e("#wpProQuiz_loadDataOverview").hide()})}},l=function(){a=new i(e("#historyNavigation"),{onChange:function(){u.loadHistoryAjax()}}),n=new i(e("#overviewNavigation"),{onChange:function(){u.loadOverviewAjax()}}),(e("#datepickerFrom").length||e("#datepickerTo").length)&&(e(document).on("DOMNodeInserted",function(t){"ui-datepicker-div"==t.target.id&&e("#ui-datepicker-div").addClass("learndash-datepicker")}),e("#datepickerFrom").datepicker({closeText:wpProQuizLocalize.closeText,currentText:wpProQuizLocalize.currentText,monthNames:wpProQuizLocalize.monthNames,monthNamesShort:wpProQuizLocalize.monthNamesShort,dayNames:wpProQuizLocalize.dayNames,dayNamesShort:wpProQuizLocalize.dayNamesShort,dayNamesMin:wpProQuizLocalize.dayNamesMin,dateFormat:wpProQuizLocalize.dateFormat,firstDay:wpProQuizLocalize.firstDay,changeMonth:!0,onClose:function(t){e("#datepickerTo").datepicker("option","minDate",t)}}),e("#datepickerTo").datepicker({closeText:wpProQuizLocalize.closeText,currentText:wpProQuizLocalize.currentText,monthNames:wpProQuizLocalize.monthNames,monthNamesShort:wpProQuizLocalize.monthNamesShort,dayNames:wpProQuizLocalize.dayNames,dayNamesShort:wpProQuizLocalize.dayNamesShort,dayNamesMin:wpProQuizLocalize.dayNamesMin,dateFormat:wpProQuizLocalize.dateFormat,firstDay:wpProQuizLocalize.firstDay,changeMonth:!0,onClose:function(t){e("#datepickerFrom").datepicker("option","maxDate",t)}})),e("#filter").click(function(){r.changeFilter(),u.loadHistoryAjax()}),e("#wpProQuiz_overlay_close").click(function(){e("#wpProQuiz_user_overlay").hide()}),e("#wpProQuiz_tabHistory .wpProQuiz_update").click(function(){return r.changeFilter(),u.loadHistoryAjax(),!1}),e("#wpProQuiz_tabOverview .wpProQuiz_update").click(function(){return c.changeFilter(),u.loadOverviewAjax(),!1}),e(".wpProQuiz_resetComplete").click(function(){return s.deleteAll(),!1}),e("#overviewFilter").click(function(){c.changeFilter(),u.loadOverviewAjax()}),r.changeFilter(),u.loadHistoryAjax(),c.changeFilter(),u.loadOverviewAjax()};l()}},s=function(){r();var t=e.noop;e(".wpProQuiz_questionEdit").length||e("body.learndash-post-type.sfwd-question").length?t=c.questionEdit:e(".wpProQuiz_globalSettings").length?t=c.gobalSettings:e(".wpProQuiz_statistics").length?t=c.statistic:e(".wpProQuiz_statisticsNew").length&&(t=c.statisticNew),t(),e(".wpProQuiz_demoImgBox a").mouseover(function(t){var i=e(this),a=e(document).width(),n=i.siblings().outerWidth(!0);if(t.pageX+n>a){var o=a-(t.pageX+n+30);e(this).next().css("left",o+"px")}e(this).next().show()}).mouseout(function(){e(this).next().hide()}).click(function(){return!1})};s()}function i(t,i){var a={onChange:null},n={contain:null,pageLeft:null,pageRight:null,currentPage:null},o=function(){var e=n.currentPage.children().length,t=Number(n.currentPage.val());n.pageLeft.hide(),n.pageRight.hide(),t>1&&n.pageLeft.show(),t+1<=e&&n.pageRight.show()},r=function(){e.extend(n,{contain:t,pageLeft:t.find(".navigationLeft"),pageRight:t.find(".navigationRight"),currentPage:t.find(".navigationCurrentPage")}),e.extend(a,i),n.pageLeft.click(function(){n.currentPage.val(Number(n.currentPage.val())-1),o(),a.onChange&&a.onChange(n.currentPage.val())}),n.pageRight.click(function(){n.currentPage.val(Number(n.currentPage.val())+1),o(),a.onChange&&a.onChange(n.currentPage.val())}),n.currentPage.change(function(){o(),a.onChange&&a.onChange(n.currentPage.val())})};this.getCurrentPage=function(){return n.currentPage.val()},this.setNumPage=function(t){n.currentPage.empty();for(var i=1;i<=t;i++)e(document.createElement("option")).val(i).text(i).appendTo(n.currentPage);o()},r()}e.fn.wpProQuiz_preview=function(){var t={openPreview:function(t){window.open(e(t).attr("href"),"wpProQuizPreview","width=900,height=900")}},i=function(){e(".wpProQuiz_prview").click(function(e){t.openPreview(this),e.preventDefault()})};i()},e.fn.wpProQuiz_quizOverall=function(){var t={changeExport:function(t){$input=e(t),$export=e(".wpProQuiz_exportList"),$ul=$export.find("ul").first(),$export.find("li").remove(),e('input[name="exportItems"]').each(function(){if($this=e(this),this.checked){var t=$this.parent().parent().find(".wpProQuiz_quizName a:eq(0)").text();e("<li>"+t+"</li>").appendTo($ul)}})},startExport:function(){return $ele=e('input[name="exportItems"]:checked'),$ele.length<1?(alert(wpProQuizLocalize.no_selected_quiz),!1):($hidden=e("#exportHidden"),$hidden.html(""),e('input[name="exportItems"]').each(function(){$this=e(this),this.checked&&e('<input type="hidden" value="'+this.value+'" name="exportIds[]">').appendTo($hidden)}),!0)}},i=function(){e(".wpProQuiz_delete").click(function(e){var t=confirm(wpProQuizLocalize.delete_msg);return!!t||(e.preventDefault(),!1)}),e(".wpProQuiz_import").click(function(t){t.preventDefault(),e(".wpProQuiz_importList").toggle("fast"),e(".wpProQuiz_exportList").hide(),e(".wpProQuiz_exportCheck").hide()}),e(".wpProQuiz_export").click(function(t){t.preventDefault(),e(".wpProQuiz_exportList").toggle("fast"),e(".wpProQuiz_exportCheck").toggle("fast"),e(".wpProQuiz_importList").hide()}),e('input[name="exportItems"]').change(function(){t.changeExport(this)}),e('input[name="exportItemsAll"]').change(function(){var t=e('input[name="exportItems"]');this.checked?t.attr("checked",!0):t.attr("checked",!1),t.change()}),e("#exportStart").click(function(e){t.startExport()||e.preventDefault()})};i()},e.fn.wpProQuiz_questionOverall=function(){var t={saveSort:function(){var i={action:"wp_pro_quiz_update_sort",sort:t.parseSortArray()},a=window.location.pathname+window.location.search,n=a.replace("admin.php","admin-ajax.php")+"&action=save_sort";e.post(n,i,function(t){e("#sortMsg").show(400).delay(1e3).hide(400)})},parseSortArray:function(){var t=new Array;return e("tbody tr").each(function(){t.push(this.id.replace("wpProQuiz_questionId_",""))}),t},sortUpdate:function(t,i){e(".wpProQuiz_questionOverall tbody").children().each(function(){$t=e(this).children().first().text(e(this).index()+1)})},loadQuestionCopy:function(){var t=e("#questionCopySelect"),i=window.location.pathname+window.location.search,a=i.replace("admin.php","admin-ajax.php")+"&action=load_question",n={action:"wp_pro_quiz_load_question",excludeId:1};t.hide(),t.empty(),e("#loadDataImg").show(),e.post(a,n,function(i){e.each(i,function(i,a){var n=e(document.createElement("optgroup"));n.attr("label",a.name),e.each(a.question,function(t,i){e(document.createElement("option")).val(i.id).text(i.name).appendTo(n)}),t.append(n)}),e("#loadDataImg").hide(),t.show()},"json")}},i=function(){e(".wp-list-table tbody").sortable({handle:".wpProQuiz_move",update:t.sortUpdate}),e(".wpProQuiz_delete").click(function(e){var t=confirm(wpProQuizLocalize.delete_msg);return!!t||(e.preventDefault(),!1)}),e("#wpProQuiz_saveSort").click(function(e){e.preventDefault(),t.saveSort()}),e("#wpProQuiz_questionCopy").click(function(i){var a=e(".wpProQuiz_questionCopy");a.is(":visible")?a.hide():(a.show(),t.loadQuestionCopy()),i.preventDefault()})};i()},e.fn.wpProQuiz_quizEdit=function(){var t={addResult:function(){e("#resultList").children().each(function(){if("none"==e(this).css("display")){var t=e(this),i=t.find('textarea[name="resultTextGrade[text][]"]'),a=i.attr("id"),n=!0;return t.find('input[name="resultTextGrade[prozent][]"]').val("1"),t.find('input[name="resultTextGrade[activ][]"]').val("1").keyup(),"undefined"==typeof tinymce||null==tinymce.editors[a]||tinymce.editors[a].isHidden()||(n=!1),null==switchEditors||n||(switchEditors.go(a,"toggle"),switchEditors.go(a,"toggle")), "undefined"!=typeof tinymce&&null!=tinymce.editors[a]?tinymce.editors[a].setContent(""):i.val(""),"undefined"==typeof tinymce||null==tinymce.editors[a]||n||tinyMCE.execCommand("mceRemoveControl",!1,a),t.parent().children(":visible").last().after(t),"undefined"==typeof tinymce||null==tinymce.editors[a]||n||tinyMCE.execCommand("mceAddControl",!1,a),e(this).show(),null==switchEditors||n||switchEditors.go(a,"toggle"),!1}})},deleteResult:function(t){e(t).parent().parent().hide(),e(t).siblings('input[name="resultTextGrade[activ][]"]').val("0")},changeResult:function(i){var a=e(i);return t.validResultInput(a.val())?(a.siblings(".resultProzent").text(a.val()),a.removeAttr("style"),!0):(a.css("background-color","#FF9696"),!1)},validResultInput:function(e){return!i(e)&&(e=e.replace(/\,/,"."),!isNaN(e)&&Number(e)<=100&&Number(e)>=0&&(null==e.match(/\./)||e.split(".")[1].length<3))},validInput:function(){if(i(e("#wpProQuiz_title").val()))return alert(wpProQuizLocalize.no_title_msg),!1;var a="";if(a="undefined"==typeof tinymce||null==tinymce.editors.text||tinymce.editors.text.isHidden()?e('textarea[name="text"]').val():tinymce.editors.text.getContent(),i(a))return alert(wpProQuizLocalize.no_quiz_start_msg),!1;if(e("#wpProQuiz_resultGradeEnabled:checked").length){var n=!0;if(e("#resultList").children().each(function(){if(e(this).is(":visible")&&!t.validResultInput(e(this).find('input[name="resultTextGrade[prozent][]"]').val()))return n=!1,!1}),!n)return alert(wpProQuizLocalize.fail_grade_result),!1}return!0},resetLock:function(){var t=window.location.pathname+window.location.search,i=t.replace("post.php","admin-ajax.php");i=i.replace("action=edit","action=reset_lock"),e.post(i,{action:"wp_pro_quiz_reset_lock"},function(t){e("#resetLockMsg").show("fast").delay(2e3).hide("fast")})},generateFormIds:function(){var t=0;e("#form_table tbody > tr").each(function(){e(this).find('[name^="form[]"]').each(function(){var i=e(this).attr("name").substr(6);e(this).attr("name","form["+t+"]"+i)}),++t})}},i=function(t){return t=e.trim(t),!t||0===t.length},a=function(){e("#statistics_on").change(function(){this.checked?(e("#statistics_ip_lock_tr").show(),e("#statistics_show_profile_tr").show()):(e("#statistics_ip_lock_tr").hide(),e("#statistics_show_profile_tr").hide())}),e(".addResult").click(function(){t.addResult()}),e(".deleteResult").click(function(e){t.deleteResult(this)}),e('input[name="resultTextGrade[prozent][]"]').keyup(function(e){t.changeResult(this)}).keydown(function(e){13==e.which&&e.preventDefault()}),e("#wpProQuiz_resultGradeEnabled").change(function(){this.checked?(e("#resultGrade").show(),e("#resultNormal").hide()):(e("#resultGrade").hide(),e("#resultNormal").show())}),window.postL10n?(e("#wpProQuiz_save,input[name=save]").click(function(i){t.generateFormIds(),e('select[name="prerequisiteList[]"] option').attr("selected","selected")}),e("#publish").click(function(){t.generateFormIds(),e('select[name="prerequisiteList[]"] option').attr("selected","selected")}),e("#save-post").click(function(){t.generateFormIds(),e('select[name="prerequisiteList[]"] option').attr("selected","selected")})):window.wp.data.subscribe(()=>{!0===window.wp.data.select("core/editor").isSavingPost()&&(t.generateFormIds(),e('select[name="prerequisiteList[]"] option').attr("selected","selected"))}),e('input[name="template"]').click(function(a){if("0"==e('select[name="templateSaveList"]').val()&&i(e('input[name="templateName"]').val()))return alert(wpProQuizLocalize.temploate_no_name),a.preventDefault(),!1;t.generateFormIds(),e('select[name="prerequisiteList[]"] option').attr("selected","selected")}),e('select[name="templateSaveList"]').change(function(){var t=e('input[name="templateName"]');"0"==e(this).val()?t.show():t.hide()}).change(),e('input[name="quizRunOnce"]').change(function(t){this.checked?(e("#wpProQuiz_quiz_run_once_type").show(),e('input[name="quizRunOnceType"]:checked').change()):e("#wpProQuiz_quiz_run_once_type").hide()}),e('input[name="quizRunOnceType"]').change(function(t){!this.checked||"1"!=this.value&&"3"!=this.value?e("#wpProQuiz_quiz_run_once_cookie").hide():e("#wpProQuiz_quiz_run_once_cookie").show()}),e('input[name="resetQuizLock"]').click(function(e){return t.resetLock(),!1}),e(".wpProQuiz_demoBox a").mouseover(function(t){var i=e(this),a=e(document).width(),n=i.siblings().outerWidth(!0);if(t.pageX+n>a){var o=a-(t.pageX+n+30);e(this).next().css("left",o+"px")}e(this).next().show()}).mouseout(function(){e(this).next().hide()}).click(function(){return!1}),e('input[name="showMaxQuestion"]').change(function(){this.checked?e("#wpProQuiz_showMaxBox").show():e("#wpProQuiz_showMaxBox").hide()}),e("#btnPrerequisiteAdd").click(function(){e('select[name="quizList"] option:selected').removeAttr("selected").appendTo('select[name="prerequisiteList[]"]')}),e("#btnPrerequisiteDelete").click(function(){e('select[name="prerequisiteList[]"] option:selected').removeAttr("selected").appendTo('select[name="quizList"]')}),e('input[name="prerequisite"]').change(function(){this.checked?e("#prerequisiteBox").show():e("#prerequisiteBox").hide()}).change(),e('input[name="toplistDataAddMultiple"]').change(function(){this.checked?e("#toplistDataAddBlockBox").show():e("#toplistDataAddBlockBox").hide()}).change(),e('input[name="toplistActivated"]').change(function(){this.checked?e("#toplistBox > tr:gt(0)").show():e("#toplistBox > tr:gt(0)").hide()}).change(),e('input[name="showReviewQuestion"]').change(function(){this.checked?e(".wpProQuiz_reviewQuestionOptions").show():e(".wpProQuiz_reviewQuestionOptions").hide()}).change(),e("#statistics_on").change(),e("#wpProQuiz_resultGradeEnabled").change(),e('input[name="quizRunOnce"]').change(),e('input[name="quizRunOnceType"]:checked').change(),e('input[name="showMaxQuestion"]').change(),e("#form_add").click(function(){e("#form_table tbody > tr:eq(0)").clone(!0).appendTo("#form_table tbody").show(),e('#form_table tbody tr:last input[type="text"]').focus()}),e('input[name="form_delete"]').click(function(){var t=e(this).parents("tr");"0"!=t.find('input[name="form[][form_id]"]').val()?(t.find('input[name="form[][form_delete]"]').val(1),t.hide()):t.remove()}),e("#form_table tbody").sortable({handle:".form_move",update:t.sortUpdate}),e(".form_move").click(function(){return!1}),e('select[name="form[][type]"]').change(function(){switch(Number(e(this).val())){case 7:case 8:e(this).siblings(".editDropDown").show();break;default:e(this).siblings(".editDropDown, .dropDownEditBox").hide()}}).change(),e(".editDropDown").click(function(){return e(".dropDownEditBox").not(e(this).siblings(".dropDownEditBox").toggle()).hide(),!1}),e(".dropDownEditBox input").click(function(){e(this).parent().hide()})};a()},e.fn.wpProQuiz_statistics=function(){var t="wpProQuiz_typeAnonymeUser",i=!0,a={loadStatistics:function(t){var i=window.location.pathname+window.location.search,n=i.replace("admin.php","admin-ajax.php")+"&action=load_statistics",o={action:"wp_pro_quiz_load_statistics",userId:t};e("#wpProQuiz_loadData").show(),e("#wpProQuiz_statistics_content, #wpProQuiz_statistics_overview").hide(),e.post(n,o,a.setStatistics,"json")},setStatistics:function(i){var a=e(".wpProQuiz_statistics_table"),n=a.find("tbody");if("wpProQuiz_typeOverview"!=t){var o=function(e,t,i){e.find(".wpProQuiz_cCorrect").text(t.cCorrect+" ("+t.pCorrect+"%)"),e.find(".wpProQuiz_cIncorrect").text(t.cIncorrect+" ("+t.pIncorrect+"%)"),e.find(".wpProQuiz_cTip").text(t.cTip),e.find(".wpProQuiz_cPoints").text(t.cPoints),1==i&&a.find(".wpProQuiz_cResult").text(t.result+"%")};o(a,i.clear,!1),e.each(i.items,function(e,t){o(n.find("#wpProQuiz_tr_"+t.id),t,!1)}),o(a.find("tfoot"),i.global,!0),e("#wpProQuiz_loadData").hide(),e("#wpProQuiz_statistics_content, .wpProQuiz_statistics_table").show()}},loadOverview:function(){e(".wpProQuiz_statistics_table, #wpProQuiz_statistics_content, #wpProQuiz_statistics_overview").hide(),e("#wpProQuiz_loadData").show();var n=window.location.pathname+window.location.search,o=n.replace("admin.php","admin-ajax.php")+"&action=load_statistics",r={action:"wp_pro_quiz_load_statistics",overview:!0,pageLimit:e("#wpProQuiz_pageLimit").val(),onlyCompleted:Number(e("#wpProQuiz_onlyCompleted").is(":checked")),page:e("#wpProQuiz_currentPage").val(),generatePageNav:Number(i)};e.post(o,r,function(n){if(e("#wpProQuiz_statistics_overview_data").empty(),"wpProQuiz_typeOverview"==t){var o=e('<tr><th><a href="#">---</a></th><th class="wpProQuiz_points">---</th><th class="wpProQuiz_cCorrect" style="color: green;">---</th><th class="wpProQuiz_cIncorrect" style="color: red;">---</th><th class="wpProQuiz_cTip">---</th><th class="wpProQuiz_cResult" style="font-weight: bold;">---</th></tr>');e.each(n.items,function(t,i){var a=o.clone();a.find("a").text(i.userName).data("userId",i.userId).click(function(){return e("#userSelect").val(e(this).data("userId")),e("#wpProQuiz_typeRegisteredUser").click(),!1}),i.completed?(a.find(".wpProQuiz_points").text(i.cPoints),a.find(".wpProQuiz_cCorrect").text(i.cCorrect+" ("+i.pCorrect+"%)"),a.find(".wpProQuiz_cIncorrect").text(i.cIncorrect+" ("+i.pIncorrect+"%)"),a.find(".wpProQuiz_cTip").text(i.cTip),a.find(".wpProQuiz_cResult").text(i.result+"%")):a.find("th").removeAttr("style"),e("#wpProQuiz_statistics_overview_data").append(a)}),null!=n.page&&(a.setPageNav(n.page),i=!1),e("#wpProQuiz_loadData").hide(),e("#wpProQuiz_statistics_overview").show()}},"json")},loadFormOverview:function(){e("#wpProQuiz_tabFormOverview").show()},changeTab:function(i){t=i,"wpProQuiz_typeRegisteredUser"==i?a.loadStatistics(e("#userSelect").val()):"wpProQuiz_typeAnonymeUser"==i?a.loadStatistics(0):"wpProQuiz_typeForm"==i?a.loadFormOverview():a.loadOverview()},resetStatistic:function(i){var n="wpProQuiz_typeRegisteredUser"==t?e("#userSelect").val():0,o=window.location.pathname+window.location.search,r=o.replace("admin.php","admin-ajax.php")+"&action=reset",c={action:"wp_pro_quiz_statistics",userId:n,complete:i};e.post(r,c,function(e){a.changeTab(t)})},setPageNav:function(t){t=Math.ceil(t/e("#wpProQuiz_pageLimit").val()),e("#wpProQuiz_currentPage").empty();for(var i=1;i<=t;i++)e(document.createElement("option")).val(i).text(i).appendTo(e("#wpProQuiz_currentPage"));e("#wpProQuiz_pageLeft, #wpProQuiz_pageRight").hide(),e("#wpProQuiz_currentPage option").length>1&&e("#wpProQuiz_pageRight").show()}},n=function(){e(".wpProQuiz_tab").click(function(t){var i=e(this);return!i.hasClass("button-primary")&&("wpProQuiz_typeRegisteredUser"==i.attr("id")?e("#wpProQuiz_userBox").show():e("#wpProQuiz_userBox").hide(),e(".wpProQuiz_tab").removeClass("button-primary").addClass("button-secondary"),i.removeClass("button-secondary").addClass("button-primary"),a.changeTab(i.attr("id")),!1)}),e("#userSelect").change(function(){a.changeTab("wpProQuiz_typeRegisteredUser")}),e(".wpProQuiz_update").click(function(){return a.changeTab(t),!1}),e("#wpProQuiz_reset").click(function(){var e=confirm(wpProQuizLocalize.reset_statistics_msg);return e&&a.resetStatistic(!1),!1}),e(".wpProQuiz_resetComplete").click(function(){var e=confirm(wpProQuizLocalize.reset_statistics_msg);return e&&a.resetStatistic(!0),!1}),e("#wpProQuiz_pageLimit, #wpProQuiz_onlyCompleted").change(function(){return e("#wpProQuiz_currentPage").val(0),i=!0,a.changeTab(t),!1}),e("#wpProQuiz_currentPage").change(function(){e("#wpProQuiz_pageLeft, #wpProQuiz_pageRight").hide(),1==e("#wpProQuiz_currentPage option").length||(e("#wpProQuiz_currentPage option:first-child:selected").length?e("#wpProQuiz_pageRight").show():e("#wpProQuiz_currentPage option:last-child:selected").length?e("#wpProQuiz_pageLeft").show():e("#wpProQuiz_pageLeft, #wpProQuiz_pageRight").show()),a.changeTab(t)}),e("#wpProQuiz_pageRight").click(function(){return e("#wpProQuiz_currentPage option:selected").next().attr("selected","selected"),e("#wpProQuiz_currentPage").change(),!1}),e("#wpProQuiz_pageLeft").click(function(){return e("#wpProQuiz_currentPage option:selected").prev().attr("selected","selected"),e("#wpProQuiz_currentPage").change(),!1}),a.changeTab("wpProQuiz_typeAnonymeUser")};n()},e.fn.wpProQuiz_toplist=function(){var t={sort:e("#wpProQuiz_sorting"),pageLimit:e("#wpProQuiz_pageLimit"),currentPage:e("#wpProQuiz_currentPage"),loadDataBox:e("#wpProQuiz_loadData"),pageLeft:e("#wpProQuiz_pageLeft"),pageRight:e("#wpProQuiz_pageRight"),dataBody:e("#wpProQuiz_toplistTable tbody"),rowClone:e("#wpProQuiz_toplistTable tbody tr:eq(0)").clone(),content:e("#wpProQuiz_content")},i={loadData:function(i){var a=window.location.pathname+window.location.search,n=a.replace("admin.php","admin-ajax.php")+"&action=load_toplist",o=this,r={action:"wp_pro_quiz_load_toplist",sort:t.sort.val(),limit:t.pageLimit.val(),page:t.currentPage.val()};null!=i&&e.extend(r,i),t.loadDataBox.show(),t.content.hide(),e.post(n,r,function(e){o.handleDataRequest(e.data),null!=e.nav&&o.handleNav(e.nav),t.loadDataBox.hide(),t.content.show()},"json")},handleNav:function(i){t.currentPage.empty();for(var a=1;a<=i.pages;a++)e(document.createElement("option")).val(a).text(a).appendTo(t.currentPage);this.checkNav()},handleDataRequest:function(i){var a=this;t.dataBody.empty(),e.each(i,function(e,i){var a=t.rowClone.clone().children();a.eq(0).children().val(i.id),a.eq(1).find("strong").text(i.name),a.eq(1).find(".inline_editUsername").val(i.name),a.eq(2).find(".wpProQuiz_email").text(i.email),a.eq(2).find("input").val(i.email),a.eq(3).text(i.type),a.eq(4).text(i.date),a.eq(5).text(i.points),a.eq(6).text(i.result),a.parent().show().appendTo(t.dataBody)}),i.length||e(document.createElement("td")).attr("colspan","7").text(wpProQuizLocalize.no_data_available).css({"font-weight":"bold","text-align":"center",padding:"5px"}).appendTo(document.createElement("tr")).appendTo(t.dataBody),e(".wpProQuiz_delete").click(function(){if(confirm(wpProQuizLocalize.confirm_delete_entry)){var t=new Array(e(this).closest("tr").find('input[name="checkedData[]"]').val());a.loadData({a:"delete",toplistIds:t})}return!1}),e(".wpProQuiz_edit").click(function(){var t=e(this).closest("tr");return t.find(".row-actions").hide(),t.find(".inline-edit").show(),t.find(".wpProQuiz_username, .wpProQuiz_email").hide(),t.find(".inline_editUsername, .inline_editEmail").show(),!1}),e(".inline_editSave").click(function(){var t=e(this).closest("tr"),i=t.find(".inline_editUsername").val(),n=t.find(".inline_editEmail").val();return a.isEmpty(i)||a.isEmpty(n)?(alert(wpProQuizLocalize.not_all_fields_completed),!1):(a.loadData({a:"edit",toplistId:t.find('input[name="checkedData[]"]').val(),name:i,email:n}),!1)}),e(".inline_editCancel").click(function(){var t=e(this).closest("tr");return t.find(".row-actions").show(),t.find(".inline-edit").hide(),t.find(".wpProQuiz_username, .wpProQuiz_email").show(),t.find(".inline_editUsername, .inline_editEmail").hide(),t.find(".inline_editUsername").val(t.find(".wpProQuiz_username").text()),t.find(".inline_editEmail").val(t.find(".wpProQuiz_email").text()),!1})},checkNav:function(){var e=t.currentPage.val();1==e?t.pageLeft.hide():t.pageLeft.show(),e==t.currentPage.children().length?t.pageRight.hide():t.pageRight.show()},isEmpty:function(t){return t=e.trim(t),!t||0===t.length}},a=function(){t.sort.change(function(){i.loadData()}),t.pageLimit.change(function(){i.loadData({nav:1})}),t.currentPage.change(function(){i.checkNav(),i.loadData()}),t.pageLeft.click(function(){t.currentPage.val(Number(t.currentPage.val())-1),i.checkNav(),i.loadData()}),t.pageRight.click(function(){t.currentPage.val(Number(t.currentPage.val())+1),i.checkNav(),i.loadData()}),e("#wpProQuiz_deleteAll").click(function(){i.loadData({a:"deleteAll"})}),e("#wpProQuiz_action").click(function(){var t=e("#wpProQuiz_actionName").val();if("0"!=t){var a=e('input[name="checkedData[]"]:checked').map(function(){return e(this).val()}).get();i.loadData({a:t,toplistIds:a})}}),e("#wpProQuiz_checkedAll").change(function(){this.checked?e('input[name="checkedData[]"]').attr("checked","checked"):e('input[name="checkedData[]"]').removeAttr("checked","checked")}),i.loadData({nav:1})};a()},e(".wpProQuiz_quizOverall").length&&e(".wpProQuiz_quizOverall").wpProQuiz_preview(),e(".wpProQuiz_quizOverall").length&&e(".wpProQuiz_quizOverall").wpProQuiz_quizOverall(),e(".wpProQuiz_quizEdit").length&&e(".wpProQuiz_quizEdit").wpProQuiz_quizEdit(),e(".wpProQuiz_questionOverall").length&&e(".wpProQuiz_questionOverall").wpProQuiz_questionOverall(),e(".wpProQuiz_toplist").length&&e(".wpProQuiz_toplist").wpProQuiz_toplist(),t()}); js/jquery.cookie.js 0000666 00000006061 15214236625 0010322 0 ustar 00 /*! * jQuery Cookie Plugin v1.4.1 * https://github.com/carhartl/jquery-cookie * * Copyright 2013 Klaus Hartl * Released under the MIT license */ (function (factory) { if (typeof define === 'function' && define.amd) { // AMD define(['jquery'], factory); } else if (typeof exports === 'object') { // CommonJS factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function ($) { var pluses = /\+/g; function encode(s) { return config.raw ? s : encodeURIComponent(s); } function decode(s) { return config.raw ? s : decodeURIComponent(s); } function stringifyCookieValue(value) { return encode(config.json ? JSON.stringify(value) : String(value)); } function parseCookieValue(s) { if (s.indexOf('"') === 0) { // This is a quoted cookie as according to RFC2068, unescape... s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, '\\'); } try { // Replace server-side written pluses with spaces. // If we can't decode the cookie, ignore it, it's unusable. // If we can't parse the cookie, ignore it, it's unusable. s = decodeURIComponent(s.replace(pluses, ' ')); return config.json ? JSON.parse(s) : s; } catch(e) {} } function read(s, converter) { var value = config.raw ? s : parseCookieValue(s); return $.isFunction(converter) ? converter(value) : value; } var config = $.cookie = function (key, value, options) { // Write if (value !== undefined && !$.isFunction(value)) { options = $.extend({}, config.defaults, options); if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setTime(+t + days * 864e+5); } return (document.cookie = [ encode(key), '=', stringifyCookieValue(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // Read var result = key ? undefined : {}; // To prevent the for loop in the first place assign an empty array // in case there are no cookies at all. Also prevents odd result when // calling $.cookie(). var cookies = document.cookie ? document.cookie.split('; ') : []; for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); var name = decode(parts.shift()); var cookie = parts.join('='); if (key && key === name) { // If second argument (value) is a function it's a converter... result = read(cookie, value); break; } // Prevent storing a cookie that we couldn't decode. if (!key && (cookie = read(cookie)) !== undefined) { result[name] = cookie; } } return result; }; config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) === undefined) { return false; } // Must not alter options, thus extending a fresh object... $.cookie(key, '', $.extend({}, options, { expires: -1 })); return !$.cookie(key); }; })); js/wpProQuiz_admin.js 0000666 00000234031 15214236625 0010663 0 ustar 00 jQuery(document).ready(function($) { /** * @memberOf $.fn */ $.fn.wpProQuiz_preview = function() { var methods = { openPreview: function(obj) { window.open($(obj).attr('href'), 'wpProQuizPreview', 'width=900,height=900'); } }; var init = function() { $('.wpProQuiz_prview').click(function(e) { methods.openPreview(this); e.preventDefault(); }); }; init(); }; $.fn.wpProQuiz_quizOverall = function() { var methods = { changeExport: function(input) { $input = $(input); $export = $('.wpProQuiz_exportList'); $ul = $export.find('ul').first(); $export.find('li').remove(); $('input[name="exportItems"]').each(function() { $this = $(this); if(this.checked) { var text = $this.parent().parent().find('.wpProQuiz_quizName a:eq(0)').text(); $('<li>' + text + '</li>').appendTo($ul); } }); }, startExport: function() { $ele = $('input[name="exportItems"]:checked'); if($ele.length < 1) { alert(wpProQuizLocalize.no_selected_quiz); return false; } $hidden = $('#exportHidden'); $hidden.html(''); $('input[name="exportItems"]').each(function() { $this = $(this); if(this.checked) { $('<input type="hidden" value="'+ this.value +'" name="exportIds[]">').appendTo($hidden); } }); return true; } }; var init = function() { $('.wpProQuiz_delete').click(function(e) { var b = confirm(wpProQuizLocalize.delete_msg); if(!b) { e.preventDefault(); return false; } return true; }); $('.wpProQuiz_import').click(function(e) { e.preventDefault(); $('.wpProQuiz_importList').toggle('fast'); $('.wpProQuiz_exportList').hide(); $('.wpProQuiz_exportCheck').hide(); }); $('.wpProQuiz_export').click(function(e) { e.preventDefault(); $('.wpProQuiz_exportList').toggle('fast'); $('.wpProQuiz_exportCheck').toggle('fast'); $('.wpProQuiz_importList').hide(); }); $('input[name="exportItems"]').change(function() { methods.changeExport(this); }); $('input[name="exportItemsAll"]').change(function() { var $input = $('input[name="exportItems"]'); if(this.checked) $input.attr('checked', true); else $input.attr('checked', false); $input.change(); }); $('#exportStart').click(function(e) { if(!methods.startExport()) e.preventDefault(); }); }; init(); }; $.fn.wpProQuiz_questionOverall = function() { var methode = { saveSort: function() { var data = { action: 'wp_pro_quiz_update_sort', sort: methode.parseSortArray() }; var location = window.location.pathname + window.location.search; var url = location.replace('admin.php', 'admin-ajax.php') + '&action=save_sort'; $.post(url, data, function(response) { $('#sortMsg').show(400).delay(1000).hide(400); }); }, parseSortArray: function() { var array = new Array(); $('tbody tr').each(function() { array.push(this.id.replace('wpProQuiz_questionId_', '')); }); return array; }, sortUpdate: function(e, ui) { $('.wpProQuiz_questionOverall tbody').children().each(function() { $t = $(this).children().first().text($(this).index() + 1); }); }, loadQuestionCopy: function() { var list = $('#questionCopySelect'); var location = window.location.pathname + window.location.search; var url = location.replace('admin.php', 'admin-ajax.php') + '&action=load_question'; var data = { action: 'wp_pro_quiz_load_question', excludeId: 1 }; list.hide(); list.empty(); $('#loadDataImg').show(); $.post( url, data, function(json) { $.each(json, function(i, v) { var group = $(document.createElement('optgroup')); group.attr('label', v.name); $.each(v.question, function(qi, qv) { $(document.createElement('option')) .val(qv.id) .text(qv.name) .appendTo(group); }); list.append(group); }); $('#loadDataImg').hide(); list.show(); }, 'json' ); } }; var init = function() { $('.wp-list-table tbody').sortable({ handle: '.wpProQuiz_move', update: methode.sortUpdate }); $('.wpProQuiz_delete').click(function(e) { var b = confirm(wpProQuizLocalize.delete_msg); if(!b) { e.preventDefault(); return false; } return true; }); $('#wpProQuiz_saveSort').click(function(e) { e.preventDefault(); methode.saveSort(); }); $('#wpProQuiz_questionCopy').click(function(e) { var $this = $('.wpProQuiz_questionCopy'); if($this.is(':visible')) { $this.hide(); } else { $this.show(); methode.loadQuestionCopy(); } e.preventDefault(); }); }; init(); }; $.fn.wpProQuiz_quizEdit = function() { var methode = { addResult: function() { $('#resultList').children().each(function() { if($(this).css('display') == 'none') { //TODO rework var $this = $(this); var $text = $this.find('textarea[name="resultTextGrade[text][]"]'); var id = $text.attr('id'); var hidden = true; $this.find('input[name="resultTextGrade[prozent][]"]').val('1'); $this.find('input[name="resultTextGrade[activ][]"]').val('1').keyup(); if(typeof tinymce != "undefined" && tinymce.editors[id] != undefined && !tinymce.editors[id].isHidden()) { hidden = false; } if(switchEditors != undefined && !hidden) { switchEditors.go(id, 'toggle'); switchEditors.go(id, 'toggle'); } if(typeof tinymce != "undefined" && tinymce.editors[id] != undefined) { tinymce.editors[id].setContent(''); } else { $text.val(''); } if(typeof tinymce != "undefined" && tinymce.editors[id] != undefined && !hidden) { tinyMCE.execCommand('mceRemoveControl', false, id); } $this.parent().children(':visible').last().after($this); if(typeof tinymce != "undefined" && tinymce.editors[id] != undefined && !hidden) { tinyMCE.execCommand('mceAddControl', false, id); } $(this).show(); if(switchEditors != undefined && !hidden) { switchEditors.go(id, 'toggle'); } return false; } }); }, deleteResult: function(e) { $(e).parent().parent().hide(); $(e).siblings('input[name="resultTextGrade[activ][]"]').val('0'); }, changeResult: function(e) { var $this = $(e); if(methode.validResultInput($this.val())) { $this.siblings('.resultProzent').text($this.val()); $this.removeAttr('style'); return true; } $this.css('background-color', '#FF9696'); return false; }, validResultInput: function(input) { if(isEmpty(input)) return false; input = input.replace(/\,/, '.'); if(!isNaN(input) && Number(input) <= 100 && Number(input) >= 0) { if(input.match(/\./) != null) return input.split('.')[1].length < 3; return true; } return false; }, validInput: function() { if(isEmpty($('#wpProQuiz_title').val())) { alert(wpProQuizLocalize.no_title_msg); return false; } var text = ''; if(typeof tinymce != "undefined" && tinymce.editors.text != undefined && !tinymce.editors.text.isHidden()) { text = tinymce.editors.text.getContent(); } else { text = $('textarea[name="text"]').val(); } if(isEmpty(text)) { alert(wpProQuizLocalize.no_quiz_start_msg); return false; } if($('#wpProQuiz_resultGradeEnabled:checked').length) { var rCheck = true; $('#resultList').children().each(function() { if($(this).is(':visible')) { if(!methode.validResultInput($(this).find('input[name="resultTextGrade[prozent][]"]').val())) { rCheck = false; return false; } } }); if(!rCheck) { alert(wpProQuizLocalize.fail_grade_result); return false; } } return true; }, resetLock: function() { var location = window.location.pathname + window.location.search; var url = location.replace('post.php', 'admin-ajax.php'); url = url.replace('action=edit', 'action=reset_lock'); $.post(url, { action: 'wp_pro_quiz_reset_lock' }, function(data) { $('#resetLockMsg').show('fast').delay(2000).hide('fast'); }); }, generateFormIds: function() { var index = 0; $('#form_table tbody > tr').each(function() { $(this).find('[name^="form[]"]').each(function() { var newname = $(this).attr('name').substr(6); $(this).attr('name', 'form[' + index + ']' + newname); }); ++index; }); } }; var isEmpty = function(str) { str = $.trim(str); return (!str || 0 === str.length); }; var init = function() { $('#statistics_on').change(function() { if(this.checked) { $('#statistics_ip_lock_tr').show(); $('#statistics_show_profile_tr').show(); } else { $('#statistics_ip_lock_tr').hide(); $('#statistics_show_profile_tr').hide(); } }); $('.addResult').click(function() { methode.addResult(); }); $('.deleteResult').click(function (e) { methode.deleteResult(this); }); $('input[name="resultTextGrade[prozent][]"]').keyup(function(event) { methode.changeResult(this); }).keydown(function(event) { if(event.which == 13) { event.preventDefault(); } }); $('#wpProQuiz_resultGradeEnabled').change(function() { if(this.checked) { $('#resultGrade').show(); $('#resultNormal').hide(); } else { $('#resultGrade').hide(); $('#resultNormal').show(); } }); // Classic editor if ( window.postL10n ) { $('#wpProQuiz_save,input[name=save]').click(function(e) { /* if(!methode.validInput()) e.preventDefault(); else */ methode.generateFormIds(); $('select[name="prerequisiteList[]"] option').attr('selected', 'selected'); }); //$('#wpProQuiz_save,input[name=save]').click(function (e) { $('#publish').click(function () { /* if(!methode.validInput()) e.preventDefault(); else */ methode.generateFormIds(); $('select[name="prerequisiteList[]"] option').attr('selected', 'selected'); }); $('#save-post').click(function () { /* if(!methode.validInput()) e.preventDefault(); else */ methode.generateFormIds(); $('select[name="prerequisiteList[]"] option').attr('selected', 'selected'); }); } else { // Gutenberg window.wp.data.subscribe( () => { if ( true === window.wp.data.select( 'core/editor' ).isSavingPost() ) { methode.generateFormIds(); $('select[name="prerequisiteList[]"] option').attr('selected', 'selected'); } }); } $('input[name="template"]').click(function(e) { if($('select[name="templateSaveList"]').val() == '0') { if(isEmpty($('input[name="templateName"]').val())) { alert(wpProQuizLocalize.temploate_no_name); e.preventDefault(); return false; } } methode.generateFormIds(); $('select[name="prerequisiteList[]"] option').attr('selected', 'selected'); }); $('select[name="templateSaveList"]').change(function() { var $templateName = $('input[name="templateName"]'); if($(this).val() == '0') { $templateName.show(); } else { $templateName.hide(); } }).change(); $('input[name="quizRunOnce"]').change(function(e) { if(this.checked) { $('#wpProQuiz_quiz_run_once_type').show(); $('input[name="quizRunOnceType"]:checked').change(); } else { $('#wpProQuiz_quiz_run_once_type').hide(); } }); $('input[name="quizRunOnceType"]').change(function(e) { if(this.checked && (this.value == "1" || this.value == "3")) { $('#wpProQuiz_quiz_run_once_cookie').show(); } else { $('#wpProQuiz_quiz_run_once_cookie').hide(); } }); $('input[name="resetQuizLock"]').click(function(e) { methode.resetLock(); return false; }); $('.wpProQuiz_demoBox a').mouseover(function(e) { var $this = $(this); var d = $(document).width(); var img = $this.siblings().outerWidth(true); if(e.pageX + img > d) { var v = d - (e.pageX + img + 30); $(this).next().css('left', v + "px"); } $(this).next().show(); }).mouseout(function() { $(this).next().hide(); }).click(function() { return false; }); $('input[name="showMaxQuestion"]').change(function() { if(this.checked) { // $('input[name="statisticsOn"]').removeAttr('checked').attr('disabled', 'disabled').change(); $('#wpProQuiz_showMaxBox').show(); } else { // $('input[name="statisticsOn"]').removeAttr('disabled'); $('#wpProQuiz_showMaxBox').hide(); } }); $('#btnPrerequisiteAdd').click(function() { $('select[name="quizList"] option:selected').removeAttr('selected').appendTo('select[name="prerequisiteList[]"]'); }); $('#btnPrerequisiteDelete').click(function() { $('select[name="prerequisiteList[]"] option:selected').removeAttr('selected').appendTo('select[name="quizList"]'); }); $('input[name="prerequisite"]').change(function() { if(this.checked) $('#prerequisiteBox').show(); else $('#prerequisiteBox').hide(); }).change(); $('input[name="toplistDataAddMultiple"]').change(function() { if(this.checked) $('#toplistDataAddBlockBox').show(); else $('#toplistDataAddBlockBox').hide(); }).change(); $('input[name="toplistActivated"]').change(function() { if(this.checked) $('#toplistBox > tr:gt(0)').show(); else $('#toplistBox > tr:gt(0)').hide(); }).change(); $('input[name="showReviewQuestion"]').change(function() { if(this.checked) { $('.wpProQuiz_reviewQuestionOptions').show(); } else { $('.wpProQuiz_reviewQuestionOptions').hide(); } }).change(); $('#statistics_on').change(); $('#wpProQuiz_resultGradeEnabled').change(); $('input[name="quizRunOnce"]').change(); $('input[name="quizRunOnceType"]:checked').change(); $('input[name="showMaxQuestion"]').change(); $('#form_add').click(function() { $('#form_table tbody > tr:eq(0)').clone(true).appendTo('#form_table tbody').show(); $('#form_table tbody tr:last input[type="text"]').focus(); }); $('input[name="form_delete"]').click(function() { var con = $(this).parents('tr'); if(con.find('input[name="form[][form_id]"]').val() != "0") { con.find('input[name="form[][form_delete]"]').val(1); con.hide(); } else { con.remove(); } }); $('#form_table tbody').sortable({ handle: '.form_move', update: methode.sortUpdate }); $('.form_move').click(function() { return false; }); $('select[name="form[][type]"]').change(function() { switch (Number($(this).val())) { case 7: case 8: $(this).siblings('.editDropDown').show(); break; default: $(this).siblings('.editDropDown, .dropDownEditBox').hide(); break; } }).change(); $('.editDropDown').click(function() { $('.dropDownEditBox').not( $(this).siblings('.dropDownEditBox').toggle()) .hide(); return false; }); $('.dropDownEditBox input').click(function() { $(this).parent().hide(); }); }; init(); }; $.fn.wpProQuiz_statistics = function() { var currectTab = 'wpProQuiz_typeAnonymeUser'; var changePageNav = true; var methode = { loadStatistics: function(userId) { var location = window.location.pathname + window.location.search; var url = location.replace('admin.php', 'admin-ajax.php') + '&action=load_statistics'; var data = { action: 'wp_pro_quiz_load_statistics', userId: userId }; $('#wpProQuiz_loadData').show(); $('#wpProQuiz_statistics_content, #wpProQuiz_statistics_overview').hide(); $.post( url, data, methode.setStatistics, 'json' ); }, setStatistics: function(json) { var $table = $('.wpProQuiz_statistics_table'); var $tbody = $table.find('tbody'); if(currectTab == 'wpProQuiz_typeOverview') { return; } var setItem = function(i, j, r) { i.find('.wpProQuiz_cCorrect').text(j.cCorrect + ' (' + j.pCorrect + '%)'); i.find('.wpProQuiz_cIncorrect').text(j.cIncorrect + ' (' + j.pIncorrect + '%)'); i.find('.wpProQuiz_cTip').text(j.cTip); i.find('.wpProQuiz_cPoints').text(j.cPoints); if(r == true) { $table.find('.wpProQuiz_cResult').text(j.result + '%'); } }; setItem($table, json.clear, false); $.each(json.items, function(i, v) { setItem($tbody.find('#wpProQuiz_tr_' + v.id), v, false); }); setItem($table.find('tfoot'), json.global, true); $('#wpProQuiz_loadData').hide(); $('#wpProQuiz_statistics_content, .wpProQuiz_statistics_table').show(); }, loadOverview: function() { $('.wpProQuiz_statistics_table, #wpProQuiz_statistics_content, #wpProQuiz_statistics_overview').hide(); $('#wpProQuiz_loadData').show(); var location = window.location.pathname + window.location.search; var url = location.replace('admin.php', 'admin-ajax.php') + '&action=load_statistics'; var data = { action: 'wp_pro_quiz_load_statistics', overview: true, pageLimit: $('#wpProQuiz_pageLimit').val(), onlyCompleted: Number($('#wpProQuiz_onlyCompleted').is(':checked')), page: $('#wpProQuiz_currentPage').val(), generatePageNav: Number(changePageNav) }; $.post( url, data, function(json) { $('#wpProQuiz_statistics_overview_data').empty(); if(currectTab != 'wpProQuiz_typeOverview') { return; } var item = $( '<tr>' + '<th><a href="#">---</a></th>' + '<th class="wpProQuiz_points">---</th>' + '<th class="wpProQuiz_cCorrect" style="color: green;">---</th>' + '<th class="wpProQuiz_cIncorrect" style="color: red;">---</th>' + '<th class="wpProQuiz_cTip">---</th>' + '<th class="wpProQuiz_cResult" style="font-weight: bold;">---</th>' + '</tr>' ); $.each(json.items, function(i, v) { var d = item.clone(); d.find('a').text(v.userName).data('userId', v.userId).click(function() { $('#userSelect').val($(this).data('userId')); $('#wpProQuiz_typeRegisteredUser').click(); return false; }); if(v.completed) { d.find('.wpProQuiz_points').text(v.cPoints); d.find('.wpProQuiz_cCorrect').text(v.cCorrect + ' (' + v.pCorrect + '%)'); d.find('.wpProQuiz_cIncorrect').text(v.cIncorrect + ' (' + v.pIncorrect + '%)'); d.find('.wpProQuiz_cTip').text(v.cTip); d.find('.wpProQuiz_cResult').text(v.result + '%'); } else { d.find('th').removeAttr('style'); } $('#wpProQuiz_statistics_overview_data').append(d); }); if(json.page != undefined) { methode.setPageNav(json.page); changePageNav = false; } $('#wpProQuiz_loadData').hide(); $('#wpProQuiz_statistics_overview').show(); }, 'json' ); }, loadFormOverview: function() { $('#wpProQuiz_tabFormOverview').show(); }, changeTab: function(id) { currectTab = id; if(id == 'wpProQuiz_typeRegisteredUser') { methode.loadStatistics($('#userSelect').val()); } else if( id == 'wpProQuiz_typeAnonymeUser') { methode.loadStatistics(0); } else if(id == 'wpProQuiz_typeForm') { methode.loadFormOverview(); } else { methode.loadOverview(); } }, resetStatistic: function(complete) { var userId = (currectTab == 'wpProQuiz_typeRegisteredUser') ? $('#userSelect').val() : 0; var location = window.location.pathname + window.location.search; var url = location.replace('admin.php', 'admin-ajax.php') + '&action=reset'; var data = { action: 'wp_pro_quiz_statistics', userId: userId, 'complete': complete }; $.post(url, data, function(e) { methode.changeTab(currectTab); }); }, setPageNav: function(page) { page = Math.ceil(page / $('#wpProQuiz_pageLimit').val()); $('#wpProQuiz_currentPage').empty(); for(var i = 1; i <= page; i++) { $(document.createElement('option')) .val(i) .text(i) .appendTo($('#wpProQuiz_currentPage')); } $('#wpProQuiz_pageLeft, #wpProQuiz_pageRight').hide(); if($('#wpProQuiz_currentPage option').length > 1) { $('#wpProQuiz_pageRight').show(); } } }; var init = function() { $('.wpProQuiz_tab').click(function(e) { var $this = $(this); if($this.hasClass('button-primary')) { return false; } if($this.attr('id') == 'wpProQuiz_typeRegisteredUser') { $('#wpProQuiz_userBox').show(); } else { $('#wpProQuiz_userBox').hide(); } $('.wpProQuiz_tab').removeClass('button-primary').addClass('button-secondary'); $this.removeClass('button-secondary').addClass('button-primary'); methode.changeTab($this.attr('id')); return false; }); $('#userSelect').change(function() { methode.changeTab('wpProQuiz_typeRegisteredUser'); }); $('.wpProQuiz_update').click(function() { methode.changeTab(currectTab); return false; }); $('#wpProQuiz_reset').click(function() { var c =confirm(wpProQuizLocalize.reset_statistics_msg); if(c) { methode.resetStatistic(false); } return false; }); $('.wpProQuiz_resetComplete').click(function() { var c =confirm(wpProQuizLocalize.reset_statistics_msg); if(c) { methode.resetStatistic(true); } return false; }); $('#wpProQuiz_pageLimit, #wpProQuiz_onlyCompleted').change(function() { $('#wpProQuiz_currentPage').val(0); changePageNav = true; methode.changeTab(currectTab); return false; }); $('#wpProQuiz_currentPage').change(function() { $('#wpProQuiz_pageLeft, #wpProQuiz_pageRight').hide(); if($('#wpProQuiz_currentPage option').length == 1) { } else if($('#wpProQuiz_currentPage option:first-child:selected').length) { $('#wpProQuiz_pageRight').show(); } else if($('#wpProQuiz_currentPage option:last-child:selected').length) { $('#wpProQuiz_pageLeft').show(); }else { $('#wpProQuiz_pageLeft, #wpProQuiz_pageRight').show(); } methode.changeTab(currectTab); }); $('#wpProQuiz_pageRight').click(function() { $('#wpProQuiz_currentPage option:selected').next().attr('selected', 'selected'); $('#wpProQuiz_currentPage').change(); return false; }); $('#wpProQuiz_pageLeft').click(function() { $('#wpProQuiz_currentPage option:selected').prev().attr('selected', 'selected'); $('#wpProQuiz_currentPage').change(); return false; }); methode.changeTab('wpProQuiz_typeAnonymeUser'); }; init(); }; $.fn.wpProQuiz_toplist = function() { var elements = { sort: $('#wpProQuiz_sorting'), pageLimit: $('#wpProQuiz_pageLimit'), currentPage: $('#wpProQuiz_currentPage'), loadDataBox: $('#wpProQuiz_loadData'), pageLeft: $('#wpProQuiz_pageLeft'), pageRight: $('#wpProQuiz_pageRight'), dataBody: $('#wpProQuiz_toplistTable tbody'), rowClone: $('#wpProQuiz_toplistTable tbody tr:eq(0)').clone(), content: $('#wpProQuiz_content') }; var methods = { loadData: function(action) { var location = window.location.pathname + window.location.search; var url = location.replace('admin.php', 'admin-ajax.php') + '&action=load_toplist'; var th = this; var data = { action: 'wp_pro_quiz_load_toplist', sort: elements.sort.val(), limit: elements.pageLimit.val(), page: elements.currentPage.val() }; if(action != undefined) { $.extend(data, action); } elements.loadDataBox.show(); elements.content.hide(); $.post(url, data, function(json) { //methods.handleDataRequest(json.data); th.handleDataRequest(json.data); if(json.nav != undefined) { //methods.handleNav(json.nav); th.handleNav(json.nav); } elements.loadDataBox.hide(); elements.content.show(); }, 'json'); }, handleNav: function(nav) { elements.currentPage.empty(); for(var i = 1; i <= nav.pages; i++) { $(document.createElement('option')) .val(i).text(i) .appendTo(elements.currentPage); } this.checkNav(); }, handleDataRequest: function(json) { var methods = this; elements.dataBody.empty(); $.each(json, function(i, v) { var data = elements.rowClone.clone().children(); data.eq(0).children().val(v.id); data.eq(1).find('strong').text(v.name); data.eq(1).find('.inline_editUsername').val(v.name); data.eq(2).find('.wpProQuiz_email').text(v.email); data.eq(2).find('input').val(v.email); data.eq(3).text(v.type); data.eq(4).text(v.date); data.eq(5).text(v.points); data.eq(6).text(v.result); data.parent().show().appendTo(elements.dataBody); }); if(!json.length) { $(document.createElement('td')) .attr('colspan', '7') .text(wpProQuizLocalize.no_data_available) .css({'font-weight': 'bold', 'text-align': 'center', 'padding': '5px'}) .appendTo(document.createElement('tr')) .appendTo(elements.dataBody); } $('.wpProQuiz_delete').click(function() { if(confirm(wpProQuizLocalize.confirm_delete_entry)) { var id = new Array($(this).closest('tr').find('input[name="checkedData[]"]').val()); methods.loadData({a: 'delete', toplistIds: id}); } return false; }); $('.wpProQuiz_edit').click(function() { var $contain = $(this).closest('tr'); $contain.find('.row-actions').hide(); $contain.find('.inline-edit').show(); $contain.find('.wpProQuiz_username, .wpProQuiz_email').hide(); $contain.find('.inline_editUsername, .inline_editEmail').show(); return false; }); $('.inline_editSave').click(function() { var $contain = $(this).closest('tr'); var username = $contain.find('.inline_editUsername').val(); var email = $contain.find('.inline_editEmail').val(); if(methods.isEmpty(username) || methods.isEmpty(email)) { alert(wpProQuizLocalize.not_all_fields_completed); return false; } methods.loadData({ a: 'edit', toplistId: $contain.find('input[name="checkedData[]"]').val(), name: username, email: email }); return false; }); $('.inline_editCancel').click(function() { var $contain = $(this).closest('tr'); $contain.find('.row-actions').show(); $contain.find('.inline-edit').hide(); $contain.find('.wpProQuiz_username, .wpProQuiz_email').show(); $contain.find('.inline_editUsername, .inline_editEmail').hide(); $contain.find('.inline_editUsername').val($contain.find('.wpProQuiz_username').text()); $contain.find('.inline_editEmail').val($contain.find('.wpProQuiz_email').text()); return false; }); }, checkNav: function() { var n = elements.currentPage.val(); if(n == 1) { elements.pageLeft.hide(); } else { elements.pageLeft.show(); } if(n == elements.currentPage.children().length) { elements.pageRight.hide(); } else { elements.pageRight.show(); } }, isEmpty: function(text) { text = $.trim(text); return (!text || 0 === text.length); } }; var init = function() { elements.sort.change(function() { methods.loadData(); }); elements.pageLimit.change(function() { methods.loadData({nav: 1}); }); elements.currentPage.change(function() { methods.checkNav(); methods.loadData(); }); elements.pageLeft.click(function() { elements.currentPage.val(Number(elements.currentPage.val()) - 1); methods.checkNav(); methods.loadData(); }); elements.pageRight.click(function() { elements.currentPage.val(Number(elements.currentPage.val()) + 1); methods.checkNav(); methods.loadData(); }); $('#wpProQuiz_deleteAll').click(function() { methods.loadData({a: 'deleteAll'}); }); $('#wpProQuiz_action').click(function() { var name = $('#wpProQuiz_actionName').val(); if(name != '0') { var ids = $('input[name="checkedData[]"]:checked').map(function() { return $(this).val(); }).get(); methods.loadData({a: name, toplistIds: ids}); } }); $('#wpProQuiz_checkedAll').change(function() { if(this.checked) $('input[name="checkedData[]"]').attr('checked', 'checked'); else $('input[name="checkedData[]"]').removeAttr('checked', 'checked'); }); methods.loadData({nav: 1}); }; init(); }; if($('.wpProQuiz_quizOverall').length) $('.wpProQuiz_quizOverall').wpProQuiz_preview(); if($('.wpProQuiz_quizOverall').length) { $('.wpProQuiz_quizOverall').wpProQuiz_quizOverall(); } if($('.wpProQuiz_quizEdit').length) $('.wpProQuiz_quizEdit').wpProQuiz_quizEdit(); // if($('.wpProQuiz_questionEdit').length) // $('.wpProQuiz_questionEdit').wpProQuiz_questionEdit(); if($('.wpProQuiz_questionOverall').length) $('.wpProQuiz_questionOverall').wpProQuiz_questionOverall(); // if($('.wpProQuiz_statistics').length) // $('.wpProQuiz_statistics').wpProQuiz_statistics(); if($('.wpProQuiz_toplist').length) $('.wpProQuiz_toplist').wpProQuiz_toplist(); /** * NEW */ /** * @memberOf WpProQuiz_Admin */ function WpProQuiz_Admin() { var global = this; global = { displayChecked: function(t, box, neg, disabled) { var c = neg ? !t.checked : t.checked; if(disabled) c ? box.attr('disabled', 'disabled') : box.removeAttr('disabled'); else c ? box.show() : box.hide(); }, isEmpty: function(text) { text = $.trim(text); return (!text || 0 === text.length); }, isNumber: function(number) { number = $.trim(number); return !global.isEmpty(number) && !isNaN(number); }, getMceContent: function(id) { if(typeof tinymce == "undefined" || typeof tinymce == undefined || typeof tinymce.editors == "undefined") return $('#'+id).val(); var editor = tinymce.editors[id]; if(editor != undefined && !editor.isHidden()) { return editor.getContent(); } return $('#'+id).val(); }, ajaxPost: function(func, data, success) { var d = { action: 'wp_pro_quiz_admin_ajax', func: func, data: data }; $.post(ajaxurl, d, success, 'json'); } }; var tabWrapper = function() { $('.wpProQuiz_tab_wrapper a').click(function() { var $this = $(this); var tabId = $this.data('tab'); var currentTab = $this.siblings('.button-primary').removeClass('button-primary').addClass('button-secondary'); $this.removeClass('button-secondary').addClass('button-primary'); $(currentTab.data('tab')).hide('fast'); $(tabId).show('fast'); $(document).trigger({type: 'changeTab', tabId: tabId}); return false; }); }; function showSpinner(itemClass) { if (itemClass != '') { $(itemClass).css('float', 'none'); $(itemClass).css('visibility', 'visible'); $(itemClass).show(); } } function hideSpinner(itemClass) { if (itemClass != '') { $(itemClass).hide(); $(itemClass).css('visibility', 'hidden'); } } function showMessage(itemClass) { if (itemClass != '') { $(itemClass).show().fadeOut(1500); } } var module = { /** * @memberOf WpProQuiz_admin.module */ gobalSettings: function() { var methode = { categoryDelete: function(id) { var data = { categoryId: id }; showSpinner('.categorySpinner'); global.ajaxPost('categoryDelete', data, function(json) { if(json.err) { return; } hideSpinner('.categorySpinner'); showMessage('.categoryDeleteUpdate'); $('select[name="category"] option[value="'+id+'"]').remove(); $('select[name="category"]').change(); }); }, categoryEdit: function(id, name) { var data = { categoryId: id, categoryName: $.trim(name) }; if(global.isEmpty(name)) { alert(wpProQuizLocalize.category_no_name); return; } showSpinner('.categorySpinner'); global.ajaxPost('categoryEdit', data, function(json) { if(json.err) { return; } hideSpinner('.categorySpinner'); showMessage('.categoryEditUpdate') $('select[name="category"] option[value="'+id+'"]').text(data.categoryName); $('select[name="category"]').val(''); $('select[name="category"]').change(); }); }, changeTimeFormat: function(inputName, $select) { if($select.val() != "0") $('input[name="' + inputName + '"]').val($select.val()); }, templateDelete: function(id, type) { var data = { templateId: id, type: type }; // Show the spinner if(!type) { showSpinner('.templateQuizSpinner'); } else { showSpinner('.templateQuestionSpinner'); } global.ajaxPost('templateDelete', data, function(json) { if(json.err) { return; } if(!type) { hideSpinner('.templateQuizSpinner'); showMessage('.templateQuizDeleteUpdate'); $('select[name="templateQuiz"] option[value="'+id+'"]').remove(); $('select[name="templateQuiz"]').val(''); $('select[name="templateQuiz"]').change(); } else { hideSpinner('.templateQuestionSpinner'); showMessage('.templateQuestionDeleteUpdate'); $('select[name="templateQuestion"] option[value="'+id+'"]').remove(); $('select[name="templateQuestion"]').val(''); $('select[name="templateQuestion"]').change(); } }); }, templateEdit: function(id, name, type) { if(global.isEmpty(name)) { alert(wpProQuizLocalize.category_no_name); return; } var data = { templateId: id, name: $.trim(name), type: type }; if (!type) { showSpinner('.templateQuizSpinner'); } else { showSpinner('.templateQuestionSpinner'); } global.ajaxPost('templateEdit', data, function(json) { if(json.err) { return; } if(!type) { hideSpinner('.templateQuizSpinner'); showMessage('.templateQuizEditUpdate'); $('select[name="templateQuiz"] option[value="'+id+'"]').text(data.name); $('select[name="templateQuiz"]').val(''); $('select[name="templateQuiz"]').change(); } else { hideSpinner('.templateQuestionSpinner'); showMessage('.templateQuestionEditUpdate'); $('select[name="templateQuestion"] option[value="'+id+'"]').text(data.name); $('select[name="templateQuestion"]').val(''); $('select[name="templateQuestion"]').change(); } }); } }; var init = function() { // $('.wpProQuiz_tab').click(function() { // var $this = $(this); // // $('.wpProQuiz_tab').removeClass('button-primary').addClass('button-secondary'); // $this.removeClass('button-secondary').addClass('button-primary'); // // $('#problemInfo, #problemContent, #globalContent').hide('fast'); // // if($this.attr('id') == 'globalTab') { // $('#globalContent').show('fast'); // } else { // $('#problemInfo, #problemContent').show('fast'); // } // }); /******************************************* * Category ******************************************/ $('select[name="category"]').change(function() { //$('input[name="categoryEditText"]').val($(this).find(':selected').text()); if ($(this).val() != '') { $('input[name="categoryEditText"]').val($('option:selected', this).text()); } else { $('input[name="categoryEditText"]').val(''); } }); $('input[name="categoryDelete"]').click(function() { var category_id = $('select[name="category"] option:selected').val(); if (category_id != '') { methode.categoryDelete(category_id); } }); $('input[name="categoryEdit"]').click(function() { var category_id = $('select[name="category"] option:selected').val(); if (category_id != '') { var category_text = $('input[name="categoryEditText"]').val(); methode.categoryEdit(category_id, category_text); } }); /******************************************* * templateQuiz ******************************************/ $('select[name="templateQuiz"]').change(function() { //$('input[name="templateQuizEditText"]').val($(this).find(':selected').text()); if ($(this).val() != '') { $('input[name="templateQuizEditText"]').val($('option:selected', this).text()); } else { $('input[name="templateQuizEditText"]').val(''); } }); $('input[name="templateQuizEdit"]').click(function() { var template_id = $('select[name="templateQuiz"] option:selected').val(); if (template_id != '') { var text = $('input[name="templateQuizEditText"]').val(); methode.templateEdit(template_id, text, 0); } }); $('input[name="templateQuizDelete"]').click(function() { var template_id = $('select[name="templateQuiz"] option:selected').val(); if (template_id != '') { methode.templateDelete(template_id, 0); } }); /******************************************* * templateQuestion ******************************************/ $('select[name="templateQuestion"]').change(function() { //$('input[name="templateQuestionEditText"]').val($(this).find(':selected').text()); if ($(this).val() != '') { $('input[name="templateQuestionEditText"]').val($('option:selected', this).text()); } else { $('input[name="templateQuestionEditText"]').val(''); } }); $('input[name="templateQuestionEdit"]').click(function() { var template_id = $('select[name="templateQuestion"] option:selected').val(); if (template_id != '') { var text = $('input[name="templateQuestionEditText"]').val(); methode.templateEdit(template_id, text, 1); } }); $('input[name="templateQuestionDelete"]').click(function() { var template_id = $('select[name="templateQuestion"] option:selected').val(); if (template_id != '') { methode.templateDelete(template_id, 1); } }); /******************************************* * ******************************************/ $('#statistic_time_format_select').change(function() { methode.changeTimeFormat('statisticTimeFormat', $(this)); }); $(document).bind('changeTab', function(data) { $('#problemInfo').hide('fast'); switch (data.tabId) { case '#problemContent': $('#problemInfo').show('fast'); break; case '#emailSettingsTab': break; } }); /* $('input[name="email[html]"]').change(function() { if(switchEditors == undefined) return false; if(this.checked) { switchEditors.go('adminEmailEditor', 'tmce'); } else { switchEditors.go('adminEmailEditor', 'html'); } }).change(); */ /* $('input[name="userEmail[html]"]').change(function() { if(switchEditors == undefined) return false; if(this.checked) { switchEditors.go('userEmailEditor', 'tmce'); } else { switchEditors.go('userEmailEditor', 'html'); } }).change(); */ }; init(); }, questionEdit: function() { var methode = this; var filter = $.noop(); var elements = { answerChildren: $('.answer_felder > div'), pointsModus: $('input[name="answerPointsActivated"]'), gPoints: $('input[name="points"]') }; methode = { generateArrayIndex: function() { var type = $('input[name="answerType"]:checked').val(); type = (type == 'single' || type == 'multiple') ? 'classic_answer' : type; $('.answerList').each(function() { var currentType = $(this).parent().attr('class'); $(this).children().each(function(i, v) { $(this).find('[name^="answerData"]').each(function() { var name = this.name; var x = name.search(/\](\[\w+\])+$/); var n = (type == currentType) ? i : 'none'; if(x > 0) { this.name = 'answerData[' + n + name.substring(x, name.length); } }); }); }); }, globalValidate: function() { //var activeEditor = wp.wpActiveEditor; if ((typenow !== 'undefined' ) && ( typenow == 'sfwd-question' )) { // var active_editor_id = wpActiveEditor; if (global.isEmpty(global.getMceContent('content'))) { alert(wpProQuizLocalize.no_question_msg); return false; } } else { if(global.isEmpty(global.getMceContent('question'))) { alert(wpProQuizLocalize.no_question_msg); return false; } } if(!elements.pointsModus.is(':checked')) { var p = elements.gPoints.val(); if(!global.isNumber(p) || p < 1) { alert(wpProQuizLocalize.no_nummber_points); return false; } } else { if($('input[name="answerType"]:checked').val() == 'free_answer') { alert(wpProQuizLocalize.dif_points); return false; } } // Causing error. Not sure where filter() function is defined. NEed to check merges to see if something was dropped. For now commentted out. //if(filter() === false) // return false; return true; }, answerRemove: function() { var li = $(this).parent(); if ( li.parent().children().length > 1 ) li.remove(); else alert(wpProQuizLocalize.no_delete_answer); return false; }, addCategory: function() { var name = $.trim($('input[name="categoryAdd"]').val()); if(global.isEmpty(name)) { return; } var data = { categoryName: name }; global.ajaxPost('categoryAdd', data, function(json) { if(json.err) { $('#categoryMsgBox').text(json.err).show('fast').delay(2000).hide('fast'); return; } var $option = $(document.createElement('option')) .val(json.categoryId) .text(json.categoryName) .attr('selected', 'selected'); $('select[name="category"]').append($option).change(); }); }, addMediaClick: function() { var closest = $(this).closest('li'); var htmlCheck = closest.find('input[name="answerData[][html]"]:eq(0)'); var field = closest.find('.wpProQuiz_text:eq(0)') var media_upload_frame; if ( undefined !== media_upload_frame ) { media_upload_frame.open(); return; } media_upload_frame = wp.media.frames.media_upload_frame = wp.media({ frame: 'select', 'library': { type: [ 'image', 'audio', 'video' ] }, multiple: false }); media_upload_frame.on( 'select', function() { var json = media_upload_frame.state().get( 'selection' ).first().toJSON(); if( json.type === "image" ) { field.val(field.val() + '<img src="' + json.url + '" alt="' + json.alt + '" />'); htmlCheck.attr('checked', true); } if( json.type === "audio" ) { field.val(field.val() + '[audio src="' + json.url + '"][/audio]'); htmlCheck.attr('checked', true); } if( json.type === "video" ) { field.val(field.val() + '[video src="' + json.url + '"][/video]'); htmlCheck.attr('checked', true); } }); media_upload_frame.open(); } }; var validate = { classic_answer: function() { var findText = 0; var findCorrect = 0; var findPoints = 0; $('.classic_answer .answerList').children().each(function() { var t = $(this); if(!global.isEmpty(t.find('textarea[name="answerData[][answer]"]').val())) { findText++; if(t.find('input[name="answerData[][correct]"]:checked').length) { findCorrect++; } var p = t.find('input[name="answerData[][points]"]').val(); if(global.isNumber(p) && p >= 0) { findPoints++; } } }); if(!findText) { alert(wpProQuizLocalize.no_answer_msg); return false; } if(!findCorrect && !($('input[name="disableCorrect"]').is(':checked') && $('input[name="answerPointsDiffModusActivated"]').is(':checked') && $('input[name="answerPointsActivated"]').is(':checked') && $('input[name="answerType"]:checked').val() == 'single')) { alert(wpProQuizLocalize.no_correct_msg); return false; } if(findPoints != findText && elements.pointsModus.is(':checked')) { alert(wpProQuizLocalize.no_nummber_points_new); return false; } return true; }, free_answer: function() { if(global.isEmpty($('.free_answer textarea[name="answerData[][answer]"]').val())) { alert(wpProQuizLocalize.no_answer_msg); return false; } return true; }, cloze_answer: function() { if(global.isEmpty(global.getMceContent('cloze'))) { alert(wpProQuizLocalize.no_answer_msg); return false; } return true; }, sort_answer: function() { var findText = 0; var findPoints = 0; $('.sort_answer .answerList').children().each(function() { var t = $(this); if(!global.isEmpty(t.find('textarea[name="answerData[][answer]"]').val())) { findText++; var p = t.find('input[name="answerData[][points]"]').val(); if(global.isNumber(p) && p >= 0) { findPoints++; } } }); if(!findText) { alert(wpProQuizLocalize.no_answer_msg); return false; } if(findPoints != findText && elements.pointsModus.is(':checked')) { alert(wpProQuizLocalize.no_nummber_points_new); return false; } return true; }, matrix_sort_answer: function() { var findText = 0; var findPoints = 0; var sortString = true; var menge = 0; $('.matrix_sort_answer .answerList').children().each(function() { var t = $(this); var p = t.find('input[name="answerData[][points]"]').val(); if(!global.isEmpty(t.find('textarea[name="answerData[][answer]"]').val())) { findText++; menge++; if(global.isEmpty(t.find('textarea[name="answerData[][sort_string]"]').val())) { sortString = false; } if(global.isNumber(p) && p >= 0) { findPoints++; } } else { if(!global.isEmpty(t.find('textarea[name="answerData[][sort_string]"]').val())) { menge++; if(global.isNumber(p) && p >= 0) { findPoints++; } } } }); if(!findText) { alert(wpProQuizLocalize.no_answer_msg); return false; } if(!sortString) { alert(wpProQuizLocalize.no_sort_element_criterion); return false; } if(findPoints != menge && elements.pointsModus.is(':checked')) { alert(wpProQuizLocalize.no_nummber_points_new); return false; } return true; }, assessment_answer: function() { if(global.isEmpty(global.getMceContent('assessment'))) { alert(wpProQuizLocalize.no_answer_msg); return false; } return true; } }; var formListener = function() { $('#wpProQuiz_tip').change(function() { global.displayChecked(this, $('#wpProQuiz_tipBox')); }).change(); $('#wpProQuiz_correctSameText').change(function() { global.displayChecked(this, $('#wpProQuiz_incorrectMassageBox'), true); global.displayChecked(this, $('#learndash_question_message_incorrect_answer'), true); }); $('input[name="answerType"]').click(function() { elements.answerChildren.hide(); var v = this.value; if(v == 'single') { if ((typenow !== 'undefined') && (typenow == 'sfwd-question')) { $('#learndash_question_single_choice_options').show(); } else { $('#singleChoiceOptions').show(); } $('input[name="disableCorrect"]').change(); } else { if ((typenow !== 'undefined') && (typenow == 'sfwd-question')) { $('#learndash_question_single_choice_options').hide(); } else { $('#singleChoiceOptions').hide(); } $('.classic_answer .wpProQuiz_classCorrect').parent().parent().show(); } if(v == 'single' || v == 'multiple') { var type = (v == 'single') ? 'radio' : 'checkbox'; v = 'classic_answer'; $('.wpProQuiz_classCorrect').each(function() { $("<input type=" + type + " />") .attr({ name: this.name, value: this.value, checked: this.checked}) .addClass('wpProQuiz_classCorrect wpProQuiz_checkbox') .insertBefore(this); }).remove(); } if ( v == 'essay' ) { $('input[name="answerPointsActivated"]').attr('checked', false); $('input[name="showPointsInBox"]').attr('checked', false); $('input[name="points"]').attr('disabled', false); $('#wpProQuiz_answerPointsActivated').hide(); $('#wpProQuiz_correctMessageBox').hide(); $('#learndash_question_message_correct_answer').hide(); $('input[name="correctSameText"]').attr('checked', false); $('textarea[name="correctMsg"]').val(''); $('#wpProQuiz_incorrectMassageBox').hide(); $('#learndash_question_message_incorrect_answer').hide(); $('textarea[name="incorrectMsg"]').val(''); $('#wpProQuiz_showPointsBox').hide(); } else { $('#wpProQuiz_answerPointsActivated').show(); $('#wpProQuiz_correctMessageBox').show(); $('#learndash_question_message_correct_answer').show(); $('#wpProQuiz_incorrectMassageBox').show(); $('#learndash_question_message_incorrect_answer').show(); } filter = (validate[v] != undefined) ? validate[v] : $.noop(); $('.' + v).show(); }); $('input[name="answerType"]:checked').click(); $('#wpProQuiz_correctSameText').change(); $('.deleteAnswer').click(methode.answerRemove); $('.addAnswer').click(function() { var default_value = $(this).attr('data-default-value'); if (default_value == undefined) default_value = 0; var ul = $(this).siblings('ul'); var clone = ul.find('li:eq(0)').clone(); clone.find('.wpProQuiz_checkbox').removeAttr('checked'); clone.find('.wpProQuiz_text').val(''); clone.find('.wpProQuiz_points').val(default_value); clone.find('.deleteAnswer').click(methode.answerRemove); clone.find('.addMedia').click(methode.addMediaClick); clone.appendTo(ul); return false; }); $('.sort_answer ul, .classic_answer ul, .matrix_sort_answer ul').sortable({ handle: '.wpProQuiz_move' }); $('#saveQuestion').click(function() { if(!methode.globalValidate()) { return false; } methode.generateArrayIndex(); return true; }); $('#publish').click(function () { if (!methode.globalValidate()) { return false; } methode.generateArrayIndex(); return true; }); $('#save-post').click(function () { if (!methode.globalValidate()) { return false; } methode.generateArrayIndex(); return true; }); $(elements.pointsModus).change(function() { global.displayChecked(this, $('.wpProQuiz_answerPoints')); global.displayChecked(this, $('#wpProQuiz_showPointsBox')); global.displayChecked(this, elements.gPoints, false, true); global.displayChecked(this, $('input[name="answerPointsDiffModusActivated"]'), true, true); if(this.checked) { $('input[name="answerPointsDiffModusActivated"]').change(); $('input[name="disableCorrect"]').change(); } else { $('.classic_answer .wpProQuiz_classCorrect').parent().parent().show(); $('input[name="disableCorrect"]').attr('disabled', 'disabled'); } }).change(); $('select[name="category"]').change(function() { var $this = $(this); var box = $('#categoryAddBox').hide(); if($this.val() == "-1") { box.show(); } }).change(); $('#categoryAddBtn').click(function() { methode.addCategory(); }); $('.addMedia').click(methode.addMediaClick); $('input[name="answerPointsDiffModusActivated"]').change(function() { global.displayChecked(this, $('input[name="disableCorrect"]'), true, true); if(this.checked) $('input[name="disableCorrect"]').change(); else $('.classic_answer .wpProQuiz_classCorrect').parent().parent().show(); }).change(); $('input[name="disableCorrect"]').change(function() { global.displayChecked(this, $('.classic_answer .wpProQuiz_classCorrect').parent().parent(), true); }).change(); $('#clickPointDia').click(function() { $('.pointDia').toggle('fast'); return false; }); $('input[name="template"]').click(function(e) { if($('select[name="templateSaveList"]').val() == '0') { if(global.isEmpty($('input[name="templateName"]').val())) { alert(wpProQuizLocalize.temploate_no_name); e.preventDefault(); return false; } } methode.generateArrayIndex(); }); $('select[name="templateSaveList"]').change(function() { var $templateName = $('input[name="templateName"]'); if($(this).val() == '0') { $templateName.show(); } else { $templateName.hide(); } }).change(); }; var init = function() { elements.answerChildren.hide(); formListener(); }; init(); }, statistic: function() { var methode = this; var quizId = $('#quizId').val(); var currentTab = 'users'; var elements = { currentPage: $('#wpProQuiz_currentPage'), pageLeft: $('#wpProQuiz_pageLeft'), pageRight: $('#wpProQuiz_pageRight'), testSelect: $('#testSelect') }; methode = { loadStatistic: function(userId, callback) { var data = { userId: userId }; global.ajaxPost('statisticLoad', data, function(json) { }); }, loadUsersStatistic: function() { var userId = $('#userSelect').val(); var data = { userId: userId, quizId: quizId, testId: $('#testSelect').val() }; methode.toggleLoadBox(false); global.ajaxPost('statisticLoad', data, function(json) { $.each(json.question, function() { var $tr = $('#wpProQuiz_tr_' + this.questionId); methode.setStatisticData($tr, this); }); $.each(json.category, function(i, v) { var $tr = $('#wpProQuiz_ctr_' + i); methode.setStatisticData($tr, v); }); $('#testSelect option:gt(0)').remove(); var $testSelect = $('#testSelect'); $.each(json.tests, function() { var $option = $(document.createElement('option')); $option.val(this.id); $option.text(this.date); if(json.testId == this.id) $option.attr('selected', true); $testSelect.append($option); }); methode.parseFormData(json.formData); methode.toggleLoadBox(true); }); }, loadUsersStatistic_: function(userId, testId) { var data = { userId: userId, quizId: quizId, testId: testId }; methode.toggleLoadBox(false); global.ajaxPost('statisticLoad', data, function(json) { $.each(json.question, function() { var $tr = $('#wpProQuiz_tr_' + this.questionId); methode.setStatisticData($tr, this); }); $.each(json.category, function(i, v) { var $tr = $('#wpProQuiz_ctr_' + i); methode.setStatisticData($tr, v); }); $('#testSelect option:gt(0)').remove(); var $testSelect = $('#testSelect'); $.each(json.tests, function() { var $option = $(document.createElement('option')); $option.val(this.id); $option.text(this.date); if(json.testId == this.id) $option.attr('selected', true); $testSelect.append($option); }); methode.parseFormData(json.formData); $('#userSelect').val(userId); $('#testSelect').val(testId); methode.toggleLoadBox(true); }); }, parseFormData: function(data) { var $formBox = $('#wpProQuiz_form_box'); if(data == null) { $formBox.hide(); return; } $.each(data, function(i, v) { $('#form_id_' + i).text(v); }); $formBox.show(); }, setStatisticData: function($o, v) { $o.find('.wpProQuiz_cCorrect').text(v.correct); $o.find('.wpProQuiz_cIncorrect').text(v.incorrect); $o.find('.wpProQuiz_cTip').text(v.hint); $o.find('.wpProQuiz_cPoints').text(v.points); $o.find('.wpProQuiz_cResult').text(v.result); $o.find('.wpProQuiz_cTime').text(v.questionTime); $o.find('.wpProQuiz_cCreateTime').text(v.date); }, toggleLoadBox: function(show) { var $loadBox = $('#wpProQuiz_loadData'); var $content = $('#wpProQuiz_content'); if(show) { $loadBox.hide(); $content.show(); } else { $content.hide(); $loadBox.show(); } }, reset: function(type) { var userId = $('#userSelect').val(); if(!confirm(wpProQuizLocalize.reset_statistics_msg)) { return; } var data = { quizId: quizId, userId: userId, testId: elements.testSelect.val(), type: type }; methode.toggleLoadBox(false); global.ajaxPost('statisticReset', data, function() { methode.loadUsersStatistic(); }); }, loadStatisticOverview: function(nav) { var data = { quizId: quizId, pageLimit: $('#wpProQuiz_pageLimit').val(), onlyCompleted: Number($('#wpProQuiz_onlyCompleted').is(':checked')), page: elements.currentPage.val(), nav: Number(nav) }; methode.toggleLoadBox(false); global.ajaxPost('statisticLoadOverview', data, function(json) { var $body = $('#wpProQuiz_statistics_overview_data'); var $tr = $body.children(); var $c = $tr.first().clone(); $tr.slice(1).remove(); $.each(json.items, function() { var clone = $c.clone(); methode.setStatisticData(clone, this); clone.find('a').text(this.userName).data('userId', this.userId).click(function() { $('#userSelect').val($(this).data('userId')); $('#wpProQuiz_typeUser').click(); return false; }); clone.show().appendTo($body); }); $c.remove(); methode.toggleLoadBox(true); if(json.page != undefined) methode.handleNav(json.page); }); }, handleNav: function(nav) { var $p = $('#wpProQuiz_currentPage').empty(); for(var i = 1; i <= nav; i++) { $(document.createElement('option')) .val(i) .text(i) .appendTo($p); } methode.checkNavBar(); }, checkNavBar: function() { var n = elements.currentPage.val(); if(n == 1) { elements.pageLeft.hide(); } else { elements.pageLeft.show(); } if(n == elements.currentPage.children().length) { elements.pageRight.hide(); } else { elements.pageRight.show(); } }, refresh: function() { if(currentTab == 'users') { methode.loadUsersStatistic(); } else if(currentTab == 'formOverview') { methode.loadFormsOverview(true); } else { methode.loadStatisticOverview(true); } }, loadFormsOverview: function(nav) { var data = { quizId: quizId, pageLimit: $('#wpProQuiz_fromPageLimit').val(), onlyUser: $('#wpProQuiz_formUser').val(), page: $('#wpProQuiz_formCurrentPage').val(), nav: Number(nav) }; methode.toggleLoadBox(false); global.ajaxPost('statisticLoadFormOverview', data, function(json) { var $body = $('#wpProQuiz_statistics_form_data'); var $tr = $body.children(); var $c = $tr.first().clone(); $tr.slice(1).remove(); $.each(json.items, function() { var clone = $c.clone(); methode.setStatisticData(clone, this); clone.find('a').text(this.userName).data('userId', this.userId).data('testId', this.testId).click(function() { methode.switchTabOnLoad('users'); methode.loadUsersStatistic_($(this).data('userId'), $(this).data('testId')); return false; }); clone.show().appendTo($body); }); $c.remove(); methode.toggleLoadBox(true); if(json.page != undefined) methode.handleFormNav(json.page); }); }, handleFormNav: function(nav) { var $p = $('#wpProQuiz_formCurrentPage').empty(); for(var i = 1; i <= nav; i++) { $(document.createElement('option')) .val(i) .text(i) .appendTo($p); } methode.checkFormNavBar(); }, checkFormNavBar: function() { var n = $('#wpProQuiz_formCurrentPage').val(); if(n == 1) { $('#wpProQuiz_formPageLeft').hide(); } else { $('#wpProQuiz_formPageLeft').show(); } if(n ==$('#wpProQuiz_formCurrentPage').children().length) { $('#wpProQuiz_formPageRight').hide(); } else { $('#wpProQuiz_formPageRight').show(); } }, switchTabOnLoad: function(name) { $('.wpProQuiz_tab').removeClass('button-primary').addClass('button-secondary'); $('.wpProQuiz_tabContent').hide(); var $this = $('#wpProQuiz_typeOverview'); if(name == 'users') { currentTab = 'users'; $('#wpProQuiz_tabUsers').show(); $this = $('#wpProQuiz_typeUser'); } else if(name == 'formOverview') { currentTab = 'formOverview'; $('#wpProQuiz_tabFormOverview').show(); $this = $('#wpProQuiz_typeForm'); } else { currentTab = 'overview'; $('#wpProQuiz_tabOverview').show(); } $this.removeClass('button-secondary').addClass('button-primary'); } }; var init = function() { $('#userSelect, #testSelect').change(function() { methode.loadUsersStatistic(); }); $('.wpProQuiz_update').click(function() { methode.refresh(); }); $('#wpProQuiz_reset').click(function() { methode.reset(0); }); $('#wpProQuiz_resetUser').click(function() { methode.reset(1); }); $('.wpProQuiz_resetComplete').click(function() { methode.reset(2); }); $('.wpProQuiz_tab').click(function() { var $this = $(this); $('.wpProQuiz_tab').removeClass('button-primary').addClass('button-secondary'); $this.removeClass('button-secondary').addClass('button-primary'); $('.wpProQuiz_tabContent').hide(); if($this.attr('id') == 'wpProQuiz_typeUser') { currentTab = 'users'; $('#wpProQuiz_tabUsers').show(); methode.loadUsersStatistic(); } else if($this.attr('id') == 'wpProQuiz_typeForm') { currentTab = 'formOverview'; $('#wpProQuiz_tabFormOverview').show(); methode.loadFormsOverview(true); } else { currentTab = 'overview'; $('#wpProQuiz_tabOverview').show(); methode.loadStatisticOverview(true); } return false; }); $('#wpProQuiz_onlyCompleted').change(function() { elements.currentPage.val(1); methode.loadStatisticOverview(true); }); $('#wpProQuiz_pageLimit').change(function() { elements.currentPage.val(1); methode.loadStatisticOverview(true); }); elements.pageLeft.click(function() { elements.currentPage.val(Number(elements.currentPage.val()) - 1); methode.loadStatisticOverview(false); methode.checkNavBar(); }); elements.pageRight.click(function() { elements.currentPage.val(Number(elements.currentPage.val()) + 1); methode.loadStatisticOverview(false); methode.checkNavBar(); }); elements.currentPage.change(function() { methode.loadStatisticOverview(false); methode.checkNavBar(); }); $('#wpProQuiz_formUser, #wpProQuiz_fromPageLimit').change(function() { $('#wpProQuiz_formCurrentPage').val(1); methode.loadFormsOverview(true); }); $('#wpProQuiz_formPageLeft').click(function() { $('#wpProQuiz_formCurrentPage').val(Number(elements.currentPage.val()) - 1); methode.loadFormsOverview(false); methode.checkFormNavBar(); }); $('#wpProQuiz_formPageRight').click(function() { $('#wpProQuiz_formCurrentPage').val(Number(elements.currentPage.val()) + 1); methode.loadFormsOverview(false); methode.checkFormNavBar(); }); $('#wpProQuiz_formCurrentPage').change(function() { methode.loadFormsOverview(false); methode.checkFormNavBar(); }); methode.loadUsersStatistic(); }; init(); }, statisticNew: function() { var quizId = $('#quizId').val(); var historyNavigator = null; var overviewNavigator = null; var historyFilter = { data: { quizId: quizId, users: -1, pageLimit: 100, dateFrom: 0, dateTo: 0, generateNav: 0 }, changeFilter: function() { var getTime = function(p) { var date = p.datepicker('getDate'); return date === null ? 0 : date.getTime() / 1000; }; $.extend(this.data, { users: $('#wpProQuiz_historyUser').val(), pageLimit: $('#wpProQuiz_historyPageLimit').val(), dateFrom: getTime($('#datepickerFrom')), dateTo: getTime($('#datepickerTo')), generateNav: 1 }); return this.data; } }; var overviewFilter = { data: { pageLimit: 100, onlyCompleted: 0, generateNav: 0, quizId: quizId }, changeFilter: function() { $.extend(this.data, { pageLimit: $('#wpProQuiz_overviewPageLimit').val(), onlyCompleted: Number($('#wpProQuiz_overviewOnlyCompleted').is(':checked')), generateNav: 1 }); } }; var deleteMethode = { deleteUserStatistic: function(refId, userId) { if(!confirm(wpProQuizLocalize.reset_statistics_msg)) return false; var data = { refId: refId, userId: userId, quizId: quizId, type: 0 }; global.ajaxPost('statisticResetNew', data, function() { $('#wpProQuiz_user_overlay').hide(); historyFilter.changeFilter(); methode.loadHistoryAjax(); overviewFilter.changeFilter(); methode.loadOverviewAjax(); }); }, deleteAll: function() { if(!confirm(wpProQuizLocalize.reset_statistics_msg)) return false; var data = { quizId: quizId, type: 1 }; global.ajaxPost('statisticResetNew', data, function() { historyFilter.changeFilter(); methode.loadHistoryAjax(); overviewFilter.changeFilter(); methode.loadOverviewAjax(); }); } }; var methode = { loadHistoryAjax: function() { var data = $.extend({ page: historyFilter.data.generateNav ? 1 : historyNavigator.getCurrentPage() }, historyFilter.data); methode.loadBox(true); var content = $('#wpProQuiz_historyLoadContext').hide(); global.ajaxPost('statisticLoadHistory', data, function(json) { content.html(json.html).show(); if(json.navi) historyNavigator.setNumPage(json.navi); historyFilter.data.generateNav = 0; content.find('.user_statistic').click(function() { methode.loadUserAjax(0, $(this).data('ref_id'), false); return false; }); content.find('.wpProQuiz_delete').click(function() { deleteMethode.deleteUserStatistic($(this).parents('tr').find('.user_statistic').data('ref_id'), 0); return false; }); methode.loadBox(false); }); }, loadUserAjax: function(userId, refId, avg) { $('#wpProQuiz_user_overlay, #wpProQuiz_loadUserData').show(); var content = $('#wpProQuiz_user_content').hide(); var data = { quizId: quizId, userId: userId, refId: refId, avg: Number(avg) }; global.ajaxPost('statisticLoadUser', data, function(json) { content.html(json.html); content.find('.wpProQuiz_update').click(function() { methode.loadUserAjax(userId, refId, avg); return false; }); content.find('#wpProQuiz_resetUserStatistic').click(function() { deleteMethode.deleteUserStatistic(refId, userId); }); content.find('.statistic_data').click(function() { $(this).parents('tr').next().toggle('fast'); return false; }); $('#wpProQuiz_loadUserData').hide(); jQuery('body').trigger('learndash-statistics-contentchanged'); content.show(); }); }, loadBox: function(show, contain) { if(show) $('#wpProQuiz_loadDataHistory').show(); else $('#wpProQuiz_loadDataHistory').hide(); }, loadOverviewAjax: function() { var data = $.extend({ page: overviewFilter.data.generateNav ? 1 : overviewNavigator.getCurrentPage() }, overviewFilter.data); $('#wpProQuiz_loadDataOverview').show(); var content = $('#wpProQuiz_overviewLoadContext').hide(); global.ajaxPost('statisticLoadOverviewNew', data, function(json) { content.html(json.html).show(); if(json.navi) overviewNavigator.setNumPage(json.navi); overviewFilter.data.generateNav = 0; content.find('.user_statistic').click(function() { methode.loadUserAjax($(this).data('user_id'), 0, true); return false; }); content.find('.wpProQuiz_delete').click(function() { deleteMethode.deleteUserStatistic(0, $(this).parents('tr').find('.user_statistic').data('user_id')); return false; }); $('#wpProQuiz_loadDataOverview').hide(); }); } }; var init = function() { historyNavigator = new Navigator($('#historyNavigation'), { onChange: function() { methode.loadHistoryAjax(); } }); overviewNavigator = new Navigator($('#overviewNavigation'), { onChange: function() { methode.loadOverviewAjax(); } }); if (($('#datepickerFrom').length) || ($('#datepickerTo').length)) { // Wait until the #ui-datepicker-div element is added to the DOM $(document).on('DOMNodeInserted', function(e) { if (e.target.id == 'ui-datepicker-div') { $('#ui-datepicker-div').addClass('learndash-datepicker'); } }); $('#datepickerFrom').datepicker({ closeText: wpProQuizLocalize.closeText, currentText: wpProQuizLocalize.currentText, monthNames: wpProQuizLocalize.monthNames, monthNamesShort: wpProQuizLocalize.monthNamesShort, dayNames: wpProQuizLocalize.dayNames, dayNamesShort: wpProQuizLocalize.dayNamesShort, dayNamesMin: wpProQuizLocalize.dayNamesMin, dateFormat: wpProQuizLocalize.dateFormat, firstDay: wpProQuizLocalize.firstDay, changeMonth: true, onClose: function(selectedDate) { $('#datepickerTo').datepicker('option', 'minDate', selectedDate); } }); $('#datepickerTo').datepicker({ closeText: wpProQuizLocalize.closeText, currentText: wpProQuizLocalize.currentText, monthNames: wpProQuizLocalize.monthNames, monthNamesShort: wpProQuizLocalize.monthNamesShort, dayNames: wpProQuizLocalize.dayNames, dayNamesShort: wpProQuizLocalize.dayNamesShort, dayNamesMin: wpProQuizLocalize.dayNamesMin, dateFormat: wpProQuizLocalize.dateFormat, firstDay: wpProQuizLocalize.firstDay, changeMonth: true, onClose: function(selectedDate) { $('#datepickerFrom').datepicker('option', 'maxDate', selectedDate); } }); } $('#filter').click(function() { historyFilter.changeFilter(); methode.loadHistoryAjax(); }); $('#wpProQuiz_overlay_close').click(function() { $('#wpProQuiz_user_overlay').hide(); }); $('#wpProQuiz_tabHistory .wpProQuiz_update').click(function() { historyFilter.changeFilter(); methode.loadHistoryAjax(); return false; }); $('#wpProQuiz_tabOverview .wpProQuiz_update').click(function() { overviewFilter.changeFilter(); methode.loadOverviewAjax(); return false; }); $('.wpProQuiz_resetComplete').click(function() { deleteMethode.deleteAll(); return false; }); $('#overviewFilter').click(function() { overviewFilter.changeFilter(); methode.loadOverviewAjax(); }); historyFilter.changeFilter(); methode.loadHistoryAjax(); overviewFilter.changeFilter(); methode.loadOverviewAjax(); }; init(); } }; var init = function() { tabWrapper(); var m = $.noop; if (($('.wpProQuiz_questionEdit').length) || ($('body.learndash-post-type.sfwd-question').length)) { m = module.questionEdit; } else if($('.wpProQuiz_globalSettings').length) { m = module.gobalSettings; } else if($('.wpProQuiz_statistics').length) { m = module.statistic; } else if($('.wpProQuiz_statisticsNew').length) { m = module.statisticNew; } m(); $('.wpProQuiz_demoImgBox a').mouseover(function(e) { var $this = $(this); var d = $(document).width(); var img = $this.siblings().outerWidth(true); if(e.pageX + img > d) { var v = d - (e.pageX + img + 30); $(this).next().css('left', v + "px"); } $(this).next().show(); }).mouseout(function() { $(this).next().hide(); }).click(function() { return false; }); }; init(); } WpProQuiz_Admin(); function Navigator(obj, option) { var defaultOption = { onChange: null }; var elements = { contain: null, pageLeft: null, pageRight: null, currentPage: null }; var checkNavBar = function() { var num = elements.currentPage.children().length; var cur = Number(elements.currentPage.val()); elements.pageLeft.hide(); elements.pageRight.hide(); if(cur > 1) elements.pageLeft.show(); if((cur + 1) <= num) elements.pageRight.show(); }; var init = function() { $.extend(elements, { contain: obj, pageLeft: obj.find('.navigationLeft'), pageRight: obj.find('.navigationRight'), currentPage: obj.find('.navigationCurrentPage') }); $.extend(defaultOption, option); elements.pageLeft.click(function() { elements.currentPage.val(Number(elements.currentPage.val()) - 1); checkNavBar(); if(defaultOption.onChange) defaultOption.onChange(elements.currentPage.val()); }); elements.pageRight.click(function() { elements.currentPage.val(Number(elements.currentPage.val()) + 1); checkNavBar(); if(defaultOption.onChange) defaultOption.onChange(elements.currentPage.val()); }); elements.currentPage.change(function() { checkNavBar(); if(defaultOption.onChange) defaultOption.onChange(elements.currentPage.val()); }); }; this.getCurrentPage = function() { return elements.currentPage.val(); } this.setNumPage = function(num) { elements.currentPage.empty(); for(var i = 1; i <= num; i++) { $(document.createElement('option')) .val(i) .text(i) .appendTo(elements.currentPage); } checkNavBar(); } init(); } }); js/jquery.cookie.min.js 0000666 00000002731 15214236625 0011104 0 ustar 00 !function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : "object" == typeof exports ? e(require("jquery")) : e(jQuery) }(function (e) { var n = /\+/g; function o(e) { return t.raw ? e : encodeURIComponent(e) } function i(e) { return o(t.json ? JSON.stringify(e) : String(e)) } function r(o, i) { var r = t.raw ? o : function (e) { 0 === e.indexOf('"') && (e = e.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\")); try { return e = decodeURIComponent(e.replace(n, " ")), t.json ? JSON.parse(e) : e } catch (e) { } }(o); return e.isFunction(i) ? i(r) : r } var t = e.cookie = function (n, c, u) { if (void 0 !== c && !e.isFunction(c)) { if ("number" == typeof (u = e.extend({}, t.defaults, u)).expires) { var a = u.expires, d = u.expires = new Date; d.setTime(+d + 864e5 * a) } return document.cookie = [o(n), "=", i(c), u.expires ? "; expires=" + u.expires.toUTCString() : "", u.path ? "; path=" + u.path : "", u.domain ? "; domain=" + u.domain : "", u.secure ? "; secure" : ""].join("") } for (var f, p = n ? void 0 : {}, s = document.cookie ? document.cookie.split("; ") : [], m = 0, v = s.length; m < v; m++) { var x = s[m].split("="), k = (f = x.shift(), t.raw ? f : decodeURIComponent(f)), l = x.join("="); if (n && n === k) { p = r(l, c); break } n || void 0 === (l = r(l)) || (p[k] = l) } return p }; t.defaults = {}, e.removeCookie = function (n, o) { return void 0 !== e.cookie(n) && (e.cookie(n, "", e.extend({}, o, { expires: -1 })), !e.cookie(n)) } }); js/wpProQuiz_front.min.js 0000666 00000120513 15214236625 0011504 0 ustar 00 (function(e){e.wpProQuizFront=function(i,t){function o(){var e=0,i=-1,t=0,o=!1;this.questionStart=function(t){-1!=i&&this.questionStop(),i=t,e=+new Date},this.questionStop=function(){-1!=i&&(f[i].time+=Math.round((new Date-e)/1e3),i=-1)},this.startQuiz=function(){o&&this.stopQuiz(),t=+new Date,o=!0},this.stopQuiz=function(){o&&(quizEndTimer=+new Date,f.comp.quizTime+=Math.round((quizEndTimer-t)/1e3),f.comp.quizEndTimestamp=quizEndTimer,f.comp.quizStartTimestamp=t,o=!1)},this.init=function(){}}function n(i,t,o,n){if("single"==i.type||"multiple"==i.type)n.children().each(function(i){var n=e(this),s=n.attr("data-pos");if(null!=t[s]){var r=t[s];1==r&&(e(".wpProQuiz_questionInput",n).prop("checked","checked"),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}}))}});else if("free_answer"==i.type)n.children().each(function(i){e(this);e(".wpProQuiz_questionInput",this).val(t)}),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}});else if("sort_answer"==i.type)jQuery.each(t,function(i,t){var o=e('li.wpProQuiz_questionListItem[data-pos="'+t+'"]',n),s=e("div.wpProQuiz_sortable",o);e(s).text();jQuery(n).append(o)}),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}});else if("matrix_sort_answer"==i.type)jQuery.each(t,function(i,t){var s=e('.wpProQuiz_matrixSortString .wpProQuiz_sortStringList li[data-pos="'+i+'"]',o),r=e('li.wpProQuiz_questionListItem[data-pos="'+t+'"] ul.wpProQuiz_maxtrixSortCriterion',n);jQuery(s).appendTo(r)}),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}});else if("cloze_answer"==i.type)jQuery('span.wpProQuiz_cloze input[type="text"]',n).each(function(i){void 0!==t[i]&&e(this).val(t[i])}),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}});else if("assessment_answer"==i.type)e('input.wpProQuiz_questionInput[value="'+t+'"]',n).attr("checked","checked"),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}});else if("essay"==i.type)if(n.find("#uploadEssayFile_"+i.id).length){var r=n.find("#uploadEssayFile_"+i.id);e(r).val(t),e("<p>"+s(t)+"</p>").insertAfter(r),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}})}else n.find(".wpProQuiz_questionEssay").length&&(n.find(".wpProQuiz_questionEssay").html(t),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}}))}function s(e){return null!=e?e.split("/").reverse()[0]:""}var r,a,u,d,c=e(i),p=t,l={},h=this,f=new Object,w=new Object,m=0,_=null,v=[],Q="",z=!1,P=1,g=0,q=null,y="",x="",k={randomAnswer:0,randomQuestion:0,disabledAnswerMark:0,checkBeforeStart:0,preview:0,cors:0,isAddAutomatic:0,quizSummeryHide:0,skipButton:0,reviewQustion:0,autoStart:0,forcingQuestionSolve:0,hideQuestionPositionOverview:0,formActivated:0,maxShowQuestion:0,sortCategories:0},S={isQuizStart:0,isLocked:0,loadLock:0,isPrerequisite:0,isUserStartLocked:0},b={check:'input[name="check"]',next:'input[name="next"]',questionList:".wpProQuiz_questionList",skip:'input[name="skip"]',singlePageLeft:'input[name="wpProQuiz_pageLeft"]',singlePageRight:'input[name="wpProQuiz_pageRight"]'},I={back:c.find('input[name="back"]'),next:c.find(b.next),quiz:c.find(".wpProQuiz_quiz"),questionList:c.find(".wpProQuiz_list"),results:c.find(".wpProQuiz_results"),sending:c.find(".wpProQuiz_sending"),quizStartPage:c.find(".wpProQuiz_text"),timelimit:c.find(".wpProQuiz_time_limit"),toplistShowInButton:c.find(".wpProQuiz_toplistShowInButton"),listItems:e()},T={token:"",isUser:0},L={START:0,END:1},C=(r=p.timelimit,a=0,u={},d="ldadv-time-limit-"+p.user_id+"-"+p.quizId,u.stop=function(){r&&(e.removeCookie(d),window.clearInterval(a),I.timelimit.hide())},u.start=function(){if(r){e.cookie.raw=!0;var i=1e3*r,t=e.cookie(d),o=t||r,n=1e3*o,s=I.timelimit.find("span").text(h.methode.parseTime(o)),c=I.timelimit.find(".wpProQuiz_progress");I.timelimit.show();var p=+new Date;a=window.setInterval(function(){var o=+new Date-p,r=n-o;o>=500&&(t=r/1e3,s.text(h.methode.parseTime(Math.ceil(t))),e.cookie(d,t)),c.css("width",r/i*100+"%"),r<=0&&(u.stop(),h.methode.finishQuiz(!0))},16)}},u),j=new function(){function i(e){}function t(e){var i="",t=m[e];t.solved?i="wpProQuiz_reviewQuestionSolved":t.review&&(i="wpProQuiz_reviewQuestionReview"),u.eq(e).removeClass("wpProQuiz_reviewQuestionSolved"),u.eq(e).removeClass("wpProQuiz_reviewQuestionReview"),""!=i&&u.eq(e).addClass(i)}function o(e){e.preventDefault();var i=e.pageY-p;i<0&&(i=0),i>d&&(i=d);var t=l*i;a.attr("style","margin-top: "+-t+"px !important"),r.css({top:i})}function n(i){i.preventDefault(),e(document).unbind(".scrollEvent")}var s=[],r=[],a=[],u=[],d=0,p=0,l=0,f=0,w=0,m=[];this.init=function(){s=c.find(".wpProQuiz_reviewQuestion"),r=s.find("div"),a=s.find("ol"),u=a.children(),r.mousedown(function(i){i.preventDefault(),i.stopPropagation(),p=i.pageY-r.offset().top+f,e(document).bind("mouseup.scrollEvent",n),e(document).bind("mousemove.scrollEvent",o)}),u.click(function(i){h.methode.showQuestion(e(this).index())}),c.bind("questionSolved",function(e){m[e.values.index].solved=e.values.solved,t(e.values.index)}),c.bind("changeQuestion",function(e){if("undefined"!=e.values.item[0]){e.values.item[0];h.methode.setupMatrixSortHeights()}u.removeClass("wpProQuiz_reviewQuestionTarget"),u.eq(e.values.index).addClass("wpProQuiz_reviewQuestionTarget"),i(e.values.index)}),c.bind("reviewQuestion",function(e){m[e.values.index].review=!m[e.values.index].review,t(e.values.index)})},this.show=function(e){if(k.reviewQustion&&s.parent().show(),c.find(".wpProQuiz_reviewDiv .wpProQuiz_button2").show(),!e){a.attr("style","margin-top: 0px !important"),r.css({top:0});var i=a.outerHeight(),t=s.height();d=t-r.height(),p=0,w=i-t,l=w/d,this.reset(),i>100&&r.show(),f=r.offset().top}},this.hide=function(){s.parent().hide()},this.toggle=function(){if(k.reviewQustion){s.parent().toggle(),u.removeClass("wpProQuiz_reviewQuestionTarget"),c.find(".wpProQuiz_reviewDiv .wpProQuiz_button2").hide(),a.attr("style","margin-top: 0px !important"),r.css({top:0});var e=a.outerHeight(),i=s.height();d=i-r.height(),p=0,w=e-i,l=w/d,e>100&&r.show(),f=r.offset().top}},this.reset=function(){for(var e=0,i=u.length;e<i;e++)m[e]={};u.removeClass("wpProQuiz_reviewQuestionTarget"),u.removeClass("wpProQuiz_reviewQuestionSolved"),u.removeClass("wpProQuiz_reviewQuestionReview")}},A=new o,E=function(i,t,o,n,s){null==s&&(s=!0);var r={},a={singleMulti:function(){var i=n.find(".wpProQuiz_questionInput");1==s&&n.find(".wpProQuiz_questionInput").attr("disabled","disabled"),jQuery(".wpProQuiz_questionListItem",n).each(function(t){var o=e(this),n=o.attr("data-pos");void 0!==n&&(r[n]=i.eq(t).is(":checked"))})},sort_answer:function(){var i=n.children();i.each(function(i,t){var o=e(this);r[i]=o.attr("data-pos")}),1==s&&n.sortable("destroy")},matrix_sort_answer:function(){var i=n.children();new Array;statistcAnswerData={0:-1},i.each(function(){var i=e(this),t=i.attr("data-pos"),o=i.find(".wpProQuiz_maxtrixSortCriterion"),n=o.children();n.length&&(statistcAnswerData[n.attr("data-pos")]=t),r=statistcAnswerData}),1==s&&o.find(".wpProQuiz_sortStringList, .wpProQuiz_maxtrixSortCriterion").sortable("destroy")},free_answer:function(){var e=n.children(),i=e.find(".wpProQuiz_questionInput").val();1==s&&e.find(".wpProQuiz_questionInput").attr("disabled","disabled"),r=i},cloze_answer:function(){r={},n.find(".wpProQuiz_cloze").each(function(i,t){var o=e(this),n=o.children(),a=n.eq(0),u=(n.eq(1),h.methode.cleanupCurlyQuotes(a.val()));r[i]=u,1==s&&a.attr("disabled","disabled")})},assessment_answer:function(){correct=!0;var i=n.find(".wpProQuiz_questionInput");1==s&&n.find(".wpProQuiz_questionInput").attr("disabled","disabled");var t=0;i.filter(":checked").each(function(){t+=parseInt(e(this).val())}),r=t},essay:function(){var e=o.find("ul.wpProQuiz_questionList").data("question_id");1==s&&n.find(".wpProQuiz_questionEssay").attr("disabled","disabled");var i=n.find(".wpProQuiz_questionEssay").val(),t=n.find("#uploadEssayFile_"+e).val();void 0!==i&&(r=i),void 0!==t&&(r=t)}};return a[i](),{response:r}},R=new function(){var i={isEmpty:function(i){return i=e.trim(i),!i||0===i.length}},t={TEXT:0,TEXTAREA:1,NUMBER:2,CHECKBOX:3,EMAIL:4,YES_NO:5,DATE:6,SELECT:7,RADIO:8};this.checkForm=function(){var o=!0;return c.find(".wpProQuiz_forms input, .wpProQuiz_forms textarea, .wpProQuiz_forms .wpProQuiz_formFields, .wpProQuiz_forms select").each(function(){var n=e(this),s=1==n.data("required"),r=n.data("type"),a=!0,u=e.trim(n.val());switch(r){case t.TEXT:case t.TEXTAREA:case t.SELECT:s&&(a=!i.isEmpty(u));break;case t.NUMBER:!s&&i.isEmpty(u)||(a=!i.isEmpty(u)&&!isNaN(u));break;case t.EMAIL:!s&&i.isEmpty(u)||(a=!i.isEmpty(u)&&new RegExp(/^[a-zA-Z0-9.!#$%&’*+\/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/).test(u));break;case t.CHECKBOX:s&&(a=n.is(":checked"));break;case t.YES_NO:case t.RADIO:s&&(a=void 0!==n.find('input[type="radio"]:checked').val());break;case t.DATE:var d=0,c=0;n.find("select").each(function(){d++,c+=i.isEmpty(e(this).val())?0:1}),(s||c>0)&&(a=d==c)}a?n.siblings(".wpProQuiz_invalidate").hide():(o=!1,n.siblings(".wpProQuiz_invalidate").show())}),o},this.getFormData=function(){var i={};return c.find(".wpProQuiz_forms input, .wpProQuiz_forms textarea, .wpProQuiz_forms .wpProQuiz_formFields, .wpProQuiz_forms select").each(function(){var o=e(this),n=o.data("form_id"),s=o.data("type");switch(s){case t.TEXT:case t.TEXTAREA:case t.SELECT:case t.NUMBER:case t.EMAIL:i[n]=o.val();break;case t.CHECKBOX:i[n]=o.is(":checked")?1:0;break;case t.YES_NO:case t.RADIO:i[n]=o.find('input[type="radio"]:checked').val();break;case t.DATE:i[n]={day:o.find('select[name="wpProQuiz_field_'+n+'_day"]').val(),month:o.find('select[name="wpProQuiz_field_'+n+'_month"]').val(),year:o.find('select[name="wpProQuiz_field_'+n+'_year"]').val()}}}),i}},D=function(i){c.find(".wpProQuiz_questionList").each(function(){var t=e(this),o=t.data("question_id"),n=t.data("type"),s={};if("single"==n||"multiple"==n)t.find(".wpProQuiz_questionListItem").each(function(){s[e(this).attr("data-pos")]=+e(this).find(".wpProQuiz_questionInput").is(":checked")});else if("free_answer"==n)s[0]=t.find(".wpProQuiz_questionInput").val();else{if("sort_answer"==n)return!0;if("matrix_sort_answer"==n)return!0;if("cloze_answer"==n){var r=0;t.find(".wpProQuiz_cloze input").each(function(){s[r++]=e(this).val()})}else if("assessment_answer"==n)s[0]="",t.find(".wpProQuiz_questionInput:checked").each(function(){s[e(this).data("index")]=e(this).val()});else if("essay"==n)return}i[o].data=s})};h.methode={parseBitOptions:function(){if(p.bo){k.randomAnswer=1&p.bo,k.randomQuestion=2&p.bo,k.disabledAnswerMark=4&p.bo,k.checkBeforeStart=8&p.bo,k.preview=16&p.bo,k.isAddAutomatic=64&p.bo,k.reviewQustion=128&p.bo,k.quizSummeryHide=256&p.bo,k.skipButton=512&p.bo,k.autoStart=1024&p.bo,k.forcingQuestionSolve=2048&p.bo,k.hideQuestionPositionOverview=4096&p.bo,k.formActivated=8192&p.bo,k.maxShowQuestion=16384&p.bo,k.sortCategories=32768&p.bo;var e=32&p.bo;e&&null!=jQuery.support&&null!=jQuery.support.cors&&0==jQuery.support.cors&&(k.cors=e)}},setClozeStyle:function(){c.find(".wpProQuiz_cloze input").each(function(){for(var i=e(this),t="",o=i.data("wordlen"),n=0;n<o;n++)t+="w";var s=e(document.createElement("span")).css("visibility","hidden").text(t).appendTo(e("body")),r=s.width();s.remove(),i.width(r+5)})},parseTime:function(e){var i=parseInt(e%60),t=parseInt(e/60%60),o=parseInt(e/3600%24);return i=(i>9?"":"0")+i,t=(t>9?"":"0")+t,o=(o>9?"":"0")+o,o+":"+t+":"+i},cleanupCurlyQuotes:function(i){return i=i.replace(/\u2018/,"'"),i=i.replace(/\u2019/,"'"),i=i.replace(/\u201C/,'"'),i=i.replace(/\u201D/,'"'),e.trim(i)},resetMatrix:function(i){i.each(function(){var i=e(this),t=i.find(".wpProQuiz_sortStringList");i.find(".wpProQuiz_sortStringItem").each(function(){t.append(e(this))})})},marker:function(e,i){k.disabledAnswerMark||(!0===i?e.addClass("wpProQuiz_answerCorrect"):!1===i?e.addClass("wpProQuiz_answerIncorrect"):e.addClass(i))},startQuiz:function(i){if(S.loadLock)S.isQuizStart=1;else{if(S.isQuizStart=0,S.isLocked)return I.quizStartPage.hide(),void c.find(".wpProQuiz_lock").show();if(S.isPrerequisite)return I.quizStartPage.hide(),void c.find(".wpProQuiz_prerequisite").show();if(S.isUserStartLocked)return I.quizStartPage.hide(),void c.find(".wpProQuiz_startOnlyRegisteredUser").show();if(k.maxShowQuestion&&!i){if(p.formPos==L.START&&!R.checkForm())return;return I.quizStartPage.hide(),c.find(".wpProQuiz_loadQuiz").show(),void h.methode.loadQuizDataAjax(!0)}if(!k.formActivated||p.formPos!=L.START||R.checkForm()){switch(h.methode.loadQuizData(),k.randomQuestion&&h.methode.random(I.questionList),k.randomAnswer&&h.methode.random(c.find(b.questionList)),k.sortCategories&&h.methode.sortCategories(),h.methode.random(c.find(".wpProQuiz_sortStringList")),h.methode.random(c.find('.wpProQuiz_questionList[data-type="sort_answer"]')),c.find(".wpProQuiz_listItem").each(function(i,t){var o=e(this);o.find(".wpProQuiz_question_page span:eq(0)").text(i+1),o.find("> h5 span").text(i+1),o.find(".wpProQuiz_questionListItem").each(function(i,t){e(this).find("> span:not(.wpProQuiz_cloze)").text(i+1+". ")})}),I.next=c.find(b.next),p.mode){case 3:c.find('input[name="checkSingle"]').show();break;case 2:c.find(b.check).show(),!k.skipButton&&k.reviewQustion&&c.find(b.skip).show();break;case 1:c.find('input[name="back"]').slice(1).show();case 0:I.next.show()}(k.hideQuestionPositionOverview||3==p.mode)&&c.find(".wpProQuiz_question_page").hide();var o=I.next.last();Q=o.val(),o.val(p.lbn);var n=I.questionList.children();if(I.listItems=c.find(".wpProQuiz_list > li"),3==p.mode)h.methode.showSinglePage(0);else{_=n.eq(0).show();var s=_.find(b.questionList).data("question_id");A.questionStart(s)}A.startQuiz(),c.find(".wpProQuiz_sortable").parents("ul").sortable({update:function(i,t){var o=e(this).parents(".wpProQuiz_listItem");c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}})}}).disableSelection(),c.find(".wpProQuiz_sortStringList, .wpProQuiz_maxtrixSortCriterion").sortable({connectWith:".wpProQuiz_maxtrixSortCriterion:not(:has(li)), .wpProQuiz_sortStringList",placeholder:"wpProQuiz_placehold",update:function(i,t){var o=e(this).parents(".wpProQuiz_listItem");c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}})}}).disableSelection(),v=[],C.start(),m=+new Date,f={comp:{points:0,correctQuestions:0,quizTime:0}},c.find(".wpProQuiz_questionList").each(function(){var i=e(this).data("question_id");f[i]={time:0}}),w={},e.each(t.catPoints,function(e,i){w[e]=0}),I.quizStartPage.hide(),c.find(".wpProQuiz_loadQuiz").hide(),I.quiz.show(),j.show(),h.methode.CookieInit(),h.methode.setupMatrixSortHeights(),3!=p.mode&&c.trigger({type:"changeQuestion",values:{item:_,index:_.index()}})}}},viewUserQuizStatistics:function(e){var i=jQuery(e).data("ref_id"),t=jQuery(e).data("quiz_id"),o={action:"wp_pro_quiz_admin_ajax",func:"statisticLoadUser",data:{quizId:t,userId:0,refId:i,avg:0}};jQuery("#wpProQuiz_user_overlay, #wpProQuiz_loadUserData").show();var n=jQuery("#wpProQuiz_user_content").hide();jQuery.ajax({type:"POST",url:WpProQuizGlobal.ajaxurl,dataType:"json",cache:!1,data:o,error:function(e,i,t){},success:function(e){void 0!==e.html&&(n.html(e.html),jQuery("#wpProQuiz_user_content").show(),jQuery("#wpProQuiz_loadUserData").hide(),n.find(".statistic_data").click(function(){return jQuery(this).parents("tr").next().toggle("fast"),!1}))}}),jQuery("#wpProQuiz_overlay_close").click(function(){jQuery("#wpProQuiz_user_overlay").hide()})},showSingleQuestion:function(e){var i=e?Math.ceil(e/p.qpp):1;this.showSinglePage(i)},showSinglePage:function(e){if($listItem=I.questionList.children().hide(),p.qpp){e=e?+e:1;var i=Math.ceil(c.find(".wpProQuiz_list > li").length/p.qpp);if(!(e>i)){var t=c.find(b.singlePageLeft).hide(),o=c.find(b.singlePageRight).hide(),n=c.find('input[name="checkSingle"]').hide();e>1&&t.val(t.data("text").replace(/%d/,e-1)).show(),e==i?n.show():o.val(o.data("text").replace(/%d/,e+1)).show(),P=e;var s=p.qpp*(e-1);$listItem.slice(s,s+p.qpp).show(),h.methode.scrollTo(I.quiz)}}else $listItem.show()},nextQuestion:function(){h.methode.CookieProcessQuestionResponse(_),jQuery(".mejs-pause").trigger("click"),this.showQuestionObject(_.next())},prevQuestion:function(){this.showQuestionObject(_.prev())},showQuestion:function(e){var i=I.listItems.eq(e);if(3==p.mode||z)return p.qpp&&h.methode.showSingleQuestion(e+1),h.methode.scrollTo(i,1),void A.startQuiz();this.showQuestionObject(i)},showQuestionObject:function(i){if(!i.length&&k.forcingQuestionSolve&&k.quizSummeryHide&&k.reviewQustion){list=I.questionList.children(),null!=list&&list.each(function(){var i=e(this),t=i.find(b.questionList),o=(t.data("question_id"),p.json[t.data("question_id")]);"sort_answer"==o.type&&c.trigger({type:"questionSolved",values:{item:i,index:i.index(),solved:!0}})});for(var t=0,o=c.find(".wpProQuiz_listItem").length;t<o;t++)if(!v[t])return alert(WpProQuizGlobal.questionsNotSolved),!1}if(_.hide(),_=i.show(),h.methode.scrollTo(I.quiz),c.trigger({type:"changeQuestion",values:{item:_,index:_.index()}}),_.length){var n=_.find(b.questionList).data("question_id");A.questionStart(n)}else h.methode.showQuizSummary()},skipQuestion:function(){c.trigger({type:"skipQuestion",values:{item:_,index:_.index()}}),h.methode.nextQuestion()},reviewQuestion:function(){c.trigger({type:"reviewQuestion",values:{item:_,index:_.index()}})},uploadFile:function(i){var t=i.currentTarget.id.replace("uploadEssaySubmit_",""),o=e("#uploadEssay_"+t)[0].files[0];if(void 0!==o){var n=e("#_uploadEssay_nonce_"+t).val(),s=e("#uploadEssaySubmit_"+t);s.val(p.essayUploading);var r=new FormData;r.append("action","learndash_upload_essay"),r.append("nonce",n),r.append("question_id",t),r.append("course_id",p.course_id),r.append("essayUpload",o),e.ajax({method:"POST",type:"POST",url:WpProQuizGlobal.ajaxurl,data:r,cache:!1,contentType:!1,processData:!1,success:function(i){if(1==i.success&&void 0!==i.data.filelink){e("#uploadEssayFile_"+t).val(i.data.filelink),s.attr("disabled","disabled"),setTimeout(function(){s.val(p.essaySuccess)},1500);var o=e("#uploadEssayFile_"+t).parents(".wpProQuiz_listItem");c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!0}})}else s.removeAttr("disabled"),s.val("Failed. Try again.")}})}i.preventDefault()},showQuizSummary:function(){if(A.questionStop(),A.stopQuiz(),!k.quizSummeryHide&&k.reviewQustion){var i=c.find(".wpProQuiz_checkPage");i.find("ol:eq(0)").empty().append(c.find(".wpProQuiz_reviewQuestion ol li").clone().removeClass("wpProQuiz_reviewQuestionTarget")).children().click(function(t){i.hide(),I.quiz.show(),j.show(!0),h.methode.showQuestion(e(this).index())});for(var t=0,o=0,n=v.length;o<n;o++)v[o]&&t++;i.find("span:eq(0)").text(t),j.hide(),I.quiz.hide(),i.show(),h.methode.scrollTo(i)}else k.formActivated&&p.formPos==L.END?(j.hide(),I.quiz.hide(),h.methode.scrollTo(c.find(".wpProQuiz_infopage").show())):h.methode.finishQuiz()},finishQuiz:function(e){I.next.last().attr("disabled","disabled"),c.find('input[name="checkSingle"]').attr("disabled","disabled"),A.questionStop(),A.stopQuiz(),C.stop();var i=(+new Date-m)/1e3;i=p.timelimit&&i>p.timelimit?p.timelimit:i,g=i,c.find(".wpProQuiz_quiz_time span").text(h.methode.parseTime(i)),e&&I.results.find(".wpProQuiz_time_limit_expired").show(),h.methode.checkQuestion(I.questionList.children(),!0)},finishQuizEnd:function(){c.find(".wpProQuiz_correct_answer").text(f.comp.correctQuestions),f.comp.result=Math.round(f.comp.points/p.globalPoints*100*100)/100;var i=!1;if(e.each(f,function(){void 0!==this.graded_status&&"not_graded"==this.graded_status&&(i=!0)}),"undefined"!=typeof certificate_details&&null!=certificate_details.certificateLink&&""!=certificate_details.certificateLink&&f.comp.result>=100*certificate_details.certificate_threshold){var o=c.find(".wpProQuiz_certificate");1==i&&"undefined"!=typeof certificate_pending&&o.html(certificate_pending),o.show()}var n=c.find(".quiz_continue_link"),s=!1;jQuery(n).hasClass("show_quiz_continue_buttom_on_fail")&&(s=!0),void 0!==t.passingpercentage&&parseFloat(t.passingpercentage)>=0?f.comp.result>=t.passingpercentage||s?"undefined"!=typeof continue_details&&(c.find(".quiz_continue_link").html(continue_details),c.find(".quiz_continue_link").show()):c.find(".quiz_continue_link").hide():"undefined"!=typeof continue_details&&(c.find(".quiz_continue_link").html(continue_details),c.find(".quiz_continue_link").show()),$pointFields=c.find(".wpProQuiz_points span"),$gradedPointsFields=c.find(".wpProQuiz_graded_points span"),$pointFields.eq(0).text(f.comp.points),$pointFields.eq(1).text(p.globalPoints),$pointFields.eq(2).text(f.comp.result+"%"),$gradedQuestionCount=0,$gradedQuestionPoints=0,e.each(f,function(i,t){if(e.isNumeric(i)&&t.graded_id){var o=t.possiblePoints-t.points;o>0&&($gradedQuestionPoints+=o,$gradedQuestionCount++)}}),$gradedQuestionCount>0&&(e(".wpProQuiz_points").hide(),e(".wpProQuiz_graded_points").show(),$gradedPointsFields.eq(0).text(f.comp.points),$gradedPointsFields.eq(1).text(p.globalPoints),$gradedPointsFields.eq(2).text(f.comp.result+"%"),$gradedPointsFields.eq(3).text($gradedQuestionCount),$gradedPointsFields.eq(4).text($gradedQuestionPoints)),c.find(".wpProQuiz_resultsList > li").eq(h.methode.findResultIndex(f.comp.result)).show(),h.methode.setAverageResult(f.comp.result,!1),this.setCategoryOverview(),h.methode.sendCompletedQuiz(),k.isAddAutomatic&&T.isUser&&h.methode.addToplist(),j.hide(),c.find(".wpProQuiz_checkPage, .wpProQuiz_infopage").hide(),I.quiz.hide()},sending:function(e,i,t){I.sending.show();var o,n=I.sending.find(".sending_progress_bar");if(o=null==typeof e||null==e?parseInt(100*n.width()/n.offsetParent().width())+156:e,null==i)i=80;null==t&&(t=1),null!=q&&null!=typeof q&&clearInterval(q),q=setInterval(function(){var e=parseInt(100*n.width()/n.offsetParent().width());e>=i&&(clearInterval(q),e>=100&&setTimeout(h.methode.showResults(),2e3)),n.css("width",o+"%"),o+=t},300)},showResults:function(){I.sending.hide(),I.results.show(),h.methode.scrollTo(I.results)},setCategoryOverview:function(){f.comp.cats={},c.find(".wpProQuiz_catOverview li").each(function(){var i=e(this),t=i.data("category_id");if(void 0===p.catPoints[t])return i.hide(),!0;var o=Math.round(w[t]/p.catPoints[t]*100*100)/100;f.comp.cats[t]=o,i.find(".wpProQuiz_catPercent").text(o+"%"),i.show()})},questionSolved:function(e){v[e.values.index]=e.values.solved},sendCompletedQuiz:function(){if(!k.preview){D(f);var e=R.getFormData();jQuery.ajax({type:"POST",url:WpProQuizGlobal.ajaxurl,dataType:"json",cache:!1,data:{action:"wp_pro_quiz_completed_quiz",course_id:p.course_id,lesson_id:p.lesson_id,topic_id:p.topic_id,quiz:p.quiz,quizId:p.quizId,results:JSON.stringify(f),timespent:g,forms:e,quiz_nonce:p.quiz_nonce},success:function(e){if(null!=e&&void 0!==p.quizId){var i=parseInt(p.quizId);void 0!==e[i]&&void 0!==e[i].quiz_result_settings&&(l=e[i].quiz_result_settings,h.methode.afterSendUpdateIU(l))}h.methode.sending(null,100,15),h.methode.CookieDelete()}})}},afterSendUpdateIU:function(e){void 0!==e.showAverageResult&&(e.showAverageResult||c.find(".wpProQuiz_resultTable").remove()),void 0!==e.showCategoryScore&&(e.showCategoryScore||c.find(".wpProQuiz_catOverview").remove()),void 0!==e.showRestartQuizButton&&(e.showRestartQuizButton||c.find('input[name="restartQuiz"]').remove()),void 0!==e.showResultPoints&&(e.showResultPoints||c.find(".wpProQuiz_points").remove()),void 0!==e.showResultQuizTime&&(e.showResultQuizTime||c.find(".wpProQuiz_quiz_time").remove()),void 0!==e.showViewQuestionButton&&(e.showViewQuestionButton||c.find('input[name="reShowQuestion"]').remove()),void 0!==e.showContinueButton&&(e.showContinueButton||c.find(".quiz_continue_link").remove())},findResultIndex:function(e){for(var i=p.resultsGrade,t=-1,o=999999,n=0;n<i.length;n++){var s=i[n];e>=s&&e-s<o&&(o=e-s,t=n)}return t},showQustionList:function(){z=!z,I.toplistShowInButton.hide(),I.quiz.toggle(),c.find(".wpProQuiz_QuestionButton").hide(),I.questionList.children().show(),j.toggle(),c.find(".wpProQuiz_question_page").hide()},random:function(i){i.each(function(){var i=e(this).children().get().sort(function(){return Math.round(Math.random())-.5});e(i).appendTo(i[0].parentNode)})},sortCategories:function(){var i=e(".wpProQuiz_list").children().get().sort(function(i,t){var o=e(i).find(".wpProQuiz_questionList").data("question_id"),n=e(t).find(".wpProQuiz_questionList").data("question_id");return p.json[o].catId-p.json[n].catId});e(i).appendTo(i[0].parentNode)},restartQuiz:function(){I.results.hide(),I.questionList.children().hide(),I.toplistShowInButton.hide(),j.hide(),c.find(".wpProQuiz_questionInput, .wpProQuiz_cloze input").removeAttr("disabled").removeAttr("checked").css("background-color",""),c.find('.wpProQuiz_questionListItem input[type="text"]').val(""),c.find(".wpProQuiz_answerCorrect, .wpProQuiz_answerIncorrect").removeClass("wpProQuiz_answerCorrect wpProQuiz_answerIncorrect"),c.find(".wpProQuiz_listItem").data("check",!1),c.find("textarea.wpProQuiz_questionEssay").val(""),c.find("input.uploadEssayFile").val(""),c.find("input.wpProQuiz_upload_essay").val(""),c.find(".wpProQuiz_response").hide().children().hide(),h.methode.resetMatrix(c.find(".wpProQuiz_listItem")),c.find(".wpProQuiz_sortStringItem, .wpProQuiz_sortable").removeAttr("style"),c.find(".wpProQuiz_clozeCorrect, .wpProQuiz_QuestionButton, .wpProQuiz_resultsList > li").hide(),c.find('.wpProQuiz_question_page, input[name="tip"]').show(),c.find(".wpProQuiz_certificate").attr("style","display: none !important"),I.results.find(".wpProQuiz_time_limit_expired").hide(),I.next.last().val(Q),z=!1,window.location.reload(!0)},showSpinner:function(){c.find(".wpProQuiz_spinner").show()},hideSpinner:function(){c.find(".wpProQuiz_spinner").hide()},checkQuestion:function(i,t){var o=null!=i,n={};i=null==i?_:i,i.each(function(){var i=e(this),t=i.index(),o=i.find(b.questionList),s=o.data("question_id"),r=p.json[o.data("question_id")],a=r.type;if(A.questionStop(),i.data("check"))return!0;"single"!=r.type&&"multiple"!=r.type||(a="singleMulti"),n[s]=E(a,r,i,o,!0),n[s].question_pro_id=r.id,n[s].question_post_id=r.question_post_id,h.methode.CookieSaveResponse(s,t,r.type,n[s])}),p.checkAnswers={list:i,responses:n,endCheck:t,finishQuiz:o},o?h.methode.sending(1,80,3):h.methode.showSpinner(),h.methode.ajax({action:"ld_adv_quiz_pro_ajax",func:"checkAnswers",data:{quizId:p.quizId,quiz:p.quiz,course_id:p.course_id,quiz_nonce:p.quiz_nonce,responses:JSON.stringify(n)}},function(i){h.methode.hideSpinner();var t=p.checkAnswers.list,o=(p.checkAnswers.responses,p.checkAnswers.r,p.checkAnswers.endCheck),n=p.checkAnswers.finishQuiz;t.each(function(){var t=e(this),n=t.find(b.questionList),s=n.data("question_id");if(t.data("check"))return!0;if(void 0!==i[s]){var r=i[s];data=p.json[n.data("question_id")],t.find(".wpProQuiz_response").show(),t.find(b.check).hide(),t.find(b.skip).hide(),t.find(b.next).show(),f[data.id].points=r.p,void 0!==r.p_nonce?f[data.id].p_nonce=r.p_nonce:f[data.id].p_nonce="",f[data.id].correct=Number(r.c),f[data.id].data=r.s,void 0!==r.a_nonce?f[data.id].a_nonce=r.a_nonce:f[data.id].a_nonce="",f[data.id].possiblePoints=r.e.possiblePoints,jQuery.isEmptyObject(f[data.id].data)&&(null==r.e.type||"sort_answer"!=r.e.type&&"matrix_sort_answer"!=r.e.type||(f[data.id].data=r.e.r)),void 0!==r.e.graded_id&&r.e.graded_id>0&&(f[data.id].graded_id=r.e.graded_id),void 0!==r.e.graded_status&&(f[data.id].graded_status=r.e.graded_status),f.comp.points+=r.p,t.find(".wpProQuiz_response").show(),t.find(b.check).hide(),t.find(b.skip).hide(),t.find(b.next).show(),jQuery.isEmptyObject(f[data.id].data)&&void 0!==r.e.type&&("sort_answer"!=r.e.type&&"matrix_sort_answer"!=r.e.type||void 0!==r.e.r&&(f[data.id].data=r.e.r),"essay"==r.e.type&&void 0!==r.e.graded_id&&(f[data.id].data={graded_id:r.e.graded_id})),w[data.catId]+=r.p,h.methode.markCorrectIncorrect(r,t,n),r.c?(void 0!==r.e.AnswerMessage&&(t.find(".wpProQuiz_correct").find(".wpProQuiz_AnswerMessage").html(r.e.AnswerMessage),t.find(".wpProQuiz_correct").trigger("learndash-quiz-answer-response-contentchanged")),t.find(".wpProQuiz_correct").show(),f.comp.correctQuestions+=1):(void 0!==r.e.AnswerMessage&&(t.find(".wpProQuiz_incorrect").find(".wpProQuiz_AnswerMessage").html(r.e.AnswerMessage),t.find(".wpProQuiz_incorrect").trigger("learndash-quiz-answer-response-contentchanged")),t.find(".wpProQuiz_incorrect").show()),t.find(".wpProQuiz_responsePoints").text(r.p),t.data("check",!0),o||c.trigger({type:"questionSolved",values:{item:t,index:t.index(),solved:!0}})}}),n&&h.methode.finishQuizEnd()})},markCorrectIncorrect:function(i,t,o){if(void 0!==i.e.c)switch(i.e.type){case"single":case"multiple":o.children().each(function(t){var o=e(this),n=o.attr("data-pos");if(i.e.c[n]){var s=e("input.wpProQuiz_questionInput",o).is(":checked");s?h.methode.marker(o,!0):h.methode.marker(o,"wpProQuiz_answerCorrectIncomplete")}else!i.c&&i.e.r[n]&&h.methode.marker(o,!1)});break;case"free_answer":var n=o.children();i.c?h.methode.marker(n,!0):h.methode.marker(n,!1);break;case"cloze_answer":o.find(".wpProQuiz_cloze").each(function(t,o){var n=e(this),s=n.children(),r=s.eq(0),a=s.eq(1);h.methode.cleanupCurlyQuotes(r.val());i.s[t]?r.addClass("wpProQuiz_answerCorrect"):(r.addClass("wpProQuiz_answerIncorrect"),void 0!==i.e.c[t]&&(a.html("("+i.e.c[t].join()+")"),a.show())),r.attr("disabled","disabled")});break;case"sort_answer":var s=o.children();s.each(function(t,o){var n=e(this);i.e.c[t]==n.attr("data-pos")?h.methode.marker(n,!0):h.methode.marker(n,!1)}),s.children().css({"box-shadow":"0 0",cursor:"auto"});var r=new Array;jQuery.each(i.e.c,function(e,i){r[i]=e}),s.sort(function(i,t){return r[e(i).attr("data-pos")]>r[e(t).attr("data-pos")]?1:-1}),o.append(s);break;case"matrix_sort_answer":s=o.children();var a=new Array;statistcAnswerData={0:-1},s.each(function(){var t=e(this),o=(t.attr("data-pos"),t.find(".wpProQuiz_maxtrixSortCriterion")),n=o.children(),s=n.attr("data-pos");n.length&&i.e.c[s]==t.attr("data-pos")?h.methode.marker(t,!0):h.methode.marker(t,!1),a[s]=o}),h.methode.resetMatrix(t),t.find(".wpProQuiz_sortStringItem").each(function(){var i=a[e(this).attr("data-pos")];null!=i&&i.append(this)}).css({"box-shadow":"0 0",cursor:"auto"})}},showTip:function(){var i=e(this),t=i.siblings(".wpProQuiz_question").find(b.questionList).data("question_id");i.siblings(".wpProQuiz_tipp").toggle("fast"),f[t].tip=1,e(document).bind("mouseup.tipEvent",function(i){var t=c.find(".wpProQuiz_tipp"),o=c.find('input[name="tip"]');t.is(i.target)||0!=t.has(i.target).length||o.is(i.target)||(t.hide("fast"),e(document).unbind(".tipEvent"))})},ajax:function(i,t,o){o=o||"json",k.cors&&(jQuery.support.cors=!0),void 0===i.quiz&&(i.quiz=p.quiz),void 0===i.course_id&&(i.course_id=p.course_id),void 0===i.quiz_nonce&&(i.quiz_nonce=p.quiz_nonce),e.ajax({method:"POST",type:"POST",url:WpProQuizGlobal.ajaxurl,data:i,success:t,dataType:o}),k.cors&&(jQuery.support.cors=!1)},checkQuizLock:function(){S.loadLock=1,h.methode.ajax({action:"wp_pro_quiz_check_lock",quizId:p.quizId},function(e){null!=e.lock&&(S.isLocked=e.lock.is,e.lock.pre&&c.find('input[name="restartQuiz"]').hide()),null!=e.prerequisite&&(S.isPrerequisite=1,c.find(".wpProQuiz_prerequisite span").text(e.prerequisite)),null!=e.startUserLock&&(S.isUserStartLocked=e.startUserLock),S.loadLock=0,S.isQuizStart&&h.methode.startQuiz()})},loadQuizData:function(){h.methode.ajax({action:"wp_pro_quiz_load_quiz_data",quizId:p.quizId},function(e){e.toplist&&h.methode.handleToplistData(e.toplist),null!=e.averageResult&&h.methode.setAverageResult(e.averageResult,!0)})},setAverageResult:function(e,i){var t=c.find(".wpProQuiz_resultValue:eq("+(i?0:1)+") > * ");t.eq(1).text(e+"%"),t.eq(0).css("width",240*e/100+"px")},handleToplistData:function(e){var i=c.find(".wpProQuiz_addToplist"),t=i.find(".wpProQuiz_addBox").show().children("div");if(e.canAdd)if(i.show(), i.find(".wpProQuiz_addToplistMessage").hide(),i.find(".wpProQuiz_toplistButton").show(),T.token=e.token,T.isUser=0,e.userId)t.hide(),T.isUser=1,k.isAddAutomatic&&i.hide();else{t.show();var o=t.children().eq(1);e.captcha?(o.find('input[name="wpProQuiz_captchaPrefix"]').val(e.captcha.code),o.find(".wpProQuiz_captchaImg").attr("src",e.captcha.img),o.find('input[name="wpProQuiz_captcha"]').val(""),o.show()):o.hide()}else i.hide()},scrollTo:function(i,t){var o=i.offset().top-100;(t||(window.pageYOffset||document.body.scrollTop)>o)&&e("html,body").animate({scrollTop:o},300)},addToplist:function(){if(!k.preview){var e=c.find(".wpProQuiz_addToplistMessage").text(WpProQuizGlobal.loadData).show(),i=c.find(".wpProQuiz_addBox").hide();h.methode.ajax({action:"wp_pro_quiz_add_toplist",quizId:p.quizId,quiz:p.quiz,token:T.token,name:i.find('input[name="wpProQuiz_toplistName"]').val(),email:i.find('input[name="wpProQuiz_toplistEmail"]').val(),captcha:i.find('input[name="wpProQuiz_captcha"]').val(),prefix:i.find('input[name="wpProQuiz_captchaPrefix"]').val(),results:f,timespent:g},function(t){e.text(t.text),t.clear?(i.hide(),h.methode.updateToplist()):i.show(),t.captcha&&(i.find(".wpProQuiz_captchaImg").attr("src",t.captcha.img),i.find('input[name="wpProQuiz_captchaPrefix"]').val(t.captcha.code),i.find('input[name="wpProQuiz_captcha"]').val(""))})}},updateToplist:function(){"function"==typeof wpProQuiz_fetchToplist&&wpProQuiz_fetchToplist()},registerSolved:function(){c.find('.wpProQuiz_questionInput[type="text"]').change(function(i){var t=e(this),o=t.parents(".wpProQuiz_listItem"),n=!1;""!=t.val()&&(n=!0),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:n}})}),c.find('.wpProQuiz_questionList[data-type="single"] .wpProQuiz_questionInput, .wpProQuiz_questionList[data-type="assessment_answer"] .wpProQuiz_questionInput').change(function(i){var t=e(this),o=t.parents(".wpProQuiz_listItem"),n=this.checked;c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:n}})}),c.find(".wpProQuiz_cloze input").change(function(){var i=e(this),t=i.parents(".wpProQuiz_listItem"),o=!0;t.find(".wpProQuiz_cloze input").each(function(){if(""==e(this).val())return o=!1,!1}),c.trigger({type:"questionSolved",values:{item:t,index:t.index(),solved:o}})}),c.find('.wpProQuiz_questionList[data-type="multiple"] .wpProQuiz_questionInput').change(function(i){var t=e(this),o=t.parents(".wpProQuiz_listItem"),n=0;o.find('.wpProQuiz_questionList[data-type="multiple"] .wpProQuiz_questionInput').each(function(e){this.checked&&n++}),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:!!n}})}),c.find('.wpProQuiz_questionList[data-type="essay"] textarea.wpProQuiz_questionEssay').change(function(i){var t=e(this),o=t.parents(".wpProQuiz_listItem"),n=!1;""!=t.val()&&(n=!0),c.trigger({type:"questionSolved",values:{item:o,index:o.index(),solved:n}})})},loadQuizDataAjax:function(i){h.methode.ajax({action:"wp_pro_quiz_admin_ajax",func:"quizLoadData",data:{quizId:p.quizId,quiz:p.quiz,quiz_nonce:p.quiz_nonce}},function(t){p.globalPoints=t.globalPoints,p.catPoints=t.catPoints,p.json=t.json,I.quiz.remove(),c.find(".wpProQuiz_quizAnker").after(t.content),e("table.wpProQuiz_toplistTable caption span.wpProQuiz_max_points").html(p.globalPoints),I={back:c.find('input[name="back"]'),next:c.find(b.next),quiz:c.find(".wpProQuiz_quiz"),questionList:c.find(".wpProQuiz_list"),results:c.find(".wpProQuiz_results"),sending:c.find(".wpProQuiz_sending"),quizStartPage:c.find(".wpProQuiz_text"),timelimit:c.find(".wpProQuiz_time_limit"),toplistShowInButton:c.find(".wpProQuiz_toplistShowInButton"),listItems:e()},h.methode.initQuiz(),i&&h.methode.startQuiz(!0);var o=t.content,n=o.search("wp-audio-shortcode"),s=o.search("wp-video-shortcode");"-1"==n&&"-1"==s||(e.getScript(t.site_url+"/wp-includes/js/mediaelement/mediaelement-and-player.min.js"),e.getScript(t.site_url+"/wp-includes/js/mediaelement/wp-mediaelement.js"),e("<link/>",{rel:"stylesheet",type:"text/css",href:t.site_url+"/wp-includes/js/mediaelement/mediaelementplayer.min.css"}).appendTo("head"))})},nextQuestionClicked:function(){var e=_.find(b.questionList),i=p.json[e.data("question_id")];if("sort_answer"==i.type){var t=_.index();void 0===v[t]&&c.trigger({type:"questionSolved",values:{item:_,index:t,solved:!0}})}if(k.forcingQuestionSolve&&!v[_.index()]&&(k.quizSummeryHide||!k.reviewQustion))return alert(WpProQuizGlobal.questionNotSolved),!1;h.methode.nextQuestion()},initQuiz:function(){h.methode.setClozeStyle(),h.methode.registerSolved(),I.next.click(h.methode.nextQuestionClicked),I.back.click(function(){h.methode.prevQuestion()}),c.find(b.check).click(function(){if(k.forcingQuestionSolve&&!v[_.index()]&&(k.quizSummeryHide||!k.reviewQustion))return alert(WpProQuizGlobal.questionNotSolved),!1;h.methode.checkQuestion()}),c.find('input[name="checkSingle"]').click(function(){if(list=I.questionList.children(),null!=list&&list.each(function(){var i=e(this),t=i.find(b.questionList),o=(t.data("question_id"),p.json[t.data("question_id")]);"sort_answer"==o.type&&c.trigger({type:"questionSolved",values:{item:i,index:i.index(),solved:!0}})}),k.forcingQuestionSolve&&(k.quizSummeryHide||!k.reviewQustion))for(var i=0,t=c.find(".wpProQuiz_listItem").length;i<t;i++)if(!v[i])return alert(WpProQuizGlobal.questionsNotSolved),!1;h.methode.showQuizSummary()}),c.find('input[name="tip"]').click(h.methode.showTip),c.find('input[name="skip"]').click(h.methode.skipQuestion),c.find('input[name="wpProQuiz_pageLeft"]').click(function(){h.methode.showSinglePage(P-1),h.methode.setupMatrixSortHeights()}),c.find('input[name="wpProQuiz_pageRight"]').click(function(){h.methode.showSinglePage(P+1),h.methode.setupMatrixSortHeights()}),c.find('input[id^="uploadEssaySubmit"]').click(h.methode.uploadFile),c.trigger("learndash-quiz-init")},CookieInit:function(){0!=p.timelimitcookie&&(y="ld_"+p.quizId+"_quiz_responses",x=jQuery.cookie(y),x=""==x||null==x?{}:JSON.parse(x),h.methode.CookieSetResponses(),h.methode.CookieResponseTimer())},CookieDelete:function(){0!=p.timelimitcookie&&(y="ld_"+p.quizId+"_quiz_responses",jQuery.cookie(y,""))},CookieProcessQuestionResponse:function(i){null!=i&&i.each(function(){var i=e(this),t=i.index(),o=i.find(b.questionList),n=o.data("question_id"),s=p.json[o.data("question_id")],r=s.type;"single"!=s.type&&"multiple"!=s.type||(r="singleMulti");var a=E(r,s,i,o,!1);h.methode.CookieSaveResponse(n,t,s.type,a)})},CookieSaveResponse:function(e,i,t,o){if(0!=p.timelimitcookie){x[e]={index:i,value:o.response,type:t};var n=new Date;n.setTime(n.getTime()+1e3*p.timelimitcookie),jQuery.cookie(y,JSON.stringify(x),{expires:n})}},CookieResponseTimer:function(){0!=p.timelimitcookie&&c.bind("questionSolved",function(e){h.methode.CookieProcessQuestionResponse(e.values.item)})},CookieSetResponses:function(){if(0!=p.timelimitcookie&&null!=x&&Object.keys(x).length){var i=I.questionList.children();i.each(function(){var i=e(this),t=i.find(b.questionList),o=t.data("question_id");if(null!=x[o]){var s=x[o],r=p.json[t.data("question_id")];r.type===s.type&&n(r,s.value,i,t)}})}},setupMatrixSortHeights:function(){e("li.wpProQuiz_listItem",I.questionList).each(function(i,t){var o=e(t).data("type");if("matrix_sort_answer"===o){var n=0;e("ul.wpProQuiz_sortStringList li",t).each(function(i,t){var o=e(t).outerHeight();o>n&&(n=o)}),n>0&&e("ul.wpProQuiz_sortStringList",t).css("min-height",n),e("ul.wpProQuiz_maxtrixSortCriterion",t).each(function(i,t){var o=e(t).parent("td");if(void 0!==o){var n=e(o).height();e(t).css("height",n),e(t).css("min-height",n)}})}})}},h.preInit=function(){h.methode.parseBitOptions(),j.init(),c.find('input[name="startQuiz"]').click(function(){return h.methode.startQuiz(),!1}),c.find('input[name="viewUserQuizStatistics"]').click(function(){return h.methode.viewUserQuizStatistics(this),!1}),k.checkBeforeStart&&!k.preview&&h.methode.checkQuizLock(),c.find('input[name="reShowQuestion"]').click(function(){h.methode.showQustionList()}),c.find('input[name="restartQuiz"]').click(function(){h.methode.restartQuiz()}),c.find('input[name="review"]').click(h.methode.reviewQuestion),c.find('input[name="wpProQuiz_toplistAdd"]').click(h.methode.addToplist),c.find('input[name="quizSummary"]').click(h.methode.showQuizSummary),c.find('input[name="endQuizSummary"]').click(function(){if(k.forcingQuestionSolve){list=I.questionList.children(),null!=list&&list.each(function(){var i=e(this),t=i.find(b.questionList),o=(t.data("question_id"),p.json[t.data("question_id")]);if("sort_answer"==o.type){var n=i.index();void 0===v[n]&&c.trigger({type:"questionSolved",values:{item:i,index:n,solved:!0}})}});for(var i=0,t=c.find(".wpProQuiz_listItem").length;i<t;i++)if(!v[i])return alert(WpProQuizGlobal.questionsNotSolved),!1}k.formActivated&&p.formPos==L.END&&!R.checkForm()||h.methode.finishQuiz()}),c.find('input[name="endInfopage"]').click(function(){R.checkForm()&&h.methode.finishQuiz()}),c.find('input[name="showToplist"]').click(function(){I.quiz.hide(),I.toplistShowInButton.toggle()}),c.bind("questionSolved",h.methode.questionSolved),k.maxShowQuestion||h.methode.initQuiz(),k.autoStart&&h.methode.startQuiz()},h.preInit()},e.fn.wpProQuizFront=function(i){return this.each(function(){null==e(this).data("wpProQuizFront")&&e(this).data("wpProQuizFront",new e.wpProQuizFront(this,i))})}})(jQuery); readme.txt 0000666 00000022530 15214236625 0006556 0 ustar 00 === Wp-Pro-Quiz === Contributors: xeno010 Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=N9B7S4FT8CE2N Tags: quiz, test, answer, question, learning, assessment Requires at least: 3.3 Tested up to: 3.6.1 Stable tag: 0.28 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html A powerful and beautiful quiz plugin for WordPress. == Description == A powerful and beautiful quiz plugin for WordPress. = Functions = * Single Choice * Multiple Choice * "Sorting" Choice * "Free" Choice * "Matrix Sorting" Choice * Cloze function * Assessment * Timelimit * Random Answer * Random Question * HTML in questions and answers is allowed * Multimedia in questions * Back-Button * Correct / incorrect response message for all questions * Different valency for every question * Different points for each answer * Result text with gradations * Preview-function * Statistics * Leaderboard * Quiz requirements * Hints * Custom fields * Import / Export function * E-mail notification * Category support * Quiz-summary * Many configuration options * Really nice standard design * Mighty * Fully compatible with cache plugins (e.g. WP-Super-Cache or W3 Total Cache) = Translations = * Arabic / عربي (Thanks Abuhassan) * Brazilian Portuguese / Português do Brasil (Thanks Gabriel V.) * Czech / čeština (Thanks Petr Š.) * Danish / dansk (Thanks Kenneth D.) * Dutch / nederlands (Thanks Bas W. and Jurriën van den H.) * English (Thanks Alexander M.) * French / français (Thanks Aurélien C.) * German / deutsch * Greek / ελληνικά (Thanks Ζαχαρίας Σ.) * Indonesian / Bahasa Indonesia (Thanks dieka91 and Creative Computer Club) * Norwegian / norsk (Thanks Stein Ivar J.) * Persian / فارسی (Thanks Behrooz N.) * Russian / русский (Thanks Sergei B. and Alex A.) * Spanish / español (Thanks Carlos R.) * Swedish / svenska (Thanks Martin J.) = Live Demo = http://www.it-gecko.de/wp-pro-quiz-quiz-plugin-fuer-wordpress.html (scroll to "Demo") = Special = * Support for "User Role Editor" etc. * Support for BuddyPress achievements 3.x.x = Support = * English: http://wordpress.org/support/plugin/wp-pro-quiz * German/Deutsch: http://www.it-gecko.de/kontakt == Installation == 1. Upload the wp-pro-quiz folder to the /wp-content/plugins/ directory 2. Activate the plugin through the 'Plugins' menu in WordPress == Screenshots == 1. Quiz demo - Start page 2. Quiz demo - Correkt message 3. Quiz demo - Multimedia 4. Quiz demo - Results 5. Quiz demo2 - Time limit and back button 6. Quiz demo - Leadboard 7. Quiz demo - Average score 8. Adminmenu - Quiz overview 9. Adminmenu - Create quiz 10. Adminmenu - Quiz question overview 11. Adminmenu - Create question 12. Adminmenu - Question statistics == Changelog == = 0.1 = * release = 0.2 = * bugfix * add statistics function * small changes = 0.3 = * added version number for js and css = 0.4 = * added hint support * bug in sort choice were fixed * mistranslations were fixed = 0.5 = * New choice: "Matrix Sorting" choice * Result text now can be graduated * CSS Bugfix = 0.6 = * For every question you can now individually be determined * Cloze answer type added * Import / export function added = 0.7 = * CSS: !important added to all CSS-properties = 0.8 = * Bugfix in the frontend and backend = 0.9 = * Bugfix in the frontend (Single choice) = 0.10 = * Bugfix: "Matrix Sorting" in connection with "Random answer" * Bugfix: Database in connection with UTF-8 * Bugfix in cloze * Bugfix in the backend = 0.11 = * Bugfix in javascript-code * "Sort elements" are always randomly arranged * Bugfix in CSS for different themes = 0.12 = * Compatible for WordPress 3.5 * Translation for Arabic have been added (Thanks Abuhassan) * added hide "restart quiz" button option * added hide "view question" button option * Bugfix in sorting choice with IE & Safari = 0.13 = * Bugfix * New screenshots * A new Touch Library was added for mobile devices * Statistics function has been extended * Setting page in case of problems added * "Copy questions from another Quiz" function added * "Execute quiz only once" option added = 0.14 = * Bugfix in the statistics function * "Questions below each other" option was added * "Number answers" option was added = 0.15 = * Typo corrected * Adjustment of admin template * Internal changes * Capability added * Support for BuddyPress achievements added * Support for "User Role Editor" etc. added * Statistic function expanded * Points now can be entered per correct answer instead of correct question * Translation for Russian have been added (Thanks Sergei B.) * Translation for Swedish have been added (Thanks Martin J.) = 0.16 = * Bug in uninstall script fixed * Option "hide correct- and incorrect-message" added * Option "correct- and incorrect-answermark" added * Option "show only specific number of questions" added * Bugfix in statistic function * Translation for Dutch have been added (Thanks Bas W.) * Translation for Norwegian have been added (Thanks Stein Ivar J.) = 0.17 = * 0.17 is 0.16 (WordPress SVN bug) = 0.18 = * "Allow HTML" bug fixed * "0" can now be used as a answer * Database: "sort" change to SMALLINT * Updated Norwegian translation * Updated Russian translation = 0.19 = * Leaderboard added * Quiz requirements added * Different points for each answer * "Matrix Sort" sort elements can now be created without criteria * Front-End javascript completely rewritten * Admin javascript revised * Average score can now be displayed in quiz * Cloze: different points can be assigned for every gap * Very many internal changes * several bugfixes = 0.20 = * Bugfix: in "Cloze": not correctly points calculated * Bugfix: "Number answers" option broken. all answers are numbered * Bugfix: Database = 0.21 = * Hard fail in version 0.21 (all question points reset) = 0.22 = * CSS Bugfixes * IIS bug fixed * Time limit improves (JS) * Updated norwegian translation * Updated russian translation * Updated dutch translation = 0.23 = * Automatically add to the leaderboard * Leaderboard is updated automatically * Cloze-Choice: several words per gap are possible * Quiz Summary added * Skip question button added * Email notification added * Category support added * Review Question added * CSS-adjustments * Bug fixes * Translation for spanish have been added (Thanks Carlos R.) * Translation for greek have been added (Thanks Ζαχαρίας Σ.) = 0.24 = * Support for Achievements V3 added * Support for Achievements V2 removed * Improvement of statistics function * TinyMCE editor added to E-Mail settings * Assessment choice added * Time logger for each question added * Option "Show category score" added in Quiz-result-site * User e-mail support added (send an email with quiz-result to the user) * "Question overview" in "View questions" will now be displayed * Rename button "next exercise" to "next" * Rename last button "next exercise" to "Finish quiz" or "Quiz-summary" * Bugfix for IIS * Adminmenu: "Media add" button in "answers" (edit/new question) added * Adminmenu: show question-category in question overview * Adminmenu: option "Hide correct questions - display" added * Adminmenu: option "Hide quiz time - display" added * Adminmenu: option "Hide score - display" added * Updated russian translation * Updated dutch translation * Updated greek translation * Translation for danish have been added (Thanks Kenneth D.) * Translation for french have been added (Thanks Aurélien C.) = 0.25 = * Categories overview in the email * Autostart option added * Support for XML import and exports added * Force user to answer a question * New point calculation for single choice (new option "different points - mode 2" added) * Option "hide question position overview" added * Option "hide question numbering" added * Updated greek translation * Updated dutch translation * Translation for czech have been added (Thanks Petr Š.) = 0.26 = * Bugfix: Cloze choice and assessment * Bugfix: Email sending = 0.27 = * Statistics function has been completely overworked. - All answers from users are stored now. - Edit, delete or add questions has no effect on existing results. * Statistics function can also be actived with the option "Show only specific number of questions" now. * The "Show only specific number of questions" option now works with cache plugins. * added custom fields * Quiz mode "Questions below eachother" can now be divided into pages. * Quiz: added option "Sort questions by category" - Sort questions by category. * Quiz: added option "Display category" - Category is displayed in the questions. * Repair Database - Added button in the global settings * Improved matrix-sorting question type by allowing sort elements to be dragged into any criterion having the same text as the correct answer. (For example, if there are 6 unique sort elements and only 2 unique criterion, then dragging a sort element into any criterion with the same correct name will validate as correct.) - Thanks Grant K Norwood (grantnorwood) * Added ability to set the table column width for matrix sorting criteria in order to allow longer criteria text. The option is displayed only when matrix sorting is selected as the answer type. - Thanks Grant K Norwood (grantnorwood) = 0.28 = * Bugfix in custom field at the option "Display position - At the end of the quiz" * Bugfix in Statistc-function * Translation for indonesian have been added (Thanks dieka91 and Creative Computer Club) css/wpProQuiz_front.min.css 0000666 00000017340 15214236625 0012037 0 ustar 00 .wpProQuiz_answerCorrect{background:#6db46d;font-weight:700}.wpProQuiz_answerCorrect label{font-weight:700}.wpProQuiz_answerIncorrect{background:#ff9191;font-weight:700}.wpProQuiz_content{margin-top:10px;margin-bottom:10px}.wpProQuiz_content h2{margin-bottom:10px}.wpProQuiz_question_page{margin-bottom:10px}.wpProQuiz_question_page span{font-weight:700}.wpProQuiz_questionListItem:last-child,.wpProQuiz_questionListItemLastChildIE{padding:3px;margin-bottom:0;overflow:auto}.wpProQuiz_questionListItem{padding:3px;margin-bottom:5px;background-image:none;margin-left:0;list-style:none;border:0}.wpProQuiz_questionListItem>table{border-collapse:collapse;margin:0;padding:0;width:100%}.wpProQuiz_catOverview ol,.wpProQuiz_list,.wpProQuiz_listItem,.wpProQuiz_maxtrixSortCriterion,.wpProQuiz_questionList,.wpProQuiz_resultsList,.wpProQuiz_sortStringList{list-style:none;padding:0;margin:0}.wpProQuiz_list{border:0}.wpProQuiz_questionList{margin-bottom:10px;background:#f8faf5;border:1px solid #c3d1a3;padding:5px;list-style:none;overflow:auto}.wpProQuiz_listItem{position:relative;border:0;background-image:none}.wpProQuiz_response{background:#f8faf5;border:1px solid #c4c4c4;padding:5px;margin-bottom:15px;box-shadow:1px 1px 2px #aaa}.wpProQuiz_response span{font-weight:700}.wpProQuiz_sort{width:25px}.wpProQuiz_results h3{margin-bottom:10px}.wpProQuiz_sort_correct_answer{font-weight:700;margin-right:5px;display:none}.wpProQuiz_sortStringItem,.wpProQuiz_sortable{padding:5px;border:1px solid #d3d3d3;box-shadow:2px 2px 1px #eee;background-color:#f8faf5;cursor:move}.wpProQuiz_time_limit .time{font-weight:700;margin-top:5px;margin-bottom:5px}.wpProQuiz_time_limit .wpProQuiz_progress{height:10px;background-color:#00f;margin-bottom:5px}.wpProQuiz_time_limit_expired{font-weight:700;font-size:15px;text-align:center}.wpProQuiz_question_text{margin-bottom:10px}.wpProQuiz_tipp>div{padding:10px;background-color:#ddecff;border:1px dotted #363636;border-radius:10px;position:absolute;bottom:5px;left:5px;right:5px;box-shadow:2px 2px 5px 0 #313131;z-index:99999}.wpProQuiz_matrixSortString,.wpProQuiz_matrixSortString>h3{margin-bottom:10px;margin-top:0}.wpProQuiz_matrixSortString{background:#f8faf5;border:1px solid #c3d1a3;padding:5px;overflow:auto}.wpProQuiz_sortStringList{padding:10px;border:0}.wpProQuiz_sortStringList>li{float:left;margin-left:5px;margin-right:5px;margin-bottom:5px}.wpProQuiz_sortStringItem{margin:0;background-image:none;list-style:none}.wpProQuiz_maxtrixSortCriterion{padding:5px;overflow:auto}.wpProQuiz_placehold{background-color:#ffffc2;list-style:none;background-image:none;padding:5px;height:30px;min-width:50px;margin:0}.wpProQuiz_maxtrixSortText{padding:5px}.wpProQuiz_mextrixTr>td{border:1px solid #d1d1d1;padding:5px;vertical-align:middle}.wpProQuiz_earned_points,.wpProQuiz_graded_points,.wpProQuiz_points{font-weight:700;text-align:center;margin-bottom:20px}.wpProQuiz_cloze input[type=text]{background:0 0;border:0;border-bottom:1px solid;height:18px;margin:0;padding:0 4px 0 4px;color:#000;border-radius:0;box-shadow:0 0}.wpProQuiz_cloze input:focus{outline:0}.wpProQuiz_questionListItem input,.wpProQuiz_questionListItem label{margin:0;font-weight:400;display:inline}.wpProQuiz_questionListItem input{float:none;display:inline}.wpProQuiz_resultsList{border:0}.wpProQuiz_resultsList>li{background-image:none;padding:0;margin:0;list-style-type:none;border:0}.wpProQuiz_loadQuiz,.wpProQuiz_lock,.wpProQuiz_prerequisite,.wpProQuiz_startOnlyRegisteredUser{border:1px dotted #ffc3c3;background-color:#fff7f7}.wpProQuiz_loadQuiz p,.wpProQuiz_lock p,.wpProQuiz_prerequisite p,.wpProQuiz_startOnlyRegisteredUser p{margin:20px;font-weight:700}.wpProQuiz_toplistTable{width:100%;border:1px solid #c3d1a3;border-collapse:collapse;margin:0}.wpProQuiz_toplistTable caption{caption-side:top;text-align:right;padding-bottom:2px;color:gray;margin:0;font-size:11px}.wpProQuiz_toplistTable thead tr{background:#9bbb59;padding:5px;color:#fff;font-weight:700}.wpProQuiz_toplistTable tbody td:FIRST-CHILD{font-weight:700}.wpProQuiz_toplistTable td,.wpProQuiz_toplistTable th{padding:5px;text-align:center;border:0}.wpProQuiz_toplistTable th{background:#9bbb59}.wpProQuiz_toplistTrOdd{background-color:#ebf1de}.wpProQuiz_addToplist{margin-top:10px;background-color:#f5faea;padding:10px;border:1px solid #c3d1a3}.wpProQuiz_addToplistMessage{border:1px solid #a0a0a0;background-color:#fcffb3;margin-bottom:5px;border-radius:5px;padding:5px;font-weight:700;color:#696969}.wpProQuiz_resultTable{margin:15px auto;width:400px;border:1px solid #c4c4c4;padding:15px;font-weight:700}.wpProQuiz_resultTable table{width:100%;border-collapse:collapse;margin:0;border:0}.wpProQuiz_resultName{width:100px;border-right:1px solid #868686;padding:10px 0;border-bottom:0;border-top:0;border-left:0}.wpProQuiz_resultValue{padding:0;border:0}.wpProQuiz_resultValue div{color:#000;text-align:right;box-shadow:1px 1px 3px 1px #c4c4c4;display:inline-block;height:18px;zoom:1;margin-right:3px;vertical-align:middle}.wpProQuiz_addBox label{display:inline}.wpProQuiz_addBox input[type=text]{margin:0}.wpProQuiz_reviewQuestion{max-height:100px;overflow:hidden;border:1px solid #c3d1a3;background-color:#f8faf5;position:relative}.wpProQuiz_box{border:1px solid #c3d1a3;background-color:#f8faf5}.wpProQuiz_checkPage h3{margin:10px 0 10px 0}.wpProQuiz_checkPage ol,.wpProQuiz_reviewQuestion ol{list-style-type:none;margin:0;padding:5px 12px 0 5px;zoom:1;position:relative;border:0}.wpProQuiz_reviewQuestion ol:after{content:".";display:block;height:0;clear:both;visibility:hidden}.wpProQuiz_checkPage li,.wpProQuiz_reviewQuestion li{float:left;margin:0 5px 5px 0;border:1px solid #cfcfcf;padding:5px 0 5px 0;width:30px;text-align:center;background-color:#fff;cursor:pointer;list-style-type:none;background-image:none}.wpProQuiz_reviewQuestion div{position:absolute;right:0;background-color:#b8b8b8;top:0;height:20px;width:10px;border:0;border-radius:10px;cursor:move}.wpProQuiz_reviewLegend{padding:5px;margin-bottom:8px}.wpProQuiz_reviewLegend ol{list-style-type:none;padding:0;margin:0;border:0}.wpProQuiz_reviewLegend li{float:left;padding-right:5px;list-style-type:none;margin:0;border:0;background-image:none}.wpProQuiz_reviewColor{height:10px;width:10px;display:inline-block;margin-right:2px}.wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionTarget{font-weight:700;border-color:#7db1d3;box-shadow:0 0 2px 1px #c4c4c4}.wpProQuiz_box li.wpProQuiz_reviewQuestionSolved,.wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionSolved{background-color:#6ca54c}.wpProQuiz_box li.wpProQuiz_reviewQuestionReview,.wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionReview{background-color:#ffb800}.wpProQuiz_button2{border:1px solid #dadada;background:#f5f5f5;color:#303030;border-radius:4px;padding:3px 5px;box-shadow:1px 1px 1px #a7a7a7;text-shadow:none;filter:none;margin:0;font-weight:400}.wpProQuiz_button2:hover{background:#ebebeb}.wpProQuiz_reviewDiv{margin:20px 0 20px 0}.wpProQuiz_header{margin:0}.wpProQuiz_catOverview{margin-top:10px;margin-bottom:20px}.wpProQuiz_catOverview li{list-style:none;padding:0;clear:left;border-bottom:1px dashed #aaa;height:1.05em;margin:10px 0 0 0;position:relative}.wpProQuiz_catOverview span{background:#fff;padding:0 3px 0 0;float:left;position:absolute;text-decoration:none}span.wpProQuiz_catPercent{font-weight:700;padding-left:5px;color:#000;right:0}.wpProQuiz_forms{margin:20px 0 20px 0}.wpProQuiz_required{color:red;font-weight:700}.wpProQuiz_invalidate{border:1px solid #ffcfcf;background:#ffebe8;padding:4px;margin:4px 0 4px 0;display:none}.wpProQuiz_forms table{width:auto;border-collapse:separate;border-spacing:2px}.wpProQuiz_forms td{vertical-align:top;padding:0 0 8px 0;margin:0;border:0;background:0 0}.wpProQuiz_forms input,.wpProQuiz_forms label,.wpProQuiz_forms select,.wpProQuiz_forms textarea{margin:0;float:none;display:inline}.wpProQuiz_forms select{width:auto} css/wpProQuiz_front.css 0000666 00000023163 15214236625 0011255 0 ustar 00 .wpProQuiz_answerCorrect { background: #6DB46D ; font-weight: bold ; } .wpProQuiz_answerCorrect label { font-weight: bold ; } .wpProQuiz_answerIncorrect { background: #FF9191 ; font-weight: bold ; } .wpProQuiz_content { margin-top: 10px ; margin-bottom: 10px ; } .wpProQuiz_content h2 { margin-bottom: 10px ; } /*.wpProQuiz_button, .wpProQuiz_button:hover { background: #13455B ; border-radius: 11px ; color: white ; font-weight: bold ; border: 1px solid #13455B ; }*/ .wpProQuiz_question_page { margin-bottom: 10px ; } .wpProQuiz_question_page span { font-weight: bold ; } .wpProQuiz_questionListItem:last-child, .wpProQuiz_questionListItemLastChildIE { padding: 3px ; margin-bottom: 0 ; overflow: auto; } .wpProQuiz_questionListItem { padding: 3px ; margin-bottom: 5px ; background-image: none ; margin-left: 0 ; list-style: none ; border: 0 ; } .wpProQuiz_questionListItem > table{ border-collapse: collapse ; margin: 0 ; padding: 0 ; width: 100%; } .wpProQuiz_list, .wpProQuiz_listItem, .wpProQuiz_questionList, .wpProQuiz_sortStringList, .wpProQuiz_sortStringList, .wpProQuiz_maxtrixSortCriterion, .wpProQuiz_resultsList, .wpProQuiz_catOverview ol { list-style: none ; padding: 0 ; margin: 0 ; } .wpProQuiz_list { border: 0 ; } .wpProQuiz_questionList { margin-bottom: 10px ; background: #F8FAF5 ; border: 1px solid #C3D1A3 ; padding: 5px ; list-style: none ; overflow: auto; } .wpProQuiz_listItem { position: relative ; border: 0 ; background-image: none ; } .wpProQuiz_response { background: #F8FAF5 ; border: 1px solid #C4C4C4 ; padding: 5px ; margin-bottom: 15px ; box-shadow: 1px 1px 2px #AAA ; } .wpProQuiz_response span { font-weight: bold ; } .wpProQuiz_sort { width: 25px ; } .wpProQuiz_results h3 { margin-bottom: 10px ; } .wpProQuiz_sort_correct_answer { font-weight: bold ; margin-right: 5px ; display: none ; } .wpProQuiz_sortable, .wpProQuiz_sortStringItem { padding: 5px ; border: 1px solid lightGrey ; box-shadow: 2px 2px 1px #EEE; background-color: #F8FAF5 ; cursor: move; } .wpProQuiz_time_limit .time { font-weight: bold ; margin-top: 5px ; margin-bottom: 5px ; } .wpProQuiz_time_limit .wpProQuiz_progress { height: 10px ; background-color: blue ; margin-bottom: 5px ; } .wpProQuiz_time_limit_expired { font-weight: bold ; font-size: 15px ; text-align: center ; } .wpProQuiz_question_text { margin-bottom: 10px ; } .wpProQuiz_tipp > div { padding: 10px ; background-color: #DDECFF ; border: 1px dotted #363636 ; border-radius: 10px ; position: absolute ; bottom: 5px ; left: 5px ; right: 5px ; box-shadow: 2px 2px 5px 0px #313131 ; z-index: 99999 ; } .wpProQuiz_matrixSortString, .wpProQuiz_matrixSortString > h3{ margin-bottom: 10px ; margin-top: 0 ; } .wpProQuiz_matrixSortString { background: #F8FAF5 ; border: 1px solid #C3D1A3 ; padding: 5px ; overflow: auto; } .wpProQuiz_sortStringList { padding: 10px ; border: 0 ; } .wpProQuiz_sortStringList > li { float: left ; margin-left: 5px ; margin-right: 5px ; margin-bottom: 5px ; } .wpProQuiz_sortStringItem { margin: 0 ; background-image: none ; list-style: none ; } .wpProQuiz_maxtrixSortCriterion { padding: 5px ; overflow: auto; } .wpProQuiz_placehold { background-color: #FFFFC2 ; list-style: none ; background-image: none ; padding: 5px ; height: 30px ; min-width: 50px ; margin: 0 ; } .wpProQuiz_maxtrixSortText { padding: 5px ; } .wpProQuiz_mextrixTr > td { border: 1px solid #D1D1D1 ; padding: 5px ; vertical-align: middle ; } .wpProQuiz_points, .wpProQuiz_earned_points, .wpProQuiz_graded_points { font-weight: bold ; text-align: center ; margin-bottom: 20px ; } .wpProQuiz_cloze input[type="text"] { background: transparent; border: 0 ; border-bottom: 1px solid ; height: 18px ; margin: 0 ; padding: 0 4px 0 4px ; color: black ; border-radius: 0 ; box-shadow: 0 0 ; } .wpProQuiz_cloze input:focus { outline: none ; } .wpProQuiz_questionListItem input, .wpProQuiz_questionListItem label { margin: 0 ; font-weight: normal; display: inline; } .wpProQuiz_questionListItem input { float: none ; display: inline ; } .wpProQuiz_resultsList { border: 0 ; } .wpProQuiz_resultsList > li { background-image: none ; padding: 0 ; margin: 0 ; list-style-type: none ; border: 0 ; } .wpProQuiz_lock, .wpProQuiz_prerequisite, .wpProQuiz_startOnlyRegisteredUser, .wpProQuiz_loadQuiz { border: 1px dotted #FFC3C3 ; background-color: #FFF7F7 ; } .wpProQuiz_lock p, .wpProQuiz_prerequisite p, .wpProQuiz_startOnlyRegisteredUser p, .wpProQuiz_loadQuiz p { margin: 20px ; font-weight: bold ; } .wpProQuiz_toplistTable { width: 100% ; border: 1px solid #C3D1A3 ; border-collapse: collapse ; margin: 0 ; } .wpProQuiz_toplistTable caption { caption-side:top ; text-align: right ; padding-bottom: 2px ; color: gray ; margin: 0 ; font-size: 11px ; } .wpProQuiz_toplistTable thead tr { background: rgb(155,187,89) ; padding: 5px ; color: white ; font-weight: bold ; } .wpProQuiz_toplistTable tbody td:FIRST-CHILD{ font-weight: bold ; } .wpProQuiz_toplistTable td, .wpProQuiz_toplistTable th { padding: 5px ; text-align: center ; border: 0 ; } .wpProQuiz_toplistTable th { background: #9BBB59 ; } .wpProQuiz_toplistTrOdd { background-color: #EBF1DE ; } .wpProQuiz_addToplist { margin-top: 10px ; background-color: #F5FAEA ; padding: 10px ; border: 1px solid #C3D1A3 ; } .wpProQuiz_addToplistMessage { border: 1px solid rgb(160, 160, 160) ; background-color: #FCFFB3 ; margin-bottom: 5px ; border-radius: 5px ; padding: 5px ; font-weight: bold ; color: dimGray ; } .wpProQuiz_resultTable { margin: 15px auto ; width: 400px ; border: 1px solid #C4C4C4 ; padding: 15px ; font-weight: bold ; } .wpProQuiz_resultTable table { width: 100% ; border-collapse: collapse ; margin: 0 ; border: 0 ; } .wpProQuiz_resultName { width: 100px ; border-right: 1px solid rgb(134, 134, 134) ; padding: 10px 0px ; border-bottom: 0 ; border-top: 0 ; border-left: 0 ; } .wpProQuiz_resultValue { padding: 0 ; border: 0 ; } .wpProQuiz_resultValue div { color: black ; text-align: right ; box-shadow: 1px 1px 3px 1px #C4C4C4 ; display: inline-block ; height: 18px ; zoom: 1 ; *display: inline ; margin-right: 3px ; vertical-align: middle ; } .wpProQuiz_addBox label { display: inline ; } .wpProQuiz_addBox input[type="text"] { margin: 0 ; } .wpProQuiz_reviewQuestion { max-height: 100px; overflow: hidden; border: 1px solid #C3D1A3; background-color: #F8FAF5; position: relative; } .wpProQuiz_box { border: 1px solid #C3D1A3; background-color: #F8FAF5; } .wpProQuiz_checkPage h3 { margin: 10px 0 10px 0; } .wpProQuiz_reviewQuestion ol, .wpProQuiz_checkPage ol { list-style-type: none ; margin: 0 ; padding: 5px 12px 0 5px ; zoom: 1 ; position: relative ; border: 0 ; } .wpProQuiz_reviewQuestion ol:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .wpProQuiz_reviewQuestion li, .wpProQuiz_checkPage li { float: left ; margin: 0 5px 5px 0 ; border: 1px solid #CFCFCF; padding: 5px 0 5px 0 ; width: 30px ; text-align: center ; background-color: white; cursor: pointer ; list-style-type: none ; background-image: none ; } .wpProQuiz_reviewQuestion div { position: absolute; right: 0; background-color: #B8B8B8; top: 0; height: 20px; width: 10px; border: 0; border-radius: 10px; cursor: move; } .wpProQuiz_reviewLegend { padding: 5px ; margin-bottom: 8px ; } .wpProQuiz_reviewLegend ol { list-style-type: none ; padding: 0 ; margin: 0 ; border: 0 ; } .wpProQuiz_reviewLegend li { float: left ; padding-right: 5px ; list-style-type: none ; margin: 0 ; border: 0 ; background-image: none ; } .wpProQuiz_reviewColor { height: 10px ; width: 10px ; display: inline-block ; margin-right: 2px ; } .wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionTarget { font-weight: bold; border-color: #7DB1D3 ; box-shadow: 0px 0px 2px 1px #C4C4C4; } .wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionSolved, .wpProQuiz_box li.wpProQuiz_reviewQuestionSolved { background-color: #6CA54C; } .wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionReview, .wpProQuiz_box li.wpProQuiz_reviewQuestionReview { background-color: #FFB800; } .wpProQuiz_button2 { border: 1px solid #DADADA ; background: whiteSmoke ; color: #303030 ; border-radius: 4px ; padding: 3px 5px ; box-shadow: 1px 1px 1px #A7A7A7 ; text-shadow: none ; filter: none ; margin: 0 ; font-weight: normal ; } .wpProQuiz_button2:hover { background: #EBEBEB ; } .wpProQuiz_reviewDiv { margin: 20px 0 20px 0 ; } .wpProQuiz_header { margin: 0px ; } .wpProQuiz_catOverview { margin-top: 10px; margin-bottom: 20px; } .wpProQuiz_catOverview li { list-style: none ; padding: 0 ; clear: left ; border-bottom: 1px dashed #aaa; height: 1.05em ; margin: 10px 0 0 0 ; position: relative ; } .wpProQuiz_catOverview span { background:#fff ; padding:0 3px 0 0 ; float:left ; position:absolute ; text-decoration:none ; } span.wpProQuiz_catPercent { font-weight: bold ; padding-left: 5px ; color: #000 ; right: 0 ; } .wpProQuiz_forms { margin: 20px 0 20px 0 ; } .wpProQuiz_required { color: #F00 ; font-weight: bold ; } .wpProQuiz_invalidate { border: 1px solid #FFCFCF ; background: #FFEBE8 ; padding: 4px ; margin: 4px 0 4px 0 ; display: none; } .wpProQuiz_forms table { width: auto ; border-collapse: separate ; border-spacing: 2px ; } .wpProQuiz_forms td { vertical-align: top ; padding: 0 0 8px 0 ; margin: 0 ; border: 0 ; background: none ; } .wpProQuiz_forms input, .wpProQuiz_forms textarea, .wpProQuiz_forms label, .wpProQuiz_forms select { margin: 0 ; float: none ; display: inline ; } .wpProQuiz_forms select { width: auto ; } css/wpProQuiz_front.min-rtl.css 0000666 00000017352 15214236625 0012641 0 ustar 00 .wpProQuiz_answerCorrect{background:#6db46d;font-weight:700}.wpProQuiz_answerCorrect label{font-weight:700}.wpProQuiz_answerIncorrect{background:#ff9191;font-weight:700}.wpProQuiz_content{margin-top:10px;margin-bottom:10px}.wpProQuiz_content h2{margin-bottom:10px}.wpProQuiz_question_page{margin-bottom:10px}.wpProQuiz_question_page span{font-weight:700}.wpProQuiz_questionListItem:last-child,.wpProQuiz_questionListItemLastChildIE{padding:3px;margin-bottom:0;overflow:auto}.wpProQuiz_questionListItem{padding:3px;margin-bottom:5px;background-image:none;margin-right:0;list-style:none;border:0}.wpProQuiz_questionListItem>table{border-collapse:collapse;margin:0;padding:0;width:100%}.wpProQuiz_catOverview ol,.wpProQuiz_list,.wpProQuiz_listItem,.wpProQuiz_maxtrixSortCriterion,.wpProQuiz_questionList,.wpProQuiz_resultsList,.wpProQuiz_sortStringList{list-style:none;padding:0;margin:0}.wpProQuiz_list{border:0}.wpProQuiz_questionList{margin-bottom:10px;background:#f8faf5;border:1px solid #c3d1a3;padding:5px;list-style:none;overflow:auto}.wpProQuiz_listItem{position:relative;border:0;background-image:none}.wpProQuiz_response{background:#f8faf5;border:1px solid #c4c4c4;padding:5px;margin-bottom:15px;box-shadow:-1px 1px 2px #aaa}.wpProQuiz_response span{font-weight:700}.wpProQuiz_sort{width:25px}.wpProQuiz_results h3{margin-bottom:10px}.wpProQuiz_sort_correct_answer{font-weight:700;margin-left:5px;display:none}.wpProQuiz_sortStringItem,.wpProQuiz_sortable{padding:5px;border:1px solid #d3d3d3;box-shadow:-2px 2px 1px #eee;background-color:#f8faf5;cursor:move}.wpProQuiz_time_limit .time{font-weight:700;margin-top:5px;margin-bottom:5px}.wpProQuiz_time_limit .wpProQuiz_progress{height:10px;background-color:#00f;margin-bottom:5px}.wpProQuiz_time_limit_expired{font-weight:700;font-size:15px;text-align:center}.wpProQuiz_question_text{margin-bottom:10px}.wpProQuiz_tipp>div{padding:10px;background-color:#ddecff;border:1px dotted #363636;border-radius:10px;position:absolute;bottom:5px;right:5px;left:5px;box-shadow:-2px 2px 5px 0 #313131;z-index:99999}.wpProQuiz_matrixSortString,.wpProQuiz_matrixSortString>h3{margin-bottom:10px;margin-top:0}.wpProQuiz_matrixSortString{background:#f8faf5;border:1px solid #c3d1a3;padding:5px;overflow:auto}.wpProQuiz_sortStringList{padding:10px;border:0}.wpProQuiz_sortStringList>li{float:right;margin-right:5px;margin-left:5px;margin-bottom:5px}.wpProQuiz_sortStringItem{margin:0;background-image:none;list-style:none}.wpProQuiz_maxtrixSortCriterion{padding:5px;overflow:auto}.wpProQuiz_placehold{background-color:#ffffc2;list-style:none;background-image:none;padding:5px;height:30px;min-width:50px;margin:0}.wpProQuiz_maxtrixSortText{padding:5px}.wpProQuiz_mextrixTr>td{border:1px solid #d1d1d1;padding:5px;vertical-align:middle}.wpProQuiz_earned_points,.wpProQuiz_graded_points,.wpProQuiz_points{font-weight:700;text-align:center;margin-bottom:20px}.wpProQuiz_cloze input[type=text]{background:100% 0;border:0;border-bottom:1px solid;height:18px;margin:0;padding:0 4px 0 4px;color:#000;border-radius:0;box-shadow:0 0}.wpProQuiz_cloze input:focus{outline:0}.wpProQuiz_questionListItem input,.wpProQuiz_questionListItem label{margin:0;font-weight:400;display:inline}.wpProQuiz_questionListItem input{float:none;display:inline}.wpProQuiz_resultsList{border:0}.wpProQuiz_resultsList>li{background-image:none;padding:0;margin:0;list-style-type:none;border:0}.wpProQuiz_loadQuiz,.wpProQuiz_lock,.wpProQuiz_prerequisite,.wpProQuiz_startOnlyRegisteredUser{border:1px dotted #ffc3c3;background-color:#fff7f7}.wpProQuiz_loadQuiz p,.wpProQuiz_lock p,.wpProQuiz_prerequisite p,.wpProQuiz_startOnlyRegisteredUser p{margin:20px;font-weight:700}.wpProQuiz_toplistTable{width:100%;border:1px solid #c3d1a3;border-collapse:collapse;margin:0}.wpProQuiz_toplistTable caption{caption-side:top;text-align:left;padding-bottom:2px;color:gray;margin:0;font-size:11px}.wpProQuiz_toplistTable thead tr{background:#9bbb59;padding:5px;color:#fff;font-weight:700}.wpProQuiz_toplistTable tbody td:FIRST-CHILD{font-weight:700}.wpProQuiz_toplistTable td,.wpProQuiz_toplistTable th{padding:5px;text-align:center;border:0}.wpProQuiz_toplistTable th{background:#9bbb59}.wpProQuiz_toplistTrOdd{background-color:#ebf1de}.wpProQuiz_addToplist{margin-top:10px;background-color:#f5faea;padding:10px;border:1px solid #c3d1a3}.wpProQuiz_addToplistMessage{border:1px solid #a0a0a0;background-color:#fcffb3;margin-bottom:5px;border-radius:5px;padding:5px;font-weight:700;color:#696969}.wpProQuiz_resultTable{margin:15px auto;width:400px;border:1px solid #c4c4c4;padding:15px;font-weight:700}.wpProQuiz_resultTable table{width:100%;border-collapse:collapse;margin:0;border:0}.wpProQuiz_resultName{width:100px;border-left:1px solid #868686;padding:10px 0;border-bottom:0;border-top:0;border-right:0}.wpProQuiz_resultValue{padding:0;border:0}.wpProQuiz_resultValue div{color:#000;text-align:left;box-shadow:-1px 1px 3px 1px #c4c4c4;display:inline-block;height:18px;zoom:1;margin-left:3px;vertical-align:middle}.wpProQuiz_addBox label{display:inline}.wpProQuiz_addBox input[type=text]{margin:0}.wpProQuiz_reviewQuestion{max-height:100px;overflow:hidden;border:1px solid #c3d1a3;background-color:#f8faf5;position:relative}.wpProQuiz_box{border:1px solid #c3d1a3;background-color:#f8faf5}.wpProQuiz_checkPage h3{margin:10px 0 10px 0}.wpProQuiz_checkPage ol,.wpProQuiz_reviewQuestion ol{list-style-type:none;margin:0;padding:5px 5px 0 12px;zoom:1;position:relative;border:0}.wpProQuiz_reviewQuestion ol:after{content:".";display:block;height:0;clear:both;visibility:hidden}.wpProQuiz_checkPage li,.wpProQuiz_reviewQuestion li{float:right;margin:0 0 5px 5px;border:1px solid #cfcfcf;padding:5px 0 5px 0;width:30px;text-align:center;background-color:#fff;cursor:pointer;list-style-type:none;background-image:none}.wpProQuiz_reviewQuestion div{position:absolute;left:0;background-color:#b8b8b8;top:0;height:20px;width:10px;border:0;border-radius:10px;cursor:move}.wpProQuiz_reviewLegend{padding:5px;margin-bottom:8px}.wpProQuiz_reviewLegend ol{list-style-type:none;padding:0;margin:0;border:0}.wpProQuiz_reviewLegend li{float:right;padding-left:5px;list-style-type:none;margin:0;border:0;background-image:none}.wpProQuiz_reviewColor{height:10px;width:10px;display:inline-block;margin-left:2px}.wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionTarget{font-weight:700;border-color:#7db1d3;box-shadow:0 0 2px 1px #c4c4c4}.wpProQuiz_box li.wpProQuiz_reviewQuestionSolved,.wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionSolved{background-color:#6ca54c}.wpProQuiz_box li.wpProQuiz_reviewQuestionReview,.wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionReview{background-color:#ffb800}.wpProQuiz_button2{border:1px solid #dadada;background:#f5f5f5;color:#303030;border-radius:4px;padding:3px 5px;box-shadow:-1px 1px 1px #a7a7a7;text-shadow:none;filter:none;margin:0;font-weight:400}.wpProQuiz_button2:hover{background:#ebebeb}.wpProQuiz_reviewDiv{margin:20px 0 20px 0}.wpProQuiz_header{margin:0}.wpProQuiz_catOverview{margin-top:10px;margin-bottom:20px}.wpProQuiz_catOverview li{list-style:none;padding:0;clear:right;border-bottom:1px dashed #aaa;height:1.05em;margin:10px 0 0 0;position:relative}.wpProQuiz_catOverview span{background:#fff;padding:0 0 0 3px;float:right;position:absolute;text-decoration:none}span.wpProQuiz_catPercent{font-weight:700;padding-right:5px;color:#000;left:0}.wpProQuiz_forms{margin:20px 0 20px 0}.wpProQuiz_required{color:red;font-weight:700}.wpProQuiz_invalidate{border:1px solid #ffcfcf;background:#ffebe8;padding:4px;margin:4px 0 4px 0;display:none}.wpProQuiz_forms table{width:auto;border-collapse:separate;border-spacing:2px}.wpProQuiz_forms td{vertical-align:top;padding:0 0 8px 0;margin:0;border:0;background:100% 0}.wpProQuiz_forms input,.wpProQuiz_forms label,.wpProQuiz_forms select,.wpProQuiz_forms textarea{margin:0;float:none;display:inline}.wpProQuiz_forms select{width:auto} css/wpProQuiz_front-rtl.css 0000666 00000023167 15214236625 0012060 0 ustar 00 .wpProQuiz_answerCorrect { background: #6DB46D ; font-weight: bold ; } .wpProQuiz_answerCorrect label { font-weight: bold ; } .wpProQuiz_answerIncorrect { background: #FF9191 ; font-weight: bold ; } .wpProQuiz_content { margin-top: 10px ; margin-bottom: 10px ; } .wpProQuiz_content h2 { margin-bottom: 10px ; } /*.wpProQuiz_button, .wpProQuiz_button:hover { background: #13455B ; border-radius: 11px ; color: white ; font-weight: bold ; border: 1px solid #13455B ; }*/ .wpProQuiz_question_page { margin-bottom: 10px ; } .wpProQuiz_question_page span { font-weight: bold ; } .wpProQuiz_questionListItem:last-child, .wpProQuiz_questionListItemLastChildIE { padding: 3px ; margin-bottom: 0 ; overflow: auto; } .wpProQuiz_questionListItem { padding: 3px ; margin-bottom: 5px ; background-image: none ; margin-right: 0 ; list-style: none ; border: 0 ; } .wpProQuiz_questionListItem > table{ border-collapse: collapse ; margin: 0 ; padding: 0 ; width: 100%; } .wpProQuiz_list, .wpProQuiz_listItem, .wpProQuiz_questionList, .wpProQuiz_sortStringList, .wpProQuiz_sortStringList, .wpProQuiz_maxtrixSortCriterion, .wpProQuiz_resultsList, .wpProQuiz_catOverview ol { list-style: none ; padding: 0 ; margin: 0 ; } .wpProQuiz_list { border: 0 ; } .wpProQuiz_questionList { margin-bottom: 10px ; background: #F8FAF5 ; border: 1px solid #C3D1A3 ; padding: 5px ; list-style: none ; overflow: auto; } .wpProQuiz_listItem { position: relative ; border: 0 ; background-image: none ; } .wpProQuiz_response { background: #F8FAF5 ; border: 1px solid #C4C4C4 ; padding: 5px ; margin-bottom: 15px ; box-shadow: -1px 1px 2px #AAA ; } .wpProQuiz_response span { font-weight: bold ; } .wpProQuiz_sort { width: 25px ; } .wpProQuiz_results h3 { margin-bottom: 10px ; } .wpProQuiz_sort_correct_answer { font-weight: bold ; margin-left: 5px ; display: none ; } .wpProQuiz_sortable, .wpProQuiz_sortStringItem { padding: 5px ; border: 1px solid lightGrey ; box-shadow: -2px 2px 1px #EEE; background-color: #F8FAF5 ; cursor: move; } .wpProQuiz_time_limit .time { font-weight: bold ; margin-top: 5px ; margin-bottom: 5px ; } .wpProQuiz_time_limit .wpProQuiz_progress { height: 10px ; background-color: blue ; margin-bottom: 5px ; } .wpProQuiz_time_limit_expired { font-weight: bold ; font-size: 15px ; text-align: center ; } .wpProQuiz_question_text { margin-bottom: 10px ; } .wpProQuiz_tipp > div { padding: 10px ; background-color: #DDECFF ; border: 1px dotted #363636 ; border-radius: 10px ; position: absolute ; bottom: 5px ; right: 5px ; left: 5px ; box-shadow: -2px 2px 5px 0px #313131 ; z-index: 99999 ; } .wpProQuiz_matrixSortString, .wpProQuiz_matrixSortString > h3{ margin-bottom: 10px ; margin-top: 0 ; } .wpProQuiz_matrixSortString { background: #F8FAF5 ; border: 1px solid #C3D1A3 ; padding: 5px ; overflow: auto; } .wpProQuiz_sortStringList { padding: 10px ; border: 0 ; } .wpProQuiz_sortStringList > li { float: right ; margin-right: 5px ; margin-left: 5px ; margin-bottom: 5px ; } .wpProQuiz_sortStringItem { margin: 0 ; background-image: none ; list-style: none ; } .wpProQuiz_maxtrixSortCriterion { padding: 5px ; overflow: auto; } .wpProQuiz_placehold { background-color: #FFFFC2 ; list-style: none ; background-image: none ; padding: 5px ; height: 30px ; min-width: 50px ; margin: 0 ; } .wpProQuiz_maxtrixSortText { padding: 5px ; } .wpProQuiz_mextrixTr > td { border: 1px solid #D1D1D1 ; padding: 5px ; vertical-align: middle ; } .wpProQuiz_points, .wpProQuiz_earned_points, .wpProQuiz_graded_points { font-weight: bold ; text-align: center ; margin-bottom: 20px ; } .wpProQuiz_cloze input[type="text"] { background: transparent; border: 0 ; border-bottom: 1px solid ; height: 18px ; margin: 0 ; padding: 0 4px 0 4px ; color: black ; border-radius: 0 ; box-shadow: 0 0 ; } .wpProQuiz_cloze input:focus { outline: none ; } .wpProQuiz_questionListItem input, .wpProQuiz_questionListItem label { margin: 0 ; font-weight: normal; display: inline; } .wpProQuiz_questionListItem input { float: none ; display: inline ; } .wpProQuiz_resultsList { border: 0 ; } .wpProQuiz_resultsList > li { background-image: none ; padding: 0 ; margin: 0 ; list-style-type: none ; border: 0 ; } .wpProQuiz_lock, .wpProQuiz_prerequisite, .wpProQuiz_startOnlyRegisteredUser, .wpProQuiz_loadQuiz { border: 1px dotted #FFC3C3 ; background-color: #FFF7F7 ; } .wpProQuiz_lock p, .wpProQuiz_prerequisite p, .wpProQuiz_startOnlyRegisteredUser p, .wpProQuiz_loadQuiz p { margin: 20px ; font-weight: bold ; } .wpProQuiz_toplistTable { width: 100% ; border: 1px solid #C3D1A3 ; border-collapse: collapse ; margin: 0 ; } .wpProQuiz_toplistTable caption { caption-side:top ; text-align: left ; padding-bottom: 2px ; color: gray ; margin: 0 ; font-size: 11px ; } .wpProQuiz_toplistTable thead tr { background: rgb(155,187,89) ; padding: 5px ; color: white ; font-weight: bold ; } .wpProQuiz_toplistTable tbody td:FIRST-CHILD{ font-weight: bold ; } .wpProQuiz_toplistTable td, .wpProQuiz_toplistTable th { padding: 5px ; text-align: center ; border: 0 ; } .wpProQuiz_toplistTable th { background: #9BBB59 ; } .wpProQuiz_toplistTrOdd { background-color: #EBF1DE ; } .wpProQuiz_addToplist { margin-top: 10px ; background-color: #F5FAEA ; padding: 10px ; border: 1px solid #C3D1A3 ; } .wpProQuiz_addToplistMessage { border: 1px solid rgb(160, 160, 160) ; background-color: #FCFFB3 ; margin-bottom: 5px ; border-radius: 5px ; padding: 5px ; font-weight: bold ; color: dimGray ; } .wpProQuiz_resultTable { margin: 15px auto ; width: 400px ; border: 1px solid #C4C4C4 ; padding: 15px ; font-weight: bold ; } .wpProQuiz_resultTable table { width: 100% ; border-collapse: collapse ; margin: 0 ; border: 0 ; } .wpProQuiz_resultName { width: 100px ; border-left: 1px solid rgb(134, 134, 134) ; padding: 10px 0px ; border-bottom: 0 ; border-top: 0 ; border-right: 0 ; } .wpProQuiz_resultValue { padding: 0 ; border: 0 ; } .wpProQuiz_resultValue div { color: black ; text-align: left ; box-shadow: -1px 1px 3px 1px #C4C4C4 ; display: inline-block ; height: 18px ; zoom: 1 ; *display: inline ; margin-left: 3px ; vertical-align: middle ; } .wpProQuiz_addBox label { display: inline ; } .wpProQuiz_addBox input[type="text"] { margin: 0 ; } .wpProQuiz_reviewQuestion { max-height: 100px; overflow: hidden; border: 1px solid #C3D1A3; background-color: #F8FAF5; position: relative; } .wpProQuiz_box { border: 1px solid #C3D1A3; background-color: #F8FAF5; } .wpProQuiz_checkPage h3 { margin: 10px 0 10px 0; } .wpProQuiz_reviewQuestion ol, .wpProQuiz_checkPage ol { list-style-type: none ; margin: 0 ; padding: 5px 5px 0 12px ; zoom: 1 ; position: relative ; border: 0 ; } .wpProQuiz_reviewQuestion ol:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .wpProQuiz_reviewQuestion li, .wpProQuiz_checkPage li { float: right ; margin: 0 0 5px 5px ; border: 1px solid #CFCFCF; padding: 5px 0 5px 0 ; width: 30px ; text-align: center ; background-color: white; cursor: pointer ; list-style-type: none ; background-image: none ; } .wpProQuiz_reviewQuestion div { position: absolute; left: 0; background-color: #B8B8B8; top: 0; height: 20px; width: 10px; border: 0; border-radius: 10px; cursor: move; } .wpProQuiz_reviewLegend { padding: 5px ; margin-bottom: 8px ; } .wpProQuiz_reviewLegend ol { list-style-type: none ; padding: 0 ; margin: 0 ; border: 0 ; } .wpProQuiz_reviewLegend li { float: right ; padding-left: 5px ; list-style-type: none ; margin: 0 ; border: 0 ; background-image: none ; } .wpProQuiz_reviewColor { height: 10px ; width: 10px ; display: inline-block ; margin-left: 2px ; } .wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionTarget { font-weight: bold; border-color: #7DB1D3 ; box-shadow: 0px 0px 2px 1px #C4C4C4; } .wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionSolved, .wpProQuiz_box li.wpProQuiz_reviewQuestionSolved { background-color: #6CA54C; } .wpProQuiz_reviewQuestion li.wpProQuiz_reviewQuestionReview, .wpProQuiz_box li.wpProQuiz_reviewQuestionReview { background-color: #FFB800; } .wpProQuiz_button2 { border: 1px solid #DADADA ; background: whiteSmoke ; color: #303030 ; border-radius: 4px ; padding: 3px 5px ; box-shadow: -1px 1px 1px #A7A7A7 ; text-shadow: none ; filter: none ; margin: 0 ; font-weight: normal ; } .wpProQuiz_button2:hover { background: #EBEBEB ; } .wpProQuiz_reviewDiv { margin: 20px 0 20px 0 ; } .wpProQuiz_header { margin: 0px ; } .wpProQuiz_catOverview { margin-top: 10px; margin-bottom: 20px; } .wpProQuiz_catOverview li { list-style: none ; padding: 0 ; clear: right ; border-bottom: 1px dashed #aaa; height: 1.05em ; margin: 10px 0 0 0 ; position: relative ; } .wpProQuiz_catOverview span { background:#fff ; padding:0 0 0 3px ; float:right ; position:absolute ; text-decoration:none ; } span.wpProQuiz_catPercent { font-weight: bold ; padding-right: 5px ; color: #000 ; left: 0 ; } .wpProQuiz_forms { margin: 20px 0 20px 0 ; } .wpProQuiz_required { color: #F00 ; font-weight: bold ; } .wpProQuiz_invalidate { border: 1px solid #FFCFCF ; background: #FFEBE8 ; padding: 4px ; margin: 4px 0 4px 0 ; display: none; } .wpProQuiz_forms table { width: auto ; border-collapse: separate ; border-spacing: 2px ; } .wpProQuiz_forms td { vertical-align: top ; padding: 0 0 8px 0 ; margin: 0 ; border: 0 ; background: none ; } .wpProQuiz_forms input, .wpProQuiz_forms textarea, .wpProQuiz_forms label, .wpProQuiz_forms select { margin: 0 ; float: none ; display: inline ; } .wpProQuiz_forms select { width: auto ; } wp-pro-quiz.php 0000666 00000012006 15214236625 0007500 0 ustar 00 <?php /* Plugin Name: WP-Pro-Quiz Plugin URI: http://wordpress.org/extend/plugins/wp-pro-quiz Description: A powerful and beautiful quiz plugin for WordPress. Version: 0.28 Author: Julius Fischer Author URI: http://www.it-gecko.de Text Domain: wp-pro-quiz Domain Path: /languages */ define('WPPROQUIZ_VERSION', '0.28'); define('WPPROQUIZ_PATH', dirname(__FILE__)); define('WPPROQUIZ_URL', plugins_url('', __FILE__)); define('WPPROQUIZ_FILE', __FILE__); //define('WPPROQUIZ_PPATH', dirname(plugin_basename(__FILE__))); //define('WPPROQUIZ_PLUGIN_PATH', WPPROQUIZ_PATH.'/plugin'); //define('WPPROQUIZ_TEXT_DOMAIN', 'learndash' ); $uploadDir = wp_upload_dir(); define('WPPROQUIZ_CAPTCHA_DIR', $uploadDir['basedir'].'/wp_pro_quiz_captcha'); define('WPPROQUIZ_CAPTCHA_URL', $uploadDir['baseurl'].'/wp_pro_quiz_captcha'); spl_autoload_register('wpProQuiz_autoload'); //$WpProQuiz_Answer_types_labels = array(); //global $WpProQuiz_Answer_types_labels; // This is never called. //register_activation_hook(__FILE__, array('WpProQuiz_Helper_Upgrade', 'upgrade')); add_action('plugins_loaded', 'wpProQuiz_pluginLoaded'); if(is_admin()) { new WpProQuiz_Controller_Admin(); } else { new WpProQuiz_Controller_Front(); } function wpProQuiz_autoload($class) { $c = explode('_', $class); if($c === false || count($c) != 3 || $c[0] !== 'WpProQuiz') return; $dir = ''; switch ($c[1]) { case 'View': $dir = 'view'; break; case 'Model': $dir = 'model'; break; case 'Helper': $dir = 'helper'; break; case 'Controller': $dir = 'controller'; break; case 'Plugin': $dir = 'plugin'; break; default: return; } if(file_exists(WPPROQUIZ_PATH.'/lib/'.$dir.'/'.$class.'.php')) include_once WPPROQUIZ_PATH.'/lib/'.$dir.'/'.$class.'.php'; } function wpProQuiz_pluginLoaded() { if ( get_option( 'wpProQuiz_version' ) !== WPPROQUIZ_VERSION ) { WpProQuiz_Helper_Upgrade::upgrade(); } } function wpProQuiz_achievementsV3() { achievements()->extensions->wp_pro_quiz = new WpProQuiz_Plugin_BpAchievementsV3(); do_action('wpProQuiz_achievementsV3'); } add_action('dpa_ready', 'wpProQuiz_achievementsV3'); /** * Format the Quiz Cloze type answers into an array to be used when comparing responses. * @ since 2.5 * copied from WpProQuiz_View_FrontQuiz */ function fetchQuestionCloze( $answer_text, $convert_to_lower = true ) { $answer_text = apply_filters( 'learndash_quiz_question_answer_preprocess', $answer_text, 'cloze' ); preg_match_all( '#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', $answer_text, $matches, PREG_SET_ORDER ); $data = array(); foreach ( $matches as $k => $v ) { $text = $v[1]; $points = ! empty( $v[2] ) ? (int) $v[2] : 1; $rowText = $multiTextData = array(); $len = array(); if ( preg_match_all( '#\[(.*?)\]#im', $text, $multiTextMatches ) ) { foreach ( $multiTextMatches[1] as $multiText ) { $multiText_clean = trim( html_entity_decode( $multiText, ENT_QUOTES ) ); if ( apply_filters('learndash_quiz_question_cloze_answers_to_lowercase', $convert_to_lower ) ) { if ( function_exists( 'mb_strtolower' ) ) $x = mb_strtolower( $multiText_clean ); else $x = strtolower( $multiText_clean ); } else { $x = $multiText_clean; } $len[] = strlen( $x ); $multiTextData[] = $x; $rowText[] = $multiText; } } else { $text_clean = trim( html_entity_decode( $text, ENT_QUOTES ) ); if ( apply_filters('learndash_quiz_question_cloze_answers_to_lowercase', $convert_to_lower ) ) { if ( function_exists( 'mb_strtolower' ) ) $x = mb_strtolower( trim( html_entity_decode( $text_clean, ENT_QUOTES ) ) ); else $x = strtolower( trim( html_entity_decode( $text_clean, ENT_QUOTES ) ) ); } else { $x = $text_clean; } $len[] = strlen( $x ); $multiTextData[] = $x; $rowText[] = $text; } $a = '<span class="wpProQuiz_cloze"><input data-wordlen="' . max( $len ) . '" type="text" value=""> '; $a .= '<span class="wpProQuiz_clozeCorrect" style="display: none;"></span></span>'; $data['correct'][] = $multiTextData; $data['points'][] = $points; $data['data'][] = $a; } $data['replace'] = preg_replace( '#\{(.*?)(?:\|(\d+))?(?:[\s]+)?\}#im', '@@wpProQuizCloze@@', $answer_text ); $data['replace'] = apply_filters( 'learndash_quiz_question_answer_postprocess', $data['replace'], 'cloze' ); return $data; } /** * This function will take an instance of a PHP stdClass and attempt to cast it to * the type of the specified $className. * * For example, we may pass 'Acme\Model\Product' as the $className. * * @param object $instance an instance of the stdClass to convert * @param string $className the name of the class type to which we want to cals * * @return mixed a version of the incoming $instance casted as the specified className */ function learndash_cast_WpProQuiz_Model_AnswerTypes($instance, $className) { return unserialize(sprintf( 'O:%d:"%s"%s', \strlen($className), $className, strstr(strstr(serialize($instance), '"'), ':') )); }
| ver. 1.4 |
Github
|
.
| PHP 7.0.33 | Generation time: 0.02 |
proxy
|
phpinfo
|
Settings