Returns a summary of a quiz attempt before it is submitted.

@param int $attemptid attempt id
@param int $preflightdata preflight required data (like passwords)
@return array of warnings and the attempt summary data for each question
@since Moodle 3.1
772291
public static function get_attempt_summary($attemptid, $preflightdata = array()) {

        $warnings = array();

        $params = array(
            'attemptid' => $attemptid,
            'preflightdata' => $preflightdata,
        );
        $params = self::validate_parameters(self::get_attempt_summary_parameters(), $params);

        list($attemptobj, $messages) = self::validate_attempt($params, true, false);

        $result = array();
        $result['warnings'] = $warnings;
        $result['questions'] = self::get_attempt_questions_data($attemptobj, false, 'all');

        return $result;
    }
1314193
protected function step_no_for_try($questionusageid, $slot, $tryno) {
        $qa = $this->get_question_attempt($questionusageid, $slot);
        return $qa->get_steps_with_submitted_response_iterator()->step_no_for_try($tryno);
    }
945735
public function load_question_attempt_step($stepid) {
        $records = $this->db->get_recordset_sql("
SELECT
    quba.contextid,
    COALESCE(q.qtype, 'missingtype') AS qtype,
    qas.id AS attemptstepid,
    qas.questionattemptid,
    qas.sequencenumber,
    qas.state,
    qas.fraction,
    qas.timecreated,
    qas.userid,
    qasd.name,
    qasd.value

FROM      {question_attempt_steps}     qas
JOIN      {question_attempts}          qa   ON qa.id              = qas.questionattemptid
JOIN      {question_usages}            quba ON quba.id            = qa.questionusageid
LEFT JOIN {question}                   q    ON q.id               = qa.questionid
LEFT JOIN {question_attempt_step_data} qasd ON qasd.attemptstepid = qas.id

WHERE
    qas.id = :stepid
        ", array('stepid' => $stepid));

        if (!$records->valid()) {
            throw new coding_exception('Failed to load question_attempt_step ' . $stepid);
        }

        $step = question_attempt_step::load_from_records($records, $stepid);
        $records->close();

        return $step;
    }
429466
public static function get_questions_attempts_returns() {
        return new external_single_structure(
            array(
                'attempts' => new external_multiple_structure(
                    new external_single_structure(
                        array(
                            'id' => new external_value(PARAM_INT, 'The attempt id'),
                            'lessonid' => new external_value(PARAM_INT, 'The attempt lessonid'),
                            'pageid' => new external_value(PARAM_INT, 'The attempt pageid'),
                            'userid' => new external_value(PARAM_INT, 'The user who did the attempt'),
                            'answerid' => new external_value(PARAM_INT, 'The attempt answerid'),
                            'retry' => new external_value(PARAM_INT, 'The lesson attempt number'),
                            'correct' => new external_value(PARAM_INT, 'If it was the correct answer'),
                            'useranswer' => new external_value(PARAM_RAW, 'The complete user answer'),
                            'timeseen' => new external_value(PARAM_INT, 'The time the question was seen'),
                        ),
                        'The question page attempts'
                    )
                ),
                'warnings' => new external_warnings(),
            )
        );
    }
387532
protected function process_add_attempt_group($useridlist) {
        $groupsprocessed = array();
        $result = true;

        foreach ($useridlist as $userid) {
            $groupid = 0;
            $group = $this->get_submission_group($userid);
            if ($group) {
                $groupid = $group->id;
            }

            if (empty($groupsprocessed[$groupid])) {
                // We need to know what the most recent group submission is.
                // Specifically when determining if we are adding another attempt (we only want to add one attempt per team),
                // and when deciding if we need to update the gradebook with an edited grade.
                $currentsubmission = $this->get_group_submission($userid, 0, false, -1);
                $this->set_most_recent_team_submission($currentsubmission);
                $result = $this->process_add_attempt($userid) && $result;
                $groupsprocessed[$groupid] = true;
            }
        }
        return $result;
    }
545808
public function getRouteData($routeExternalId, $externalCoverageId)
    {
        // param depth '3' to get 'administrative_region' in response
        $response = $this->navitia_sam->getRoute($externalCoverageId, $routeExternalId, 3);
        if (!isset($response->routes) || empty($response->routes)) {
            throw new \Exception(
                $this->translator->trans(
                    'services.navitia.no_data_for_this_route',
                    array('%RouteId%' => $routeExternalId),
                    'exceptions'
                )
            );
        }

        return ($response->routes[0]);
    }
1022480
public function doRequest($apiName, array $data, $answerFormat = self::ANSWER_FORMAT_ARRAY, $try_number = 1, $resetTryNodes = true)
    {
        if ($resetTryNodes) {
            $this->resetTryNodes = count(static::$nodeURL);
        }
        $requestId = $this->getNextId();
        $requestData = [
            'jsonrpc' => '2.0',
            'id'      => $requestId,
            'method'  => 'call',
            'params'  => [
                $apiName,
                $data['method'],
                $data['params']
            ]
        ];
        try {
            $curlOptions = [];
            $curlOptions['CURLOPT_CONNECTTIMEOUT'] = $this->wsTimeoutSeconds;
            $answerRaw = $this->curlRequest(
                $this->getCurrentUrl(),
                'post',
                $requestData,
                $curlOptions
            );
            if ($answerRaw['code'] !== 200) {
                throw new \Exception("Curl answer code is '{$answerRaw['code']}' and response '{$answerRaw['response']}'");
            }
            $answer = json_decode($answerRaw['response'], self::ANSWER_FORMAT_ARRAY === $answerFormat);

            if (isset($answer['error'])) {
                throw new \Exception('got error in answer: ' . $answer['error']['code'] . ' ' . $answer['error']['message']);
            }
            //check that answer has the same id or id from previous tries, else it is answer from other request
            if (self::ANSWER_FORMAT_ARRAY === $answerFormat) {
                $answerId = $answer['id'];
            } else { //if (self::ANSWER_FORMAT_OBJECT === $answerFormat) {
                $answerId = $answer->id;
            }
            if ($requestId - $answerId > ($try_number - 1)) {
                throw new \Exception('got answer from old request');
            }


        } catch (\Exception $e) {
            if ($try_number < $this->maxNumberOfTriesToCallApi) {
                //if got WS Exception, try to get answer again
                $answer = $this->doRequest($apiName, $data, $answerFormat, $try_number + 1, false);
            } elseif ($this->resetTryNodes > 1) {
                $this->resetTryNodes = $this->resetTryNodes - 1;
                //if got WS Exception after few ties, connect to reserve node
                $this->setReserveNodeUrlToCurrentUrl();
                $answer = $this->doRequest($apiName, $data, $answerFormat, 1, false);
            } else {
                //if nothing helps
                throw $e;
            }
        }

        return $answer;
    }
739911
public static function get_attempt_access_information_returns() {
        return new external_single_structure(
            array(
                'endtime' => new external_value(PARAM_INT, 'When the attempt must be submitted (determined by rules).',
                                                VALUE_OPTIONAL),
                'isfinished' => new external_value(PARAM_BOOL, 'Whether there is no way the user will ever be allowed to attempt.'),
                'ispreflightcheckrequired' => new external_value(PARAM_BOOL, 'whether a check is required before the user
                                                                    starts/continues his attempt.', VALUE_OPTIONAL),
                'preventnewattemptreasons' => new external_multiple_structure(
                                                new external_value(PARAM_TEXT, 'access restriction description'),
                                                                    'list of reasons'),
                'warnings' => new external_warnings(),
            )
        );
    }
282210
public function get_last_page_seen($retriescount) {
        global $DB, $USER;

        $lastpageseen = false;
        $allattempts = $this->get_attempts($retriescount);
        if (!empty($allattempts)) {
            $attempt = end($allattempts);
            $attemptpage = $this->load_page($attempt->pageid);
            $jumpto = $DB->get_field('lesson_answers', 'jumpto', array('id' => $attempt->answerid));
            // Convert the jumpto to a proper page id.
            if ($jumpto == 0) {
                // Check if a question has been incorrectly answered AND no more attempts at it are left.
                $nattempts = $this->get_attempts($attempt->retry, false, $attempt->pageid, $USER->id);
                if (count($nattempts) >= $this->properties->maxattempts) {
                    $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
                } else {
                    $lastpageseen = $attempt->pageid;
                }
            } else if ($jumpto == LESSON_NEXTPAGE) {
                $lastpageseen = $this->get_next_page($attemptpage->nextpageid);
            } else if ($jumpto == LESSON_CLUSTERJUMP) {
                $lastpageseen = $this->cluster_jump($attempt->pageid);
            } else {
                $lastpageseen = $jumpto;
            }
        }

        if ($branchtables = $this->get_content_pages_viewed($retriescount, $USER->id, 'timeseen DESC')) {
            // In here, user has viewed a branch table.
            $lastbranchtable = current($branchtables);
            if (count($allattempts) > 0) {
                if ($lastbranchtable->timeseen > $attempt->timeseen) {
                    // This branch table was viewed more recently than the question page.
                    if (!empty($lastbranchtable->nextpageid)) {
                        $lastpageseen = $lastbranchtable->nextpageid;
                    } else {
                        // Next page ID did not exist prior to MDL-34006.
                        $lastpageseen = $lastbranchtable->pageid;
                    }
                }
            } else {
                // Has not answered any questions but has viewed a branch table.
                if (!empty($lastbranchtable->nextpageid)) {
                    $lastpageseen = $lastbranchtable->nextpageid;
                } else {
                    // Next page ID did not exist prior to MDL-34006.
                    $lastpageseen = $lastbranchtable->pageid;
                }
            }
        }
        return $lastpageseen;
    }
1254864
def _preflight_check(desired, fromrepo, **kwargs):
    '''
    
    '''
    if 'pkg.check_db' not in __salt__:
        return {}
    ret = {'suggest': {}, 'no_suggest': []}
    pkginfo = __salt__['pkg.check_db'](
        *list(desired.keys()), fromrepo=fromrepo, **kwargs
    )
    for pkgname in pkginfo:
        if pkginfo[pkgname]['found'] is False:
            if pkginfo[pkgname]['suggestions']:
                ret['suggest'][pkgname] = pkginfo[pkgname]['suggestions']
            else:
                ret['no_suggest'].append(pkgname)
    return ret
1342293
static function failedLoginAttemptsByUserID( $userID )
    {
        $db = eZDB::instance();
        $contentObjectID = (int) $userID;

        $userVisitArray = $db->arrayQuery( "SELECT failed_login_attempts FROM ezuservisit WHERE user_id=$contentObjectID" );

        $failedLoginAttempts = isset( $userVisitArray[0] ) ? $userVisitArray[0]['failed_login_attempts'] : 0;
        return $failedLoginAttempts;
    }
1022274
public static function execute_prechecks(restore_controller $controller, $droptemptablesafter = false) {
        global $CFG;

        $errors = array();
        $warnings = array();

        // Some handy vars to be used along the prechecks
        $samesite = $controller->is_samesite();
        $restoreusers = $controller->get_plan()->get_setting('users')->get_value();
        $hasmnetusers = (int)$controller->get_info()->mnet_remoteusers;
        $restoreid = $controller->get_restoreid();
        $courseid = $controller->get_courseid();
        $userid = $controller->get_userid();
        $rolemappings = $controller->get_info()->role_mappings;
        $progress = $controller->get_progress();

        // Start tracking progress. There are currently 8 major steps, corresponding
        // to $majorstep++ lines in this code; we keep track of the total so as to
        // verify that it's still correct. If you add a major step, you need to change
        // the total here.
        $majorstep = 1;
        $majorsteps = 8;
        $progress->start_progress('Carrying out pre-restore checks', $majorsteps);

        // Load all the included tasks to look for inforef.xml files
        $inforeffiles = array();
        $tasks = restore_dbops::get_included_tasks($restoreid);
        $progress->start_progress('Listing inforef files', count($tasks));
        $minorstep = 1;
        foreach ($tasks as $task) {
            // Add the inforef.xml file if exists
            $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
            if (file_exists($inforefpath)) {
                $inforeffiles[] = $inforefpath;
            }
            $progress->progress($minorstep++);
        }
        $progress->end_progress();
        $progress->progress($majorstep++);

        // Create temp tables
        restore_controller_dbops::create_restore_temp_tables($controller->get_restoreid());

        // Check we are restoring one backup >= $min20version (very first ok ever)
        $min20version = 2010072300;
        if ($controller->get_info()->backup_version < $min20version) {
            $message = new stdclass();
            $message->backup = $controller->get_info()->backup_version;
            $message->min    = $min20version;
            $errors[] = get_string('errorminbackup20version', 'backup', $message);
        }

        // Compare Moodle's versions
        if ($CFG->version < $controller->get_info()->moodle_version) {
            $message = new stdclass();
            $message->serverversion = $CFG->version;
            $message->serverrelease = $CFG->release;
            $message->backupversion = $controller->get_info()->moodle_version;
            $message->backuprelease = $controller->get_info()->moodle_release;
            $warnings[] = get_string('noticenewerbackup','',$message);
        }

        // The original_course_format var was introduced in Moodle 2.9.
        $originalcourseformat = null;
        if (!empty($controller->get_info()->original_course_format)) {
            $originalcourseformat = $controller->get_info()->original_course_format;
        }

        // We can't restore other course's backups on the front page.
        if ($controller->get_courseid() == SITEID &&
                $originalcourseformat != 'site' &&
                $controller->get_type() == backup::TYPE_1COURSE) {
            $errors[] = get_string('errorrestorefrontpagebackup', 'backup');
        }

        // We can't restore front pages over other courses.
        if ($controller->get_courseid() != SITEID &&
                $originalcourseformat == 'site' &&
                $controller->get_type() == backup::TYPE_1COURSE) {
            $errors[] = get_string('errorrestorefrontpagebackup', 'backup');
        }

        // If restoring to different site and restoring users and backup has mnet users warn/error
        if (!$samesite && $restoreusers && $hasmnetusers) {
            // User is admin (can create users at sysctx), warn
            if (has_capability('moodle/user:create', context_system::instance(), $controller->get_userid())) {
                $warnings[] = get_string('mnetrestore_extusers_admin', 'admin');
            // User not admin
            } else {
                $errors[] = get_string('mnetrestore_extusers_noadmin', 'admin');
            }
        }

        // Load all the inforef files, we are going to need them
        $progress->start_progress('Loading temporary IDs', count($inforeffiles));
        $minorstep = 1;
        foreach ($inforeffiles as $inforeffile) {
            // Load each inforef file to temp_ids.
            restore_dbops::load_inforef_to_tempids($restoreid, $inforeffile, $progress);
            $progress->progress($minorstep++);
        }
        $progress->end_progress();
        $progress->progress($majorstep++);

        // If restoring users, check we are able to create all them
        if ($restoreusers) {
            $file = $controller->get_plan()->get_basepath() . '/users.xml';
             // Load needed users to temp_ids.
            restore_dbops::load_users_to_tempids($restoreid, $file, $progress);
            $progress->progress($majorstep++);
            if ($problems = restore_dbops::precheck_included_users($restoreid, $courseid, $userid, $samesite, $progress)) {
                $errors = array_merge($errors, $problems);
            }
        } else {
            // To ensure consistent number of steps in progress tracking,
            // mark progress even though we didn't do anything.
            $progress->progress($majorstep++);
        }
        $progress->progress($majorstep++);

        // Note: restore won't create roles at all. Only mapping/skip!
        $file = $controller->get_plan()->get_basepath() . '/roles.xml';
        restore_dbops::load_roles_to_tempids($restoreid, $file); // Load needed roles to temp_ids
        if ($problems = restore_dbops::precheck_included_roles($restoreid, $courseid, $userid, $samesite, $rolemappings)) {
            $errors = array_key_exists('errors', $problems) ? array_merge($errors, $problems['errors']) : $errors;
            $warnings = array_key_exists('warnings', $problems) ? array_merge($warnings, $problems['warnings']) : $warnings;
        }
        $progress->progress($majorstep++);

        // Check we are able to restore and the categories and questions
        $file = $controller->get_plan()->get_basepath() . '/questions.xml';
        restore_dbops::load_categories_and_questions_to_tempids($restoreid, $file);
        if ($problems = restore_dbops::precheck_categories_and_questions($restoreid, $courseid, $userid, $samesite)) {
            $errors = array_key_exists('errors', $problems) ? array_merge($errors, $problems['errors']) : $errors;
            $warnings = array_key_exists('warnings', $problems) ? array_merge($warnings, $problems['warnings']) : $warnings;
        }
        $progress->progress($majorstep++);

        // Prepare results.
        $results = array();
        if (!empty($errors)) {
            $results['errors'] = $errors;
        }
        if (!empty($warnings)) {
            $results['warnings'] = $warnings;
        }
        // Warnings/errors detected or want to do so explicitly, drop temp tables
        if (!empty($results) || $droptemptablesafter) {
            restore_controller_dbops::drop_restore_temp_tables($controller->get_restoreid());
        }

        // Finish progress and check we got the initial number of steps right.
        $progress->progress($majorstep++);
        if ($majorstep != $majorsteps) {
            throw new coding_exception('Progress step count wrong: ' . $majorstep);
        }
        $progress->end_progress();

        return $results;
    }
813164
public function loginUser(array $userData)
    {
        // Login has failed with this email/password.
        if (! auth()->attempt($userData, request('remember', false))) {
            return $this->handleInvalidCredentials();
        }

        // Check if the user is inactive.
        if (auth()->user()->status_id === Status::INACTIVE) {
            return $this->handleInactiveUser();
        }

        // Check if the user has been blocked.
        if (auth()->user()->status_id === Status::BLOCKED) {
            return $this->handleBlockedUsers();
        }

        // User has passed all checks and can be redirected to the site.
        return $this->handleSuccessfulLogin();
    }
120979
public function make_question($questiondata) {
        $question = $this->make_question_instance($questiondata);
        $this->initialise_question_instance($question, $questiondata);
        return $question;
    }
1362196
protected function restore_question_attempt_worker($data, $nameprefix) {
        global $DB;

        $data = (object)$data;
        $oldid = $data->id;
        $question = $this->get_mapping('question', $data->questionid);

        $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
        $data->questionid      = $question->newitemid;
        if (!property_exists($data, 'variant')) {
            $data->variant = 1;
        }

        if (!property_exists($data, 'maxfraction')) {
            $data->maxfraction = 1;
        }

        $newitemid = $DB->insert_record('question_attempts', $data);

        $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
        $this->qtypes[$newitemid] = $question->info->qtype;
        $this->newquestionids[$newitemid] = $data->questionid;
    }
226170
public function finish_review_link(quiz_attempt $attemptobj) {
        $url = $attemptobj->view_url();

        if ($attemptobj->get_access_manager(time())->attempt_must_be_in_popup()) {
            $this->page->requires->js_init_call('M.mod_quiz.secure_window.init_close_button',
                    array($url), false, quiz_get_js_module());
            return html_writer::empty_tag('input', array('type' => 'button',
                    'value' => get_string('finishreview', 'quiz'),
                    'id' => 'secureclosebutton',
                    'class' => 'mod_quiz-next-nav btn btn-primary'));

        } else {
            return html_writer::link($url, get_string('finishreview', 'quiz'),
                    array('class' => 'mod_quiz-next-nav'));
        }
    }
74438
public function getRequestData($sent = true)
    {
        if(!($this instanceof EntityInterface)){
            throw new \Exception(sprintf(
                '%s can only be used if the class implements %s',
                __TRAIT__,
                EntityInterface::class
            ));
        }

        if($sent && ($request = $this->getRequest())){
            $query = [];
            parse_str($request->getUri()->getQuery(), $query);
            return $query;
        }

        // Trigger a pre-getRequestData() hook for any last minute
        // decision making that needs to be done, but only if
        // it hasn't been sent already
        if (method_exists($this, 'preGetRequestDataHook')) {
            $this->preGetRequestDataHook();
        }

        return $this->requestData;
    }