Example #1
0
 /**
  * Try to add this specific question to the database (to the pool).
  * @param Array $singleQuestionData Specific question data to add.
  * @return Integer The ID of the newly inserted question ID, or false if it wasn't added.
  */
 private function loadQuestionData_addQuestionToDatabase($singleQuestionData)
 {
     if (!$singleQuestionData || empty($singleQuestionData)) {
         return false;
     }
     global $wpdb, $wpcwdb;
     $wpdb->show_errors();
     // ### 1 - Initialise data to be added for question.
     $questionDetailsToAdd = $singleQuestionData;
     // ### 2 - Need to strip out question order, as there is no question_order field
     // in the database, so we need to use it in the mappings data.
     $question_order = WPCW_arrays_getValue($singleQuestionData, 'question_order');
     unset($questionDetailsToAdd['question_order']);
     // ### 3 - Handle the insert of the special arrays that need serialising. We know these exist
     // as we have specifically validated them.
     $questionDetailsToAdd['question_data_answers'] = false;
     if (!empty($singleQuestionData['question_data_answers'])) {
         $questionDetailsToAdd['question_data_answers'] = serialize($singleQuestionData['question_data_answers']);
     }
     // ### 4 - Extract tags from the question data so that we can insert the question into
     //		   the database without any errors.
     $tagList = array();
     if (isset($questionDetailsToAdd['tags'])) {
         $tagList = $questionDetailsToAdd['tags'];
     }
     unset($questionDetailsToAdd['tags']);
     // ### 5 - Insert details of this particular question into the database.
     $queryResult = $wpdb->query(arrayToSQLInsert($wpcwdb->quiz_qs, $questionDetailsToAdd));
     // ### 6 - Store the ID of the newly inserted ID, we'll need it for associating tags.
     $currentQuestionID = $wpdb->insert_id;
     // ### 7 - Check query succeeded.
     if ($queryResult === FALSE) {
         $this->errorList[] = __('There was a problem adding the question into the database.', 'wp_courseware');
         return false;
     }
     // ### 8 - Now we create the tag associations.
     WPCW_questions_tags_addTags($currentQuestionID, $tagList);
     return $currentQuestionID;
 }
Example #2
0
/**
 * Function called when a new question tag is added.
 */
