This is executed every time we have one /MOODLE_BACKUP/COURSE/MODULES/MOD/LESSON/PAGES/PAGE/ANSWERS/ANSWER
data available
968575
public function process_lesson_answer($data) {

        // replay the upgrade step 2010072003
        $flags = intval($data['flags']);
        if ($flags & 1) {
            $data['answer_text']  = text_to_html($data['answer_text'], false, false, true);
            $data['answerformat'] = FORMAT_HTML;
        }
        if ($flags & 2) {
            $data['response']       = text_to_html($data['response'], false, false, true);
            $data['responseformat'] = FORMAT_HTML;
        }

        // buffer for conversion of <jumpto> in line with
        // upgrade step 2010121400 from mod/lesson/db/upgrade.php
        $this->answers[] = $data;
    }
289935
public function process_page_responses(lesson_page $page) {
        $context = $this->get_context();

        // Check the page has answers [MDL-25632].
        if (count($page->answers) > 0) {
            $result = $page->record_attempt($context);
        } else {
            // The page has no answers so we will just progress to the next page in the
            // sequence (as set by newpageid).
            $result = new stdClass;
            $result->newpageid       = optional_param('newpageid', $page->nextpageid, PARAM_INT);
            $result->nodefaultresponse  = true;
            $result->inmediatejump = false;
        }

        if ($result->inmediatejump) {
            return $result;
        }

        $result->newpageid = $this->calculate_new_page_on_jump($page, $result->newpageid);

        return $result;
    }
1147630
public function process_lesson_page($data) {
        global $CFG;

        // replay the upgrade step 2009120801
        if ($CFG->texteditors !== 'textarea') {
            $data['contents'] = text_to_html($data['contents'], false, false, true);
            $data['contentsformat'] = FORMAT_HTML;
        }

        // store page in pages
        $this->page = new stdClass();
        $this->page->id = $data['pageid'];
        unset($data['pageid']);
        $this->page->data = $data;
    }
1353572
public function execute() {
        global $DB, $CFG;
        if (!empty($CFG->enablebadges)) {
            require_once($CFG->libdir . '/badgeslib.php');
            $total = 0;

            $courseparams = array();
            if (empty($CFG->badges_allowcoursebadges)) {
                $coursesql = '';
            } else {
                $coursesql = ' OR EXISTS (SELECT c.id FROM {course} c WHERE c.visible = :visible AND c.startdate < :current'
                        . '     AND c.id = b.courseid) ';
                $courseparams = array('visible' => true, 'current' => time());
            }

            $sql = 'SELECT b.id
                      FROM {badge} b
                     WHERE (b.status = :active OR b.status = :activelocked)
                       AND (b.type = :site ' . $coursesql . ')';
            $badgeparams = [
                'active' => BADGE_STATUS_ACTIVE,
                'activelocked' => BADGE_STATUS_ACTIVE_LOCKED,
                'site' => BADGE_TYPE_SITE
            ];
            $params = array_merge($badgeparams, $courseparams);
            $badges = $DB->get_fieldset_sql($sql, $params);

            mtrace('Started reviewing available badges.');
            foreach ($badges as $bid) {
                $badge = new \badge($bid);

                if ($badge->has_criteria()) {
                    if (debugging()) {
                        mtrace('Processing badge "' . $badge->name . '"...');
                    }

                    $issued = $badge->review_all_criteria();

                    if (debugging()) {
                        mtrace('...badge was issued to ' . $issued . ' users.');
                    }
                    $total += $issued;
                }
            }

            mtrace('Badges were issued ' . $total . ' time(s).');
        }
    }
