lib/model/WpProQuiz_Model_Statistic.php000066600000005750152142366250014233 0ustar00_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.php000066600000010557152142366250016353 0ustar00setAddRawShortcode( $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.php000066600000030264152142366250015236 0ustar00_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.php000066600000003277152142366250016610 0ustar00_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.php000066600000021427152142366250014360 0ustar00_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.php000066600000002773152142366250013512 0ustar00_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.php000066600000037317152142366250016041 0ustar00 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.php000066600000002070152142366250015175 0ustar00_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.php000066600000001001152142366250014022 0ustar00_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.php000066600000006777152142366250014562 0ustar00_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.php000066600000003136152142366250013716 0ustar00_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.php000066600000005603152142366250015646 0ustar00_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.php000066600000005761152142366250015074 0ustar00_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.php000066600000001762152142366250013153 0ustar00_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.php000066600000001522152142366250014030 0ustar00_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.php000066600000003520152142366250015753 0ustar00_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.php000066600000065705152142366250013222 0ustar00_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.php000066600000004051152142366250014312 0ustar00_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.php000066600000005511152142366250015062 0ustar00= '.(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.php000066600000004764152142366250013173 0ustar00_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.php000066600000006637152142366250015405 0ustar00_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.php000066600000023604152142366250014071 0ustar00_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.php000066600000003642152142366250015202 0ustar00_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.php000066600000004755152142366250016116 0ustar00delete( $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.php000066600000007527152142366250015212 0ustar00_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.php000066600000002470152142366250013320 0ustar00setModelData($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.php000066600000005341152142366250015611 0ustar00_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.php000066600000003403152142366250014325 0ustar00_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.php000066600000003300152142366250016224 0ustar00_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.php000066600000003237152142366250015763 0ustar00get_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.php000066600000003320152142366250015755 0ustar00actions = 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.php000066600000026411152142366250016065 0ustar00loadToplist($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.php000066600000124436152142366250015365 0ustar00showAction(); 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
'. print_r($v, true) .'
'); $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
'. print_r($email_settings_admin, true) .'
'); $email_settings_user = LearnDash_Settings_Section::get_section_settings_all( 'LearnDash_Settings_Quizzes_User_Email' ); //error_log('email_settings_user
'. print_r($email_settings_user, true) .'
'); $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
'. print_r($email_params, true) .'
'); 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
'. print_r($email_params, true) .'
'); 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.php000066600000001311152142366250016047 0ustar00handleExport(); } 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.php000066600000041415152142366250016237 0ustar00_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 = "" . esc_html__( "Click here to add another question.", 'learndash' ) . ""; //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.php000066600000004536152142366250017354 0ustar00edit(); } 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.php000066600000002020152142366250017010 0ustar00show(); } 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.php000066600000023602152142366250015516 0ustar00loadSettings(); 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.php000066600000001406152142366250016177 0ustar00updateName($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.php000066600000024065152142366250015462 0ustar00_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.php000066600000000541152142366250016546 0ustar00_post === null) { $this->_post = stripslashes_deep($_POST); } if($this->_cookie === null && $_COOKIE !== null) { $this->_cookie = stripslashes_deep($_COOKIE); } } }lib/controller/WpProQuiz_Controller_Category.php000066600000002253152142366250016202 0ustar00save( $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.php000066600000005424152142366250016051 0ustar00 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.php000066600000022567152142366250017224 0ustar00data = $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.php000066600000004614152142366250015313 0ustar00initCallbacks(); 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.php000066600000065702152142366250016567 0ustar00show($_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.php000066600000002631152142366250014452 0ustar00
inQuiz) { ?>

: quiz->getName(); ?>

'. $this->points .''); ?>


error) { ?>

error; ?>
finish) { ?>

import_post_id ) { $edit_link = '' . sprintf( // translators: placeholder: Quiz Title. esc_html_x('%s', 'placeholder: Quiz Title', 'learndash'), get_the_title( $this->import_post_id ) ) . ''; } echo wpautop( sprintf( // translators: placeholder: link to Imported Quiz esc_html_x( 'Import completed successfully: %s', 'placeholder: link to Imported Quiz.', 'learndash' ), $edit_link ) ); ?>
' . sprintf( // translators: placeholder: Quiz. esc_html_x( 'Return to %s Import/Export.', 'placeholder: Quiz', 'learndash' ), LearnDash_Custom_Label::get_label( 'quiz' ) ) . '' ); */ ?>
import['master'] as $master) { ?>
getName(); ?>
    import['question'][$master->getId()])) { ?> import['question'][$master->getId()] as $question) { ?>
  • getTitle(); ?>

header; ?>

question->getQuestion(), "question", array('textarea_rows' => 5)); ?>

