Serializes Question solutions.

@param GraphicQuestion $graphicQuestion

@return array
189400
private function serializeSolutions(GraphicQuestion $graphicQuestion)
    {
        return array_map(function (Area $area) {
            $solutionData = [
                'area' => $this->serializeArea($area),
                'score' => $area->getScore(),
            ];

            if ($area->getFeedback()) {
                $solutionData['feedback'] = $area->getFeedback();
            }

            return $solutionData;
        }, $graphicQuestion->getAreas()->toArray());
    }
1327291
public function getCsvAnswers(AbstractItem $item, Answer $answer)
    {
        $data = json_decode($answer->getData(), true);
        $answers = [];

        foreach ($item->getChoices() as $choice) {
            if (is_array($data) && in_array($choice->getUuid(), $data)) {
                $answers[] = $choice->getData();
            }
        }

        $compressor = new ArrayCompressor();

        return [$compressor->compress($answers)];
    }
1322428
public function process_mc($xml, &$questions) {

        if ($this->getpath($xml, array('POOL', '#', 'QUESTION_MULTIPLECHOICE'), false, false)) {
            $mcquestions = $this->getpath($xml,
                    array('POOL', '#', 'QUESTION_MULTIPLECHOICE'), false, false);
        } else {
            return;
        }

        foreach ($mcquestions as $thisquestion) {

            $question = $this->process_common($thisquestion);

            $correctfeedback = $this->getpath($thisquestion,
                    array('#', 'GRADABLE', 0, '#', 'FEEDBACK_WHEN_CORRECT', 0, '#'),
                    '', true);
            $incorrectfeedback = $this->getpath($thisquestion,
                    array('#', 'GRADABLE', 0, '#', 'FEEDBACK_WHEN_INCORRECT', 0, '#'),
                    '', true);
            $question->correctfeedback = $this->cleaned_text_field($correctfeedback);
            $question->partiallycorrectfeedback = $this->text_field('');
            $question->incorrectfeedback = $this->cleaned_text_field($incorrectfeedback);

            $question->qtype = 'multichoice';
            $question->single = 1; // Only one answer is allowed.

            $choices = $this->getpath($thisquestion, array('#', 'ANSWER'), false, false);
            $correctanswerid = $this->getpath($thisquestion,
                        array('#', 'GRADABLE', 0, '#', 'CORRECTANSWER', 0, '@', 'answer_id'),
                        '', true);
            foreach ($choices as $choice) {
                $choicetext = $this->getpath($choice, array('#', 'TEXT', 0, '#'), '', true);
                // Put this choice in the question object.
                $question->answer[] = $this->cleaned_text_field($choicetext);

                $choiceid = $this->getpath($choice, array('@', 'id'), '', true);
                // If choice is the right answer, give 100% mark, otherwise give 0%.
                if (strcmp ($choiceid, $correctanswerid) == 0) {
                    $question->fraction[] = 1;
                } else {
                    $question->fraction[] = 0;
                }
                // There is never feedback specific to each choice.
                $question->feedback[] = $this->text_field('');
            }
            $questions[] = $question;
        }
    }
1365170
private function deserializeImage(GraphicQuestion $graphicQuestion, array $imageData)
    {
        $image = $graphicQuestion->getImage() ?: new Image();

        $this->sipe('id', 'setUuid', $imageData, $image);
        $this->sipe('type', 'setType', $imageData, $image);
        $this->sipe('id', 'setTitle', $imageData, $image);
        $this->sipe('width', 'setWidth', $imageData, $image);
        $this->sipe('height', 'setHeight', $imageData, $image);

        $objectClass = get_class($graphicQuestion);
        $objectUuid = $graphicQuestion->getQuestion() ? $graphicQuestion->getQuestion()->getUuid() : null;
        $title = $graphicQuestion->getQuestion() ? $graphicQuestion->getQuestion()->getTitle() : null;

        $typeParts = explode('/', $imageData['type']);

        if (isset($imageData['data'])) {
            $imageName = "{$imageData['id']}.{$typeParts[1]}";
            $publicFile = $this->fileUtils->createFileFromData(
                $imageData['data'],
                $imageName,
                $objectClass,
                $objectUuid,
                $title,
                $objectClass
            );

            if ($publicFile) {
                $image->setUrl($publicFile->getUrl());
            }
        } elseif (isset($imageData['url'])) {
            $image->setUrl($imageData['url']);
        }

        $graphicQuestion->setImage($image);
    }