function WPCW_AJAX_handleQuestionNewTag()
{
    $ajaxResults = array('success' => true, 'errormsg' => __('Unfortunately there was a problem adding the tag.', 'wp_courseware'), 'html' => false);
    // Assume that we may have multiple tags, separated by commas.
    $potentialTagList = explode(',', WPCW_arrays_getValue($_POST, 'tagtext'));
    $cleanTagList = array();
    // Check if question is expected to have been saved.
    $hasQuestionBeenSaved = 'yes' == WPCW_arrays_getValue($_POST, 'isquestionsaved');
    // Got potential tags
    if (!empty($potentialTagList)) {
        // Clean up each tag, and add to a list.
        foreach ($potentialTagList as $potentialTag) {
            $cleanTagList[] = sanitize_text_field(stripslashes($potentialTag));
        }
        // Check that cleaned tags are ok too
        if (!empty($cleanTagList)) {
            // Do this if the question exists and we're adding tags.
            if ($hasQuestionBeenSaved) {
                // Get the ID of the question we're adding this tag to.
                $questionID = intval(WPCW_arrays_getValue($_POST, 'questionid'));
                // Validate that the question exists before we tag it.
                $questionDetails = WPCW_questions_getQuestionDetails($questionID);
                if (!$questionDetails) {
                    $ajaxResults['errormsg'] = __('Unfortunately that question could not be found, so the tag could not be added.', 'wp_courseware');
                    $ajaxResults['success'] = false;
                } else {
                    // Add the tag to the database, get a list of the tag details now that they have been added.
                    $tagDetailList = WPCW_questions_tags_addTags($questionID, $cleanTagList);
                    foreach ($tagDetailList as $tagAddedID => $tagAddedText) {
                        // Create the HTML to show the new tag.
                        $ajaxResults['html'] .= sprintf('<span><a data-questionid="%d" data-tagid="%d" class="ntdelbutton">X</a>&nbsp;%s</span>', $questionID, $tagAddedID, $tagAddedText);
                    }
                }
                // else question found
            } else {
                $tagDetailList = WPCW_questions_tags_addTags_withoutQuestion($cleanTagList);
                // For a new question, the ID is a string, not a value.
                $questionIDStr = WPCW_arrays_getValue($_POST, 'questionid');
                // Create a hidden form entry plus the little tag, so that we can add the tag to the question when we save.
                foreach ($tagDetailList as $tagAddedID => $tagAddedText) {
                    // Create the HTML to show the new tag. We'll add the full string to the hidden field so that we can
                    // add the tags later.
                    $ajaxResults['html'] .= sprintf('
								<span>
									<a data-questionid="%d" data-tagid="%d" class="ntdelbutton">X</a>&nbsp;%s
									<input type="hidden" name="tags_to_add%s[]" value="%s" />
								</span>
								', 0, $tagAddedID, $tagAddedText, $questionIDStr, addslashes($tagAddedText));
                }
                // end foreach
            }
        }
    }
    header('Content-Type: application/json');
    echo json_encode($ajaxResults);
    die;
}
/**
 * Handle saving questions to the database.
 * 
 * @param Integer $quizID The quiz for which the questions apply to. 
 * @param Boolean $singleQuestionMode If true, then we're updating a single question, and we do things slightly differently.
 */
function WPCW_handler_questions_processSave($quizID, $singleQuestionMode = false)
{
    global $wpdb, $wpcwdb;
    $wpdb->show_errors();
    $questionsToSave = array();
    $questionsToSave_New = array();
    // Check $_POST data for the
    foreach ($_POST as $key => $value) {
        // #### 1 - Check if we're deleting a question from this quiz
        // We're not just deleting the question, just the association. This is because questions remain in the
        // pool now.
        if (preg_match('/^delete_wpcw_quiz_details_([0-9]+)$/', $key, $matches)) {
            // Remove mapping from the mapping table.
            $SQL = $wpdb->prepare("\n\t\t\t\tDELETE FROM {$wpcwdb->quiz_qs_mapping}\n\t\t\t\tWHERE question_id = %d\n\t\t\t\t  AND parent_quiz_id = %d\n\t\t\t", $matches[1], $quizID);
            $wpdb->query($SQL);
            // Update usage counts
            WPCW_questions_updateUsageCount($matches[1]);
            // Just a deletion - move on to next array item to save processing time.
            continue;
        }
        // #### 2 - See if we have a question to check for.
        if (preg_match('/^question_question_(new_question_)?([0-9]+)$/', $key, $matches)) {
            // Got the ID of the question, now get answers and correct answer.
            $questionID = $matches[2];
            // Store the extra string if we're adding a new question.
            $newQuestionPrefix = $matches[1];
            $fieldName_Answers = 'question_answer_' . $newQuestionPrefix . $questionID;
            $fieldName_Answers_Img = 'question_answer_image_' . $newQuestionPrefix . $questionID;
            $fieldName_Correct = 'question_answer_sel_' . $newQuestionPrefix . $questionID;
            $fieldName_Type = 'question_type_' . $newQuestionPrefix . $questionID;
            $fieldName_Order = 'question_order_' . $newQuestionPrefix . $questionID;
            $fieldName_AnswerType = 'question_answer_type_' . $newQuestionPrefix . $questionID;
            $fieldName_AnswerHint = 'question_answer_hint_' . $newQuestionPrefix . $questionID;
            $fieldName_Explanation = 'question_answer_explanation_' . $newQuestionPrefix . $questionID;
            $fieldName_Image = 'question_image_' . $newQuestionPrefix . $questionID;
            // For Multi-Choice - Answer randomization
            $fieldName_Multi_Random_Enable = 'question_multi_random_enable_' . $newQuestionPrefix . $questionID;
            $fieldName_Multi_Random_Count = 'question_multi_random_count_' . $newQuestionPrefix . $questionID;
            // Order should be a number
            $questionOrder = 0;
            if (isset($_POST[$fieldName_Order])) {
                $questionOrder = $_POST[$fieldName_Order] + 0;
            }
            // Default types
            $qAns = false;
            $qAnsCor = false;
            $qAnsType = false;
            // Just used for open question types.
            $qAnsFileTypes = false;
            // Just used for upload file types.
            // Get the hint - Just used for open and upload types. Allow HTML.
            $qAnsHint = trim(WPCW_arrays_getValue($_POST, $fieldName_AnswerHint));
            // Get the explanation - All questions. Allow HTML.
            $qAnsExplain = trim(WPCW_arrays_getValue($_POST, $fieldName_Explanation));
            // The image URL to use. No HTML. Table record is 300 chars, hence cropping.
            $qQuesImage = trim(substr(strip_tags(WPCW_arrays_getValue($_POST, $fieldName_Image)), 0, 300));
            // How many questions are there is this selection? 1 by default for non-random questions.
            $expandedQuestionCount = 1;
            // For Multi-Choice - Answer randomization
            $qMultiRandomEnable = false;
            $qMultiRandomCount = 5;
            // What type of question do we have?
            $questionType = WPCW_arrays_getValue($_POST, $fieldName_Type);
            switch ($questionType) {
                case 'multi':
                    $qAns = WPCW_quiz_MultipleChoice::editSave_extractAnswerList($fieldName_Answers, $fieldName_Answers_Img);
                    $qAnsCor = WPCW_quiz_MultipleChoice::editSave_extractCorrectAnswer($qAns, $fieldName_Correct);
                    // Provide the UI with at least once slot for an answer.
                    if (!$qAns) {
                        $qAns = array('1' => array('answer' => ''), '2' => array('answer' => ''));
                    }
                    // Check randomization values (boolean will be 'on' to enable, as it's a checkbox)
                    $qMultiRandomEnable = 'on' == WPCW_arrays_getValue($_POST, $fieldName_Multi_Random_Enable);
                    $qMultiRandomCount = intval(WPCW_arrays_getValue($_POST, $fieldName_Multi_Random_Count));
                    break;
                case 'open':
                    // See if there's a question type that's been sent back to the server.
                    $answerTypes = WPCW_quiz_OpenEntry::getValidAnswerTypes();
                    $thisAnswerType = WPCW_arrays_getValue($_POST, $fieldName_AnswerType);
                    // Validate the answer type is in the list. Don't create a default so that user must choose.
                    if (isset($answerTypes[$thisAnswerType])) {
                        $qAnsType = $thisAnswerType;
                    }
                    // There's no correct answer for an open question.
                    $qAnsCor = false;
                    break;
                case 'upload':
                    $fieldName_FileType = 'question_answer_file_types_' . $newQuestionPrefix . $questionID;
                    // Check new file extension types, parsing them.
                    $qAnsFileTypesRaw = WPCW_files_cleanFileExtensionList(WPCW_arrays_getValue($_POST, $fieldName_FileType));
                    $qAnsFileTypes = implode(',', $qAnsFileTypesRaw);
                    break;
                case 'truefalse':
                    $qAnsCor = WPCW_quiz_TrueFalse::editSave_extractCorrectAnswer($fieldName_Correct);
                    break;
                    // Validate the the JSON data here... ensure all the tags are valid (not worried about the counts).
                    // Then save back to database.
                // Validate the the JSON data here... ensure all the tags are valid (not worried about the counts).
                // Then save back to database.
                case 'random_selection':
                    // Reset to zero for counting below.
                    $expandedQuestionCount = 0;
                    $decodedTags = WPCW_quiz_RandomSelection::decodeTagSelection(stripslashes($value));
                    // Capture just ID and count and resave back to database.
                    $toSaveList = false;
                    if (!empty($decodedTags)) {
                        $toSaveList = array();
                        foreach ($decodedTags as $decodedKey => $decodedDetails) {
                            $toSaveList[$decodedKey] = $decodedDetails['count'];
                            // Track requested questions
                            $expandedQuestionCount += $decodedDetails['count'];
                        }
                    }
                    // Overwrite $value to use cleaned question
                    $value = json_encode($toSaveList);
                    break;
                    // Not expecting anything here... so not handling the error case.
                // Not expecting anything here... so not handling the error case.
                default:
                    break;
            }
            // ### 4a - Encode the answer data
            $encodedqAns = $qAns;
            if (!empty($qAns)) {
                foreach ($encodedqAns as $idx => $data) {
                    $encodedqAns[$idx]['answer'] = base64_encode($data['answer']);
                }
            }
            // ### 4b - Save new question data as a list ready for saving to the database.
            $quDataToSave = array('question_answers' => false, 'question_question' => stripslashes($value), 'question_data_answers' => serialize($encodedqAns), 'question_correct_answer' => $qAnsCor, 'question_type' => $questionType, 'question_order' => $questionOrder, 'question_answer_type' => $qAnsType, 'question_answer_hint' => stripslashes($qAnsHint), 'question_answer_explanation' => stripslashes($qAnsExplain), 'question_answer_file_types' => $qAnsFileTypes, 'question_image' => $qQuesImage, 'question_expanded_count' => $expandedQuestionCount, 'question_multi_random_enable' => $qMultiRandomEnable, 'question_multi_random_count' => $qMultiRandomCount, 'taglist' => array());
            // ### 5 - Check if there are any tags to save. Only happens for questions that
            // haven't been saved, so that we can save when we do a $_POST save.
            $tagFieldForNewQuestions = 'tags_to_add_' . $newQuestionPrefix . $questionID;
            if (isset($_POST[$tagFieldForNewQuestions])) {
                if (!empty($_POST[$tagFieldForNewQuestions])) {
                    // Validate each tag ID we have, add to list to be stored for this question later.
                    foreach ($_POST[$tagFieldForNewQuestions] as $idx => $tagText) {
                        $tagText = trim(stripslashes($tagText));
                        if ($tagText) {
                            $quDataToSave['taglist'][] = $tagText;
                        }
                    }
                }
            }
            // Not a new question - so not got question ID as yet
            if ($newQuestionPrefix) {
                $questionsToSave_New[] = $quDataToSave;
            } else {
                $quDataToSave['question_id'] = $questionID;
                $questionsToSave[$questionID] = $quDataToSave;
            }
        }
        // end if question found.
    }
    // Only need to adjust quiz settings when editing a quiz and not a single question.
    if (!$singleQuestionMode) {
        // #### 6 - Remove association of all questions for this quiz
        //          as we're going to re-add them.
        $wpdb->query($wpdb->prepare("\n\t\t\t\t\tDELETE FROM {$wpcwdb->quiz_qs_mapping}\n\t\t\t\t\tWHERE parent_quiz_id = %d\n\t\t\t\t", $quizID));
    }
    // #### 7 - Check we have existing questions to save
    if (count($questionsToSave)) {
        // Now save all data back to the database.
        foreach ($questionsToSave as $questionID => $questionDetails) {
            // Extract the question order, as can't save order with question in DB
            $questionOrder = $questionDetails['question_order'];
            unset($questionDetails['question_order']);
            // Tag list only used for new questions, so remove this field
            unset($questionDetails['taglist']);
            // Save question details back to database.
            $wpdb->query(arrayToSQLUpdate($wpcwdb->quiz_qs, $questionDetails, 'question_id'));
            // No need to update counts/associations when editing a single lone question
            if (!$singleQuestionMode) {
                // Create the association for this quiz/question.
                $wpdb->query($wpdb->prepare("\n\t\t\t\t\tINSERT INTO {$wpcwdb->quiz_qs_mapping} \n\t\t\t\t\t(question_id, parent_quiz_id, question_order)\n\t\t\t\t\tVALUES (%d, %d, %d)\n\t\t\t\t", $questionID, $quizID, $questionOrder));
                // Update usage count for question.
                WPCW_questions_updateUsageCount($questionID);
            }
        }
    }
    // #### 8 - Save the new questions we have
    if (count($questionsToSave_New)) {
        // Now save all data back to the database.
        foreach ($questionsToSave_New as $questionDetails) {
            // Extract the question order, as can't save order with question in DB
            $questionOrder = $questionDetails['question_order'];
            unset($questionDetails['question_order']);
            // Extract the tags added for this question - we'll save manually.
            $tagsToAddList = $questionDetails['taglist'];
            unset($questionDetails['taglist']);
            // Create question in database
            $wpdb->query(arrayToSQLInsert($wpcwdb->quiz_qs, $questionDetails));
            $newQuestionID = $wpdb->insert_id;
            // No need to update counts/associations when editing a single lone question
            if (!$singleQuestionMode) {
                // Create the association for this quiz/question.
                $wpdb->query($wpdb->prepare("\n\t\t\t\t\tINSERT INTO {$wpcwdb->quiz_qs_mapping} \n\t\t\t\t\t(question_id, parent_quiz_id, question_order)\n\t\t\t\t\tVALUES (%d, %d, %d)\n\t\t\t\t", $newQuestionID, $quizID, $questionOrder));
                // Update usage
                WPCW_questions_updateUsageCount($newQuestionID);
            }
            // Add associations for tags for this unsaved question now we finally have a question ID.
            if (!empty($tagsToAddList)) {
                WPCW_questions_tags_addTags($newQuestionID, $tagsToAddList);
            }
        }
    }
}