question->getCorrectMsg(), "correctMsg", array('textarea_rows' => 3)); ?>

question->getIncorrectMsg(), "incorrectMsg", array('textarea_rows' => 3)); ?>

question->getTipMsg(), 'tipMsg', array('textarea_rows' => 3)); ?>

question->getAnswerType(); $type = $type === null ? 'single' : $type; ?>
singleChoiceOptions($this->data['classic_answer']); ?>

freeChoice($this->data['free_answer']); ?>

    sortingChoice($this->data['sort_answer']); ?>
    singleMultiCoice($this->data['classic_answer']); ?>



    matrixSortingChoice($this->data['matrix_sort_answer']); ?>
clozeChoice($this->data['cloze_answer']); ?>
assessmentChoice($this->data['assessment_answer']); ?>
essayChoice($this->data['essay']); ?>
  • "I {[play][love][hate]} soccer" . In this case answers play, love OR hate are correct.', 'learndash') ); ?>

    getAnswer(), 'cloze', array('textarea_rows' => 10, 'textarea_name' => 'answerData[cloze][answer]')); ?>



    *

    *

    getAnswer(), 'assessment', array('textarea_rows' => 10, 'textarea_name' => 'answerData[assessment][answer]')); ?>




    This changes the calculation of the points', 'learndash') ); ?>




    answerPointDia(); ?>

    quiz->getName() ); ?>

    quiz->isStatisticsOn()) { ?>

    formTable(); ?> questionList as $k => $ql) { $index = 1; $cPoints = 0; ?> getPoints(); $cPoints += $q->getPoints(); ?>
    (hh:mm:ss)
    : categoryList[$k]->getCategoryName(); ?>
    getTitle(); ?> getPoints(); ?>
    quiz->isFormActivated()) return; ?>

    forms as $form) { /* @var $form WpProQuiz_Model_Form */ ?>
    getFieldname()); ?> asdfffffffffffffffffffffsadfsdfa sf asd fas
    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 '

    '.$msg.'

    '; else echo '

    '.$msg.'

    '; } 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.php000066600000011417152142366250014414 0ustar00

    quiz->getName(); ?>

    • :
    load
    |

    : quiz->getName(); ?>


    question)) { foreach ($this->question as $question) { $points += $question->getPoints(); ?>
    'ldAdvQuiz', 'module' => 'question', 'action' => 'addEdit', 'quiz_id' => $this->quiz->getId(), 'questionId' => $question->getId(), 'post_id' => @$_GET['post_id'] ), admin_url('admin.php') ); ?>getTitle(); ?>
    | |
    getAnswerType(); if (isset($learndash_question_types[$question_type])) { echo $learndash_question_types[$question_type]; } ?> getCategoryName(); ?> getPoints(); ?>

    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 ); ?>
    posts ) ) ) { foreach( $quiz_query_results->posts as $quiz_post ) { ?>
    ID; ?> - ID ); ?>
    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 ) { ?>
    $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', ) ); } ?>

    quiz)) { ?>

    _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(), ); ?>
    quiz->isTitleHidden() ) { echo '

    ', $this->quiz->getName(), '

    '; } 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 ); ?>
    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 " "; } 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 ""; } 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'] ); ?>
    quiz->isTitleHidden() ) { echo '

    ', $this->quiz->getName(), '

    '; } 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(); ?>
    showQuizBox( count( $this->question ) ); $quizData['content'] = ob_get_contents(); $quizData['site_url'] = get_site_url(); ob_end_clean(); return $quizData; } private function showQuizAnker() { ?> $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 = ' '; $a .= ''; $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 .= ''; } $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 = '
    ' . esc_html__( 'You must fill out this field.', 'learndash' ) . '
    '; $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' ) ); ?>
    forms as $form ) { /* @var $form WpProQuiz_Model_Form */ $id = 'forms_' . $this->quiz->getId() . '_' . $index ++; $name = 'wpProQuiz_field_' . $form->getFormId(); ?>
    '; echo esc_html( $form->getFieldname() ); echo $form->isRequired() ? '*' : ''; echo ''; ?> getType() ) { case WpProQuiz_Model_Form::FORM_TYPE_TEXT: case WpProQuiz_Model_Form::FORM_TYPE_EMAIL: case WpProQuiz_Model_Form::FORM_TYPE_NUMBER: echo ''; break; case WpProQuiz_Model_Form::FORM_TYPE_TEXTAREA: echo ''; break; case WpProQuiz_Model_Form::FORM_TYPE_CHECKBOX: echo ''; break; case WpProQuiz_Model_Form::FORM_TYPE_DATE: echo '
    '; echo WpProQuiz_Helper_Until::getDatePicker( get_option( 'date_format', 'j. F Y' ), $name ); echo '
    '; break; case WpProQuiz_Model_Form::FORM_TYPE_RADIO: echo '
    '; if ( $form->getData() !== null ) { foreach ( $form->getData() as $data ) { echo ' '; } } echo '
    '; break; case WpProQuiz_Model_Form::FORM_TYPE_SELECT: if ( $form->getData() !== null ) { echo ''; } break; case WpProQuiz_Model_Form::FORM_TYPE_YES_NO: echo '
    '; echo ' '; echo ' '; echo '
    '; break; } if ( isset( $validateText[ $form->getType() ] ) ) { echo '
    ' . $validateText[ $form->getType() ] . '
    '; } else { echo '
    ' . esc_html__( 'You must fill out this field.', 'learndash' ) . '
    '; } ?>
    quiz->isFormActivated() && $this->quiz->getFormShowPosition() == WpProQuiz_Model_Quiz::QUIZ_FORM_POSITION_START ) { $this->showFormBox(); } ?>
    '. print_r($post, true) .''); if ( current_user_can( 'wpProQuiz_show_statistics' ) ) { $user_quizzes = get_user_meta(get_current_user_id(), '_sfwd-quizzes', true); //error_log('user_quizzes
    '. print_r($user_quizzes, true) .'
    '); if ( !empty( $user_quizzes ) ) { //krsort($user_quizzes); $user_quizzes = array_reverse($user_quizzes); //error_log('sorted: user_quizzes
    '. print_r($user_quizzes, true) .'
    '); 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 .']'); ?>
    $globalPoints, 'json' => $json, 'catPoints' => $catPoints ); } private function showLoadQuizBox() { ?>


    Really Simple CAPTCHA

    captchaIsInstalled) { ?>


    continue', 'learndash'); ?>

    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()); ?>


    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 )); ?> >
    checked($form->isRequired()); ?>>

    10)); ?>

    globalSettings(); ?>

    category)) { ?> templateQuiz)) { ?> templateQuestion)) { ?>






    email['from'] ) ) && ( !is_email( $this->email['from'] ) ) ) { ?>

    (%s) will be used.', 'learndash') ), get_option('admin_email') ); ?>

    email['message'], 'adminEmailEditor', array('textarea_rows' => 20, 'textarea_name' => 'email[message]')); ?>

    :

    • $userId -
    • $username -
    • $quizname -
    • $result -
    • $points -
    • $ip -
    • $categories -
    isRaw) { $rawSystem = esc_html__('to activate', 'learndash'); } else { $rawSystem = esc_html__('not to activate', 'learndash'); } ?>

    emailSettings(); ?> userEmailSettings(); ?>

    quiz->getName()); ?>


    quiz->isStatisticsOn()) { ?>

    showHistory(); ?> showTabOverview(); ?>
    showModalWindow(); ?>

    • '; $dateBis = ''; printf(__('Search to date limit from %s to %s', 'learndash'), $dateVon, $dateBis); ?>
    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() { ?> historyModel)) { ?> historyModel as $model) { /* @var $model WpProQuiz_Model_StatisticHistory */ ?>
    getUserName(); ?>
    getFormatTime(); ?> getFormatCorrect(); ?> getFormatIncorrect(); ?> getPoints(); ?> getResult(); ?>%
    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 ) ) { ?>fetch( intval( $_POST['data']['quizId'] ) ); } else { return; } ?>

    userName ); ?>

    avg) { ?>

    statisticModel->getMinCreateTime() ); ?> - statisticModel->getMaxCreateTime() ); ?>

    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' ) ); ?>

    formTable(); ?> userStatistic as $cat) { $cCorrect = $cIncorrect = $cHintCount = $cPoints = $cGPoints = $cTime = 0; ?> 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']; ?> avg && $q['statistcAnswerData'] !== null) { ?>
    (hh:mm:ss)
    :
    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'] ); } ?>
    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 ) ) { ?>
    $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; } } } } } ?> _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 .= ''; } $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 = ' '; // $a .= ''; $a = ''.esc_html(isset($answerData[$index]) ? empty($answerData[$index]) ? '---' : $answerData[$index] : '---').' '; $a .= '('.implode(', ', $rowText).')'; $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; ?>

    forms as $form) { /* @var $form WpProQuiz_Model_Form */ if(!isset($formData[$form->getFormId()])) continue; $str = $formData[$form->getFormId()]; ?>
    getFieldname()); ?> 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; } ?>
    showOverviewTable(); $content = ob_get_contents(); ob_end_clean(); return $content; } public function showOverviewTable() { ?> statisticModel)) { ?> 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 = '---'; } ?>
    (hh:mm:ss)
    getUserName()); ?> getUserName()); } ?>
    >

    header; ?>

    1. Frage 4 von 7 1 Punkte

      4. Frage

      Frage3

      Korrekt

    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.php000066600000002767152142366250014172 0ustar00_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.php000066600000043344152142366250014556 0ustar00setError(__('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.php000066600000040702152142366250014560 0ustar00createElement( '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.php000066600000003463152142366250013524 0ustar00isRequired() && (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.php000066600000017060152142366250014071 0ustar00setError(__('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.php000066600000103436152142366250014457 0ustar00_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.php000066600000006312152142366250013710 0ustar00'; for($i = 1; $i <= 31; $i++) { $day .= ''; } $day .= ' '; $monthNumber = ' '; $monthName = ' '; $year = ' '; $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.php000066600000007510152142366250014205 0ustar00add_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.php000066600000001067152142366250007304 0ustar00delete(); 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.js000066600000002703152142366250011270 0ustar00function 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.js000066600000001704152142366250012052 0ustar00function 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;r1){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.js000066600000250667152142366250010740 0ustar00(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

    . // 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 ); $('

    '+basename( question_value )+'

    ').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('
    '+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"); $("", { 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.js000066600000136370152142366250011454 0ustar00jQuery(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()+''+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("").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("
  • "+t+"
  • ").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('').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('------------------');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.js000066600000006061152142366250010322 0ustar00/*! * 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.js000066600000234031152142366250010663 0ustar00jQuery(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(); $('
  • ' + text + '
  • ').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) { $('').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 = $( '' + '---' + '---' + '---' + '---' + '---' + '---' + '' ); $.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() + '' + 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() { $("") .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.js000066600000002731152142366250011104 0ustar00!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.js000066600000120513152142366250011504 0ustar00(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("

    "+s(t)+"

    ").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;e0)&&(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;n9?"":"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;tp.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=s&&e-s 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("",{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;in&&(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;itable{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.css000066600000023163152142366250011255 0ustar00.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.css000066600000017352152142366250012641 0ustar00.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.css000066600000023167152142366250012060 0ustar00.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.php000066600000012006152142366250007500 0ustar00extensions->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 = ' '; $a .= ''; $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), '"'), ':') )); }