597987
public function getStatistics(Item $question, Exercise $exercise = null, $finishedPapersOnly = false)
    {
        $questionStats = [];

        // We load all the answers for the question (we need to get the entities as the response in DB are not processable as is)
        $answers = $this->answerRepository->findByQuestion($question, $exercise, $finishedPapersOnly);

        // Number of Users that have seen the question
        $questionStats['seen'] = count($answers);

        // Grab answer data to pass it decoded to the question type
        // it doesn't need to know the whole Answer object
        $answersData = [];

        // get corrected answers for the Item in order to compute question success percentage
        $correctedAnswers = [];

        // Number of Users that have answered the question (no blank answer)
        $questionStats['answered'] = 0;

        if (!empty($answers)) {
            // Let the handler of the question type parse and compile the data
            $definition = $this->itemDefinitions->get($question->getMimeType());

            for ($i = 0; $i < $questionStats['seen']; ++$i) {
                $answer = $answers[$i];
                if (!empty($answer->getData())) {
                    ++$questionStats['answered'];
                    $answersData[] = json_decode($answer->getData(), true);
                }

                // for each answer get corresponding correction
                if ($definition instanceof AnswerableItemDefinitionInterface && isset($answersData[$i])) {
                    $corrected = $definition->correctAnswer($question->getInteraction(), $answersData[$i]);
                    $correctedAnswers[] = $corrected;
                }
            }

            // Let the handler of the question type parse and compile the data
            if ($definition instanceof AnswerableItemDefinitionInterface) {
                $questionStats['solutions'] = $definition->getStatistics($question->getInteraction(), $answersData, $questionStats['seen']);
            }
        }

        // get the number of good answers among all
        $nbGoodAnswers = 0;

        foreach ($correctedAnswers as $corrected) {
            if ($corrected instanceof CorrectedAnswer && 0 === count($corrected->getMissing()) && 0 === count($corrected->getUnexpected())) {
                ++$nbGoodAnswers;
            }
        }
        // compute question success percentage
        $questionStats['successPercent'] = $questionStats['answered'] > 0 ? (100 * $nbGoodAnswers) / $questionStats['answered'] : 0;

        return $questionStats;
    }
354977
public function find_right_answer($wrappedquestion) {
        // We only take into account *one* (the first) correct answer.
        while ($answer = array_shift($wrappedquestion->answers)) {
            if (!question_state::graded_state_for_fraction(
                    $answer->fraction)->is_incorrect()) {
                // Store this answer as a choice, only if this is a new one.
                $key = array_search($answer->answer, $this->choices);
                if ($key === false) {
                    $key = $answer->id;
                    $this->choices[$key] = $answer->answer;
                }
                return $key;
            }
        }
        // We should never get there.
        throw new coding_exception('shortanswerquestionwithoutrightanswer', $wrappedquestion->id);

    }
1127660
private function serializeObjects(Item $question, array $options = [])
    {
        return array_values(array_map(function (ItemObject $object) use ($options) {
            return $this->itemObjectSerializer->serialize($object, $options);
        }, $question->getObjects()->toArray()));
    }
1149263
private function serializeQuestionType(Item $question, array $options = [])
    {
        $type = $this->itemDefinitions->getConvertedType($question->getMimeType());
        $definition = $this->itemDefinitions->get($type);

        return $definition->serializeQuestion($question->getInteraction(), $options);
    }
1215255
public function serialize()
    {
        $frame = $this->frame;
        if (!empty($this->comments)) {
            $frame['_comments'] = $this->comments;
        }

        return serialize($frame);
    }
77868
public function serialize(BooleanQuestion $question, array $options = [])
    {
        // Serializes choices
        $choices = $this->serializeChoices($question, $options);

        if (in_array(Transfer::SHUFFLE_ANSWERS, $options)) {
            shuffle($choices);
        }

        $serialized = ['choices' => $choices];

        if (in_array(Transfer::INCLUDE_SOLUTIONS, $options)) {
            $serialized['solutions'] = $this->serializeSolutions($question);
        }

        return $serialized;
    }
1039425
private function serializeTags(Item $question)
    {
        $event = new GenericDataEvent([
            'class' => Item::class,
            'ids' => [$question->getUuid()],
        ]);
        $this->eventDispatcher->dispatch('claroline_retrieve_used_tags_by_class_and_ids', $event);

        return $event->getResponse();
    }
161331
public function get_question_options($question) {
        global $DB, $OUTPUT;
        // Get additional information from database
        // and attach it to the question object.
        if (!$question->options = $DB->get_record('question_truefalse',
                array('question' => $question->id))) {
            echo $OUTPUT->notification('Error: Missing question options!');
            return false;
        }
        // Load the answers.
        if (!$question->options->answers = $DB->get_records('question_answers',
                array('question' =>  $question->id), 'id ASC')) {
            echo $OUTPUT->notification('Error: Missing question answers for truefalse question ' .
                    $question->id . '!');
            return false;
        }

        return true;
    }