1255132
function startModulesAfterPageLoad( lo ) {
  // header hooks
  if ( ( lo != null ) && ( lo.header != null ) && ( lo.header.modules != null ) ) {
    for ( var i = 0; i < lo.header.modules.length; i++ ) {
      startModuleAfterPageLoad( lo.header.modules[i] );
    }
  }
  // footer hooks
  if ( ( lo != null ) && ( lo.footer != null ) && ( lo.footer.modules != null ) ) {
    for ( var i = 0; i < lo.footer.modules.length; i++ ) {
      startModuleAfterPageLoad( lo.footer.modules[i] );
    }
  }
  ajaxOngoing--;
}
1238652
public function execute() {
        global $CFG, $DB;

        if ($CFG->enablecompletion) {
            require_once($CFG->libdir . "/completionlib.php");

            if (debugging()) {
                mtrace('Marking users as started');
            }

            // This causes it to default to everyone (if there is no student role).
            $sqlroles = '';
            if (!empty($CFG->gradebookroles)) {
                $sqlroles = ' AND ra.roleid IN (' . $CFG->gradebookroles.')';
            }

            // It's purpose is to locate all the active participants of a course with course completion enabled.
            // We also only want the users with no course_completions record as this functions job is to create
            // the missing ones :)
            // We want to record the user's enrolment start time for the course. This gets tricky because there can be
            // multiple enrolment plugins active in a course, hence the possibility of multiple records for each
            // couse/user in the results.
            $sql = "SELECT c.id AS course, u.id AS userid, crc.id AS completionid, ue.timestart AS timeenrolled,
                           ue.timecreated
                      FROM {user} u
                INNER JOIN {user_enrolments} ue ON ue.userid = u.id
                INNER JOIN {enrol} e ON e.id = ue.enrolid
                INNER JOIN {course} c ON c.id = e.courseid
                INNER JOIN {role_assignments} ra ON ra.userid = u.id
                 LEFT JOIN {course_completions} crc ON crc.course = c.id AND crc.userid = u.id
                     WHERE c.enablecompletion = 1
                       AND crc.timeenrolled IS NULL
                       AND ue.status = 0
                       AND e.status = 0
                       AND u.deleted = 0
                       AND ue.timestart < ?
                       AND (ue.timeend > ? OR ue.timeend = 0)
                       $sqlroles
                  ORDER BY course, userid";
            $now = time();
            $rs = $DB->get_recordset_sql($sql, [$now, $now, $now, $now]);

            // Check if result is empty.
            if (!$rs->valid()) {
                // Not going to iterate (but exit), close rs.
                $rs->close();
                return;
            }

            // We are essentially doing a group by in the code here (as I can't find a decent way of doing it
            // in the sql). Since there can be multiple enrolment plugins for each course, we can have multiple rows
            // for each participant in the query result. This isn't really a problem until you combine it with the fact
            // that the enrolment plugins can save the enrol start time in either timestart or timeenrolled.
            // The purpose of the loop is to find the earliest enrolment start time for each participant in each course.
            $prev = null;
            while ($rs->valid() || $prev) {
                $current = $rs->current();
                if (!isset($current->course)) {
                    $current = false;
                } else {
                    // Not all enrol plugins fill out timestart correctly, so use whichever is non-zero.
                    $current->timeenrolled = max($current->timecreated, $current->timeenrolled);
                }

                // If we are at the last record, or we aren't at the first and the record is for a diff user/course.
                if ($prev && (!$rs->valid() ||
                        ($current->course != $prev->course || $current->userid != $prev->userid))) {

                    $completion = new \completion_completion();
                    $completion->userid = $prev->userid;
                    $completion->course = $prev->course;
                    $completion->timeenrolled = (string) $prev->timeenrolled;
                    $completion->timestarted = 0;
                    $completion->reaggregate = time();
                    if ($prev->completionid) {
                        $completion->id = $prev->completionid;
                    }
                    $completion->mark_enrolled();

                    if (debugging()) {
                        mtrace('Marked started user ' . $prev->userid . ' in course ' . $prev->course);
                    }
                } else if ($prev && $current) {
                    // Else, if this record is for the same user/course use oldest timeenrolled.
                    $current->timeenrolled = min($current->timeenrolled, $prev->timeenrolled);
                }
                // Move current record to previous.
                $prev = $current;
                // Move to next record.
                $rs->next();
            }
            $rs->close();
        }
    }
