Returns the answers for a matrix or list type question from the answers table

Uses 1 query to retrieve all answers and serves them as needed

@param integer    $qid        Question ID
@param integer    $scaleId    Scale ID
963471
private function _getHardAnswers($qid, $scaleId)
    {
        if (! is_array($this->_hardAnswers)) {
            $qaTable = $this->_getAnswersTableName();
            $qTable  = $this->_getQuestionsTableName();

            $sql = 'SELECT a.*, q.other FROM ' . $qaTable . ' AS a
                LEFT JOIN ' . $qTable . ' AS q ON q.qid = a.qid AND q.language = a.language
                WHERE q.sid = ? AND q.language = ? ORDER BY a.qid, a.scale_id, sortorder';
            
            $this->_hardAnswers = array();
            if ($rows = $this->lsDb->fetchAll($sql, array($this->sourceSurveyId, $this->language))) {
                foreach ($rows as $row) {
                    $this->_hardAnswers[$row['qid']][$row['scale_id']][$row['code']] = $row['answer'];
                    if ($row['other']=='Y') {
                        $this->_hardAnswers[$row['qid']][$row['scale_id']]['-oth-'] =  $this->_getQuestionAttribute($row['qid'], 'other_replace_text', $this->translate->_('Other'));
                    }
                }
            }
        }

        if (array_key_exists($qid, $this->_hardAnswers) && array_key_exists($scaleId, $this->_hardAnswers[$qid])) {
            return $this->_hardAnswers[$qid][$scaleId];
        }

        return false;
    }
217633
protected function use_question($questionid) {
        if (isset($this->recentlyusedquestions[$questionid])) {
            $this->recentlyusedquestions[$questionid] += 1;
        } else {
            $this->recentlyusedquestions[$questionid] = 1;
        }

        foreach ($this->availablequestionscache as $categorykey => $questionsforcategory) {
            foreach ($questionsforcategory as $numuses => $questionids) {
                if (!isset($questionids[$questionid])) {
                    continue;
                }
                unset($this->availablequestionscache[$categorykey][$numuses][$questionid]);
                if (empty($this->availablequestionscache[$categorykey][$numuses])) {
                    unset($this->availablequestionscache[$categorykey][$numuses]);
                }
            }
        }
    }
731053
protected function getFromFirstLevelCache($cacheId)
    {
        if (!empty(self::$firstLevelCache[$this->cacheName][$cacheId])) {
            return self::$firstLevelCache[$this->cacheName][$cacheId];
        }

        return null;
    }
368690
protected function getSurveyId($roundId)
    {
       $this->_ensureRounds();
       if (isset($this->_rounds[$roundId]['gro_id_survey'])) {
           return $this->_rounds[$roundId]['gro_id_survey'];
       }

       throw new \Gems_Exception_Coding("Requested non existing survey id for round $roundId.");
    }
635649
public function get($cacheId)
    {
        $firstLevelResult = $this->getFromFirstLevelCache($cacheId);
        if ($firstLevelResult !== null) {
            return $firstLevelResult;
        }

        return $this->secondLevelCache->get($cacheId);
    }