785275
private function serializeSolutions(PairQuestion $pairQuestion)
    {
        // Merge rows and odd items in one array
        return array_merge(
            // Rows
            array_map(function (GridRow $row) {
                $solution = [
                    'ordered' => $row->isOrdered(),
                    'itemIds' => array_map(function (GridItem $item) {
                        return $item->getUuid();
                    }, $row->getItems()),
                    'score' => $row->getScore(),
                ];

                if ($row->getFeedback()) {
                    $solution['feedback'] = $row->getFeedback();
                }

                return $solution;
            }, $pairQuestion->getRows()->toArray()),
            // Odd items
            array_map(function (GridOdd $odd) {
                $solution = [
                    'itemIds' => [$odd->getItem()->getUuid()],
                    'score' => $odd->getScore(),
                ];

                if ($odd->getFeedback()) {
                    $solution['feedback'] = $odd->getFeedback();
                }

                return $solution;
            }, $pairQuestion->getOddItems()->toArray())
        );
    }
891730
public function serialize()
    {
        return serialize(
            [
                $this->outFilePath,
                $this->width,
                $this->height,
                $this->frameRate,
                $this->loopCount,
                $this->gifData,
                $this->frames,
                $this->counter,
            ]
        );
    }
762585
protected function output_statistics_graph($quizorid, $qubaids) {
        global $DB, $PAGE;

        $quiz = $quizorid;
        if (!is_object($quiz)) {
            $quiz = $DB->get_record('quiz', array('id' => $quizorid), '*', MUST_EXIST);
        }

        // Load the rest of the required data.
        $questions = quiz_report_get_significant_questions($quiz);

        // Only load main question not sub questions.
        $questionstatistics = $DB->get_records_select('question_statistics',
                'hashcode = ? AND slot IS NOT NULL AND variant IS NULL',
            [$qubaids->get_hash_code()]);

        // Configure what to display.
        $fieldstoplot = [
            'facility' => get_string('facility', 'quiz_statistics'),
            'discriminativeefficiency' => get_string('discriminative_efficiency', 'quiz_statistics')
        ];
        $fieldstoplotfactor = ['facility' => 100, 'discriminativeefficiency' => 1];

        // Prepare the arrays to hold the data.
        $xdata = [];
        foreach (array_keys($fieldstoplot) as $fieldtoplot) {
            $ydata[$fieldtoplot] = [];
        }

        // Fill in the data for each question.
        foreach ($questionstatistics as $questionstatistic) {
            $number = $questions[$questionstatistic->slot]->number;
            $xdata[$number] = $number;

            foreach ($fieldstoplot as $fieldtoplot => $notused) {
                $value = $questionstatistic->$fieldtoplot;
                if (is_null($value)) {
                    $value = 0;
                }
                $value *= $fieldstoplotfactor[$fieldtoplot];
                $ydata[$fieldtoplot][$number] = number_format($value, 2);
            }
        }

        // Create the chart.
        sort($xdata);
        $chart = new \core\chart_bar();
        $chart->get_xaxis(0, true)->set_label(get_string('position', 'quiz_statistics'));
        $chart->set_labels(array_values($xdata));

        foreach ($fieldstoplot as $fieldtoplot => $notused) {
            ksort($ydata[$fieldtoplot]);
            $series = new \core\chart_series($fieldstoplot[$fieldtoplot], array_values($ydata[$fieldtoplot]));
            $chart->add_series($series);
        }

        // Find max.
        $max = 0;
        foreach ($fieldstoplot as $fieldtoplot => $notused) {
            $max = max($max, max($ydata[$fieldtoplot]));
        }

        // Set Y properties.
        $yaxis = $chart->get_yaxis(0, true);
        $yaxis->set_stepsize(10);
        $yaxis->set_label('%');

        $output = $PAGE->get_renderer('mod_quiz');
        $graphname = get_string('statisticsreportgraph', 'quiz_statistics');
        echo $output->chart($chart, $graphname);
    }
748216
private function serializeChoices(BooleanQuestion $question, array $options = [])
    {
        return array_map(function (BooleanChoice $choice) use ($options) {
            $choiceData = $this->contentSerializer->serialize($choice, $options);
            $choiceData['id'] = $choice->getUuid();

            return $choiceData;
        }, $question->getChoices()->toArray());
    }
1298171
public static function make_question($questiondata) {
        return self::get_qtype($questiondata->qtype, false)->make_question($questiondata, false);
    }