1304470
public function execute() {
        global $CFG;

        require_once($CFG->dirroot . '/mod/assign/locallib.php');
        \assign::cron();

        $plugins = \core_component::get_plugin_list('assignsubmission');

        foreach ($plugins as $name => $plugin) {
            $disabled = get_config('assignsubmission_' . $name, 'disabled');
            if (!$disabled) {
                $class = 'assign_submission_' . $name;
                require_once($CFG->dirroot . '/mod/assign/submission/' . $name . '/locallib.php');
                $class::cron();
            }
        }
        $plugins = \core_component::get_plugin_list('assignfeedback');

        foreach ($plugins as $name => $plugin) {
            $disabled = get_config('assignfeedback_' . $name, 'disabled');
            if (!$disabled) {
                $class = 'assign_feedback_' . $name;
                require_once($CFG->dirroot . '/mod/assign/feedback/' . $name . '/locallib.php');
                $class::cron();
            }
        }

        return true;
    }
246855
function () /*:Void*/ {

        if (!this._initialized) {

            /**
             * Fires when loading a test page
             * @event testpagebegin
             * @param curPage {string} the page being loaded
             * @static
             */

            /**
             * Fires when a test page is complete
             * @event testpagecomplete
             * @param obj {page: string, results: object} the name of the
             * page that was loaded, and the test suite results
             * @static
             */

            /**
             * Fires when the test manager starts running all test pages
             * @event testmanagerbegin
             * @static
             */

            /**
             * Fires when the test manager finishes running all test pages.  External
             * test runners should subscribe to this event in order to get the
             * aggregated test results.
             * @event testmanagercomplete
             * @param obj { pages_passed: int, pages_failed: int, tests_passed: int
             *              tests_failed: int, passed: string[], failed: string[],
             *              page_results: {} }
             * @static
             */

            //create iframe if not already available
            if (!this._frame){
                var frame /*:HTMLElement*/ = document.createElement("iframe");
                frame.style.visibility = "hidden";
                frame.style.position = "absolute";
                document.body.appendChild(frame);
                this._frame = frame.contentWindow || frame.contentDocument.parentWindow;
            }

            this._initialized = true;
        }


        // reset the results cache
        this._results = {

            passed: 0,
            failed: 0,
            ignored: 0,
            total: 0,
            type: "report",
            name: "YUI Test Results",
            duration: 0,
            failedPages:[],
            passedPages:[]
            /*
            // number of pages that pass
            pages_passed: 0,
            // number of pages that fail
            pages_failed: 0,
            // total number of tests passed
            tests_passed: 0,
            // total number of tests failed
            tests_failed: 0,
            // array of pages that passed
            passed: [],
            // array of pages that failed
            failed: [],
            // map of full results for each page
            page_results: {}*/
        };

        this.fire(this.TEST_MANAGER_BEGIN_EVENT, null);
        this._run();

    }