1280992
public static function restore_get_question_banks($restoreid, $contextlevel = null) {
        global $DB;

        $results = array();
        $qcats = $DB->get_recordset_sql("SELECT itemid, parentitemid AS contextid, info
                                         FROM {backup_ids_temp}
                                       WHERE backupid = ?
                                         AND itemname = 'question_category'", array($restoreid));
        foreach ($qcats as $qcat) {
            // If this qcat context haven't been acummulated yet, do that
            if (!isset($results[$qcat->contextid])) {
                $info = backup_controller_dbops::decode_backup_temp_info($qcat->info);
                // Filter by contextlevel if necessary
                if (is_null($contextlevel) || $contextlevel == $info->contextlevel) {
                    $results[$qcat->contextid] = $info->contextlevel;
                }
            }
        }
        $qcats->close();
        // Sort by value (contextlevel from CONTEXT_SYSTEM downto CONTEXT_MODULE)
        asort($results);
        return $results;
    }
564219
protected String getAnswers(Integer questionSeqId, List<? extends AnswerHeaderContract> answerHeaders) {

        String answer = null;
        String childAnswer = null;
        StringBuilder stringBuilder = new StringBuilder();
        if (answerHeaders != null && !answerHeaders.isEmpty()) {
            for (AnswerHeaderContract answerHeader : answerHeaders) {
                List<? extends AnswerContract> answerDetails = answerHeader.getAnswers();
                for (AnswerContract answers : answerDetails) {
                    if (questionSeqId.equals(getQuestionAnswerService().findQuestionById(answers.getQuestionId()).getQuestionSeqId())) {
                        answer = answers.getAnswer();
                        if (answer != null) {
                            if (!answer.equals(NOT_ANSWERED)) {
                                stringBuilder.append(answer);
                                stringBuilder.append(",");
                            }
                        }
                        childAnswer = stringBuilder.toString();
                    }
                }
            }
        }
        return childAnswer;
    }
946559
public function getSurveyStatistics($surveyId) {
        $seq   = new \MUtil_Html_Sequence();
        $seq->setGlue(\MUtil_Html::create('br'));
        $seq[] = $this->getNumberOfAnswers($surveyId);
        $seq[] = $this->calculateTrackUsage($surveyId);

        return $seq;
    }
315769
public function getPostQuestionAnswer($id, $sort = null)
    {
        $question = new Question($this->di->get("db"));
        $user     = new User($this->di->get("db"));

        if ($question->find("id", $id) == null) {
            return false;
        }
        $question = $question->getQuestion($id);


        // This is a bad practice and should be in the module, (fix this after kmom10 future)
        // getting actual user Objects for posts for reputation show in view.
        $question->question->userObj = $user->getUser($question->user);
        $question->userObj           = $user->getUser($question->user);

        $question->answers = array_map(function ($answer) {
            $user                = new User($this->di->get("db"));
            $answer->userObj     = $user->getUser($answer->user);
            $answer->vote->score = $answer->vote->score == null ? 0 : $answer->vote->score;
            return $answer;
        }, $question->answers);

        // Get query for up or down
        $order = isset($_GET["order"]) ? $_GET["order"] : "up";

        // Highest points
        if ($sort == "points") {
            usort($question->answers, function ($current, $next) {
                return $current->vote->score > $next->vote->score;
            });
        }

        // Accepted top
        if ($sort == "accepted") {
            usort($question->answers, function ($current, $next) {
                return $current->accepted == "yes" ? 1 : -1;
            });
        }


        // Highest votes
        if ($sort == "vote") {
            usort($question->answers, function ($current, $next) {
                return count($current->vote->likes) > count($next->vote->likes);
            });
        }

        // If up array_reverse, "down" is default from module
        if ($order == "up") {
            $question->answers = array_reverse($question->answers);
        }

        $form       = new CreateAnswerForm($this->di, $id);
        $form->check();

        $views = [
            ["comment/question/view/view-question", ["question" => $question], "question"],
            ["comment/question/view/view-answers",
            ["answers" => $question->answers, "questionId" => $question->question->questionId], "answer"],
            ["comment/question/view/post-answer", ["form" => $form->getHTML()], "form"],
            ["comment/question/view/wrappedField", ["question" => $question], "main"]
            ];
        $this->di->get("pageRenderComment")->renderPage([
            "views" => $views,
            "title" => "Fråga $question->id"
        ]);

        return false;
    }
1181982
private function pullQuestion($questionId, array $questions, array $decodedQuestions = [])
    {
        if (empty($decodedQuestions[$questionId])) {
            foreach ($questions as $index => $question) {
                if ($question->getId() === (int) $questionId && !empty($question->getMimeType())) {
                    $decodedQuestions[$questionId] = $this->itemSerializer->serialize($question, [Transfer::INCLUDE_SOLUTIONS]);
                    unset($questions[$index]);
                    break;
                }
            }
        }

        return !empty($decodedQuestions[$questionId]) ? $decodedQuestions[$questionId] : null;
    }
1023284
public function deserialize($data, Scale $scale)
    {
        $this->sipe('id', 'setUuid', $data, $scale);
        $this->sipe('name', 'setName', $data, $scale);

        if (isset($data['levels'])) {
            $scale->emptyLevels();

            foreach ($data['levels'] as $key => $levelData) {
                $level = $this->levelRepo->findOneBy(['uuid' => $levelData['id']]);

                if (!$level) {
                    $level = new Level();
                    $level->setUuid($levelData['id']);
                }
                $level->setScale($scale);
                $level->setName($levelData['value']);
                $level->setValue($key);
                $this->om->persist($level);
                $scale->addLevel($level);
            }
        }

        return $scale;
    }
867355
public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
        $contextlist = new \core_privacy\local\request\contextlist();

        // While we should not have an analysis without answers, it's safer to gather contexts by looking at both tables.
        $sql = "
            SELECT DISTINCT ctx.id
              FROM {survey} s
              JOIN {modules} m
                ON m.name = :survey
              JOIN {course_modules} cm
                ON cm.instance = s.id
               AND cm.module = m.id
              JOIN {context} ctx
                ON ctx.instanceid = cm.id
               AND ctx.contextlevel = :modulelevel
         LEFT JOIN {survey_answers} sa
                ON sa.survey = s.id
               AND sa.userid = :userid1
         LEFT JOIN {survey_analysis} sy
                ON sy.survey = s.id
               AND sy.userid = :userid2
             WHERE s.template <> 0
               AND (sa.id IS NOT NULL
                OR sy.id IS NOT NULL)";

        $contextlist->add_from_sql($sql, [
            'survey' => 'survey',
            'modulelevel' => CONTEXT_MODULE,
            'userid1' => $userid,
            'userid2' => $userid,
        ]);

        return $contextlist;
    }
1252874
public function hasAnswer($answerId)
    {
        foreach ($this->answers as $answer) {
            if ($answer->id == $answerId) {
                return true;
            }
        }
        return false;
    }
1256067
public function getQueuedPdf($appId, $scanId, $queueId, array $queryParams = [])
    {
        $response = $this->client->get($this->uri($appId, $scanId, 'pdfs') . '/queues/' . $queueId, [
            'query' => $queryParams,
        ]);

        return $this->handleResponse($response);
    }
1293233
private function _getPossibleAnswers($field)
    {
        $scaleId = isset($field['scale_id']) ? $field['scale_id'] : 0;
        $code    = $field['code'];

        if (isset($this->_answers[$code][$scaleId])) {
            return $this->_answers[$code][$scaleId];
        }
        
        $qid  = $field['qid'];

        // Get the real multioption
        $answers = $this->_getMultiOptions($field);
        if (!$answers) {
            // If not present, try to find ranges or a description
            switch ($field['type']) {
                case ':':
                    //Get the labels that could apply!
                    if ($this->_getQuestionAttribute($qid, 'multiflexible_checkbox')) {
                        $answers = $this->_getFixedAnswers($field['type']);
                        break;
                    }
                    $maxvalue  = $this->_getQuestionAttribute($qid, 'multiflexible_max', 10);
                    $minvalue  = $this->_getQuestionAttribute($qid, 'multiflexible_min', 1);
                    $stepvalue = $this->_getQuestionAttribute($qid, 'multiflexible_step', 1);
                    $answers   = range($minvalue, $maxvalue, $stepvalue);
                    $answers   = array_combine($answers, $answers);
                    break;
                case '5':
                case 'A':
                    $answers = range(1, 5);
                    $answers = array_combine($answers, $answers);
                    break;
                case 'B':
                    $answers = range(1, 10);
                    $answers = array_combine($answers, $answers);
                    break;
                case 'K':
                    $maxvalue  = $this->_getQuestionAttribute($qid, 'slider_max', 100);
                    $minvalue  = $this->_getQuestionAttribute($qid, 'slider_min', 0);
                    $stepvalue = $this->_getQuestionAttribute($qid, 'slider_accuracy', 1);
                    $answers   = range($minvalue, $maxvalue, $stepvalue);
                    $answers   = array_combine($answers, $answers);
                    break;                    
                case 'D':
                    $answers = $this->translate->_('Date');
                    break;
                case 'N':
                    $answers = $this->translate->_('Free number');
                    break;
                case 'X':
                    $answers = '';  // Boilerplate, this has no answer
                    break;
                case 'T':
                    $answers = $this->translate->_('Free text (long)');
                    break;
                case 'U':
                    $answers = $this->translate->_('Free text (very long)');
                    break;
                default:
                    $answers = $this->translate->_('Free text');
            }
        }
        $this->_answers[$code][$scaleId] = $answers;

        return $this->_answers[$code][$scaleId];
    }
236273
public static function get_scale_values($scaleid) {
        global $DB;
        $params = self::validate_parameters(self::get_scale_values_parameters(),
            array(
                'scaleid' => $scaleid,
            )
        );
        $context = context_system::instance();
        self::validate_context($context);
        // The following section is not learning plan specific and so has not been moved to the api.
        // Retrieve the scale value from the database.
        $scale = grade_scale::fetch(array('id' => $scaleid));
        $scalevalues = $scale->load_items();
        foreach ($scalevalues as $key => $value) {
            // Add a key (make the first value 1).
            $scalevalues[$key] = array(
                    'id' => $key + 1,
                    'name' => external_format_string($value, $context->id)
                );
        }
        return $scalevalues;
    }
1132301
public function deleteById(string $modelId)
    {
        $deleteResult = $this->getRequest()->request(
            'DELETE',
            $this->getRequestUrl(sprintf('models/%s', $modelId))
        );

        return $deleteResult['status'];
    }