986860
public function initialise() {
        global $PAGE, $USER, $OUTPUT, $CFG;
        if (during_initial_install()) {
            return;
        }

        $current = false;

        $course = $PAGE->course;

        $this->page->navigation->initialise();

        // First walk the nav tree looking for "flat_navigation" nodes.
        if ($course->id > 1) {
            // It's a real course.
            $url = new moodle_url('/course/view.php', array('id' => $course->id));

            $coursecontext = context_course::instance($course->id, MUST_EXIST);
            // This is the name that will be shown for the course.
            $coursename = empty($CFG->navshowfullcoursenames) ?
                format_string($course->shortname, true, array('context' => $coursecontext)) :
                format_string($course->fullname, true, array('context' => $coursecontext));

            $flat = new flat_navigation_node(navigation_node::create($coursename, $url), 0);
            $flat->set_collectionlabel($coursename);
            $flat->key = 'coursehome';
            $flat->icon = new pix_icon('i/course', '');

            $courseformat = course_get_format($course);
            $coursenode = $PAGE->navigation->find_active_node();
            $targettype = navigation_node::TYPE_COURSE;

            // Single activity format has no course node - the course node is swapped for the activity node.
            if (!$courseformat->has_view_page()) {
                $targettype = navigation_node::TYPE_ACTIVITY;
            }

            while (!empty($coursenode) && ($coursenode->type != $targettype)) {
                $coursenode = $coursenode->parent;
            }
            // There is one very strange page in mod/feedback/view.php which thinks it is both site and course
            // context at the same time. That page is broken but we need to handle it (hence the SITEID).
            if ($coursenode && $coursenode->key != SITEID) {
                $this->add($flat);
                foreach ($coursenode->children as $child) {
                    if ($child->action) {
                        $flat = new flat_navigation_node($child, 0);
                        $this->add($flat);
                    }
                }
            }

            $this->page->navigation->build_flat_navigation_list($this, true, get_string('site'));
        } else {
            $this->page->navigation->build_flat_navigation_list($this, false, get_string('site'));
        }

        $admin = $PAGE->settingsnav->find('siteadministration', navigation_node::TYPE_SITE_ADMIN);
        if (!$admin) {
            // Try again - crazy nav tree!
            $admin = $PAGE->settingsnav->find('root', navigation_node::TYPE_SITE_ADMIN);
        }
        if ($admin) {
            $flat = new flat_navigation_node($admin, 0);
            $flat->set_showdivider(true, get_string('sitesettings'));
            $flat->key = 'sitesettings';
            $flat->icon = new pix_icon('t/preferences', '');
            $this->add($flat);
        }

        // Add-a-block in editing mode.
        if (isset($this->page->theme->addblockposition) &&
                $this->page->theme->addblockposition == BLOCK_ADDBLOCK_POSITION_FLATNAV &&
                $PAGE->user_is_editing() && $PAGE->user_can_edit_blocks() &&
                ($addable = $PAGE->blocks->get_addable_blocks())) {
            $url = new moodle_url($PAGE->url, ['bui_addblock' => '', 'sesskey' => sesskey()]);
            $addablock = navigation_node::create(get_string('addblock'), $url);
            $flat = new flat_navigation_node($addablock, 0);
            $flat->set_showdivider(true, get_string('blocksaddedit'));
            $flat->key = 'addblock';
            $flat->icon = new pix_icon('i/addblock', '');
            $this->add($flat);
            $blocks = [];
            foreach ($addable as $block) {
                $blocks[] = $block->name;
            }
            $params = array('blocks' => $blocks, 'url' => '?' . $url->get_query_string(false));
            $PAGE->requires->js_call_amd('core/addblockmodal', 'init', array($params));
        }
    }
1067337
public function process_quiz($data) {
        global $CFG;

        // Replay the upgrade step 2008081501.
        if (is_null($data['sumgrades'])) {
            $data['sumgrades'] = 0;
            // TODO for user data: quiz_attempts SET sumgrades=0 WHERE sumgrades IS NULL.
            // TODO for user data: quiz_grades.grade should be not be null , convert to default 0.
        }

        // Replay the upgrade step 2009042000.
        if ($CFG->texteditors !== 'textarea') {
            $data['intro']       = text_to_html($data['intro'], false, false, true);
            $data['introformat'] = FORMAT_HTML;
        }

        // Replay the upgrade step 2009031001.
        $data['timelimit'] *= 60;

        // Get the course module id and context id.
        $instanceid     = $data['id'];
        $cminfo         = $this->get_cminfo($instanceid);
        $this->moduleid = $cminfo['id'];
        $contextid      = $this->converter->get_contextid(CONTEXT_MODULE, $this->moduleid);

        // Get a fresh new file manager for this instance.
        $this->fileman = $this->converter->get_file_manager($contextid, 'mod_quiz');

        // Convert course files embedded into the intro.
        $this->fileman->filearea = 'intro';
        $this->fileman->itemid   = 0;
        $data['intro'] = moodle1_converter::migrate_referenced_files(
                $data['intro'], $this->fileman);

        // Start writing quiz.xml.
        $this->open_xml_writer("activities/quiz_{$this->moduleid}/quiz.xml");
        $this->xmlwriter->begin_tag('activity', array('id' => $instanceid,
                'moduleid' => $this->moduleid, 'modulename' => 'quiz',
                'contextid' => $contextid));
        $this->xmlwriter->begin_tag('quiz', array('id' => $instanceid));

        foreach ($data as $field => $value) {
            if ($field <> 'id') {
                $this->xmlwriter->full_tag($field, $value);
            }
        }

        return $data;
    }
773821
public function display() {
        global $PAGE, $COURSE;

        $this->require_definition_after_data();

        $config = new stdClass;
        if ($this->uistage->get_ui() instanceof import_ui) {
            $config->title = get_string('confirmcancelimport', 'backup');
        } else if ($this->uistage->get_ui() instanceof restore_ui) {
            $config->title = get_string('confirmcancelrestore', 'backup');
        } else {
            $config->title = get_string('confirmcancel', 'backup');
        }
        $config->question = get_string('confirmcancelquestion', 'backup');
        $config->yesLabel = $config->title;
        $config->noLabel = get_string('confirmcancelno', 'backup');
        $config->closeButtonTitle = get_string('close', 'editor');
        $PAGE->requires->yui_module(
            'moodle-backup-confirmcancel',
            'M.core_backup.confirmcancel.watch_cancel_buttons',
            array($config)
        );

        // Get list of module types on course.
        $modinfo = get_fast_modinfo($COURSE);
        $modnames = $modinfo->get_used_module_names(true);
        $PAGE->requires->yui_module('moodle-backup-backupselectall', 'M.core_backup.backupselectall',
                array($modnames));
        $PAGE->requires->strings_for_js(array('select', 'all', 'none'), 'moodle');
        $PAGE->requires->strings_for_js(array('showtypes', 'hidetypes'), 'backup');

        parent::display();
    }
1126913
public static function rewrite_answers_urls($answer, $rewriteanswer = true) {
        global $PAGE;

        $context = context_module::instance($PAGE->cm->id);
        if ($rewriteanswer) {
            $answer->answer = file_rewrite_pluginfile_urls($answer->answer, 'pluginfile.php', $context->id,
                    'mod_lesson', 'page_answers', $answer->id);
        }
        $answer->response = file_rewrite_pluginfile_urls($answer->response, 'pluginfile.php', $context->id,
                'mod_lesson', 'page_responses', $answer->id);

        return $answer;
    }
1065686
protected function execute_condition() {
        global $CFG, $DB;

        if ($this->get_courseid() == SITEID) {
            return false;
        }

        // No gradebook info found, don't execute
        $fullpath = $this->task->get_taskbasepath();
        $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
        if (!file_exists($fullpath)) {
            return false;
        }

        // Some module present in backup file isn't available to restore
        // in this site, don't execute
        if ($this->task->is_missing_modules()) {
            return false;
        }

        // Some activity has been excluded to be restored, don't execute
        if ($this->task->is_excluding_activities()) {
            return false;
        }

        // There should only be one grade category (the 1 associated with the course itself)
        // If other categories already exist we're restoring into an existing course.
        // Restoring categories into a course with an existing category structure is unlikely to go well
        $category = new stdclass();
        $category->courseid  = $this->get_courseid();
        $catcount = $DB->count_records('grade_categories', (array)$category);
        if ($catcount>1) {
            return false;
        }

        // Identify the backup we're dealing with.
        $backuprelease = floatval($this->get_task()->get_info()->backup_release); // The major version: 2.9, 3.0, ...
        $backupbuild = 0;
        preg_match('/(\d{8})/', $this->get_task()->get_info()->moodle_release, $matches);
        if (!empty($matches[1])) {
            $backupbuild = (int) $matches[1]; // The date of Moodle build at the time of the backup.
        }

        // On older versions the freeze value has to be converted.
        // We do this from here as it is happening right before the file is read.
        // This only targets the backup files that can contain the legacy freeze.
        if ($backupbuild > 20150618 && ($backuprelease < 3.0 || $backupbuild < 20160527)) {
            $this->rewrite_step_backup_file_for_legacy_freeze($fullpath);
        }

        // Arrived here, execute the step
        return true;
     }
854557
def update
      @page = Page.find(params[:id])
      questions = @presenter.all_questions_for_page(params[:id])
      questions.post(params[:answers], @answer_sheet)
      
      questions.save
      
      @elements = questions.elements
      
      # Save references
      if params[:reference].present?
        params[:reference].each do |id, values|
          ref = @answer_sheet.reference_sheets.find(id)
          # if the email address has changed, we have to trash the old reference answers
          ref.attributes = values
          ref.save(:validate => false)
        end
      end
      @presenter.active_page = nil
      @answer_sheet.touch
      respond_to do |format|
        format.js
        #format.html
      end
    end
848027
public function delete() {
        global $CFG, $DB;
        require_once($CFG->libdir.'/gradelib.php');
        require_once($CFG->dirroot.'/calendar/lib.php');

        $cm = get_coursemodule_from_instance('lesson', $this->properties->id, $this->properties->course);
        $context = context_module::instance($cm->id);

        $this->delete_all_overrides();

        grade_update('mod/lesson', $this->properties->course, 'mod', 'lesson', $this->properties->id, 0, null, array('deleted'=>1));

        // We must delete the module record after we delete the grade item.
        $DB->delete_records("lesson", array("id"=>$this->properties->id));
        $DB->delete_records("lesson_pages", array("lessonid"=>$this->properties->id));
        $DB->delete_records("lesson_answers", array("lessonid"=>$this->properties->id));
        $DB->delete_records("lesson_attempts", array("lessonid"=>$this->properties->id));
        $DB->delete_records("lesson_grades", array("lessonid"=>$this->properties->id));
        $DB->delete_records("lesson_timer", array("lessonid"=>$this->properties->id));
        $DB->delete_records("lesson_branch", array("lessonid"=>$this->properties->id));
        if ($events = $DB->get_records('event', array("modulename"=>'lesson', "instance"=>$this->properties->id))) {
            $coursecontext = context_course::instance($cm->course);
            foreach($events as $event) {
                $event->context = $coursecontext;
                $event = calendar_event::load($event);
                $event->delete();
            }
        }

        // Delete files associated with this module.
        $fs = get_file_storage();
        $fs->delete_area_files($context->id);

        return true;
    }
769292
public function execute() {
        global $CFG, $DB;

        $now = time();

        mtrace(' processing workshop subplugins ...');

        // Now when the scheduled allocator had a chance to do its job.
        // Check if there are some workshops to switch into the assessment phase.
        $workshops = $DB->get_records_select("workshop",
            "phase = 20 AND phaseswitchassessment = 1 AND submissionend > 0 AND submissionend < ?", [$now]);

        if (!empty($workshops)) {
            mtrace('Processing automatic assessment phase switch in ' . count($workshops) . ' workshop(s) ... ', '');
            require_once($CFG->dirroot . '/mod/workshop/locallib.php');
            foreach ($workshops as $workshop) {
                $cm = get_coursemodule_from_instance('workshop', $workshop->id, $workshop->course, false, MUST_EXIST);
                $course = $DB->get_record('course', ['id' => $cm->course], '*', MUST_EXIST);
                $workshop = new \workshop($workshop, $cm, $course);
                $workshop->switch_phase(workshop::PHASE_ASSESSMENT);

                $params = [
                    'objectid' => $workshop->id,
                    'context' => $workshop->context,
                    'courseid' => $workshop->course->id,
                    'other' => [
                        'workshopphase' => $workshop->phase
                    ]
                ];
                $event = \mod_workshop\event\phase_switched::create($params);
                $event->trigger();

                // Disable the automatic switching now so that it is not executed again by accident.
                // That can happen if the teacher changes the phase back to the submission one.
                $DB->set_field('workshop', 'phaseswitchassessment', 0, ['id' => $workshop->id]);
            }
            mtrace('done');
        }
    }
1128943
function reuse() {
      if(!storage[storageKey] && post.collection('parent') && post.collection('parent')[storageKey]){
        $contentDomNode.html(post.collection('parent')[storageKey]);
        $contentDomNode.attr('data-div-placeholder-content', 'true');
        saveData();
      }
    }