Launches a automated backup routine for the given course

@param stdClass $course
@param int $starttime
@param int $userid
@return bool
1453
public static function launch_automated_backup($course, $starttime, $userid) {

        $outcome = self::BACKUP_STATUS_OK;
        $config = get_config('backup');
        $dir = $config->backup_auto_destination;
        $storage = (int)$config->backup_auto_storage;

        $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO,
                backup::MODE_AUTOMATED, $userid);

        try {

            // Set the default filename.
            $format = $bc->get_format();
            $type = $bc->get_type();
            $id = $bc->get_id();
            $users = $bc->get_plan()->get_setting('users')->get_value();
            $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
            $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type,
                    $id, $users, $anonymised));

            $bc->set_status(backup::STATUS_AWAITING);

            $bc->execute_plan();
            $results = $bc->get_results();
            $outcome = self::outcome_from_results($results);
            $file = $results['backup_destination']; // May be empty if file already moved to target location.

            // If we need to copy the backup file to an external dir and it is not writable, change status to error.
            // This is a feature to prevent moodledata to be filled up and break a site when the admin misconfigured
            // the automated backups storage type and destination directory.
            if ($storage !== 0 && (empty($dir) || !file_exists($dir) || !is_dir($dir) || !is_writable($dir))) {
                $bc->log('Specified backup directory is not writable - ', backup::LOG_ERROR, $dir);
                $dir = null;
                $outcome = self::BACKUP_STATUS_ERROR;
            }

            // Copy file only if there was no error.
            if ($file && !empty($dir) && $storage !== 0 && $outcome != self::BACKUP_STATUS_ERROR) {
                $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised,
                        !$config->backup_shortname);
                if (!$file->copy_content_to($dir.'/'.$filename)) {
                    $bc->log('Attempt to copy backup file to the specified directory failed - ',
                            backup::LOG_ERROR, $dir);
                    $outcome = self::BACKUP_STATUS_ERROR;
                }
                if ($outcome != self::BACKUP_STATUS_ERROR && $storage === 1) {
                    if (!$file->delete()) {
                        $outcome = self::BACKUP_STATUS_WARNING;
                        $bc->log('Attempt to delete the backup file from course automated backup area failed - ',
                                backup::LOG_WARNING, $file->get_filename());
                    }
                }
            }

        } catch (moodle_exception $e) {
            $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
            $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
            $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
            $outcome = self::BACKUP_STATUS_ERROR;
        }

        // Delete the backup file immediately if something went wrong.
        if ($outcome === self::BACKUP_STATUS_ERROR) {

            // Delete the file from file area if exists.
            if (!empty($file)) {
                $file->delete();
            }

            // Delete file from external storage if exists.
            if ($storage !== 0 && !empty($filename) && file_exists($dir.'/'.$filename)) {
                @unlink($dir.'/'.$filename);
            }
        }

        $bc->destroy();
        unset($bc);

        return $outcome;
    }
971106
public static function create_from_ids($userfromid, $usertoid, $notificationid, $courseid) {
        // We may be sending a notification from the 'noreply' address, which means we are not actually sending a
        // notification from a valid user. In this case, we will set the userid to 0.
        // Check if the userid is valid.
        if (!\core_user::is_real_user($userfromid)) {
            $userfromid = 0;
        }

        // If the courseid is null, then set it to the site id.
        if (is_null($courseid)) {
            $courseid = SITEID;
        }

        $event = self::create(
            [
                'objectid' => $notificationid,
                'userid' => $userfromid,
                'context' => \context_system::instance(),
                'relateduserid' => $usertoid,
                'other' => [
                    'courseid' => $courseid
                ]
            ]
        );

        return $event;
    }
1198394
public static function get_users_in_context(userlist $userlist) {
        $context = $userlist->get_context();

        if ($context instanceof \context_course) {
            $params = ['courseid' => $context->instanceid];

            $sql = "SELECT bc.userid
                      FROM {backup_controllers} bc
                     WHERE bc.itemid = :courseid
                           AND bc.type = :typecourse";

            $courseparams = ['typecourse' => 'course'] + $params;

            $userlist->add_from_sql('userid', $sql, $courseparams);

            $sql = "SELECT bc.userid
                      FROM {backup_controllers} bc
                      JOIN {course_sections} c
                           ON bc.itemid = c.id
                     WHERE c.course = :courseid
                           AND bc.type = :typesection";

            $sectionparams = ['typesection' => 'section'] + $params;

            $userlist->add_from_sql('userid', $sql, $sectionparams);
        }

        if ($context instanceof \context_module) {
            $params = [
                'cmid' => $context->instanceid,
                'typeactivity' => 'activity'
            ];

            $sql = "SELECT bc.userid
                      FROM {backup_controllers} bc
                     WHERE bc.itemid = :cmid
                           AND bc.type = :typeactivity";

            $userlist->add_from_sql('userid', $sql, $params);
        }
    }
917077
public function update_user_enrol(stdClass $instance, $userid, $status = NULL, $timestart = NULL, $timeend = NULL) {
        global $DB, $USER, $CFG;

        $name = $this->get_name();

        if ($instance->enrol !== $name) {
            throw new coding_exception('invalid enrol instance!');
        }

        if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
            // weird, user not enrolled
            return;
        }

        $modified = false;
        if (isset($status) and $ue->status != $status) {
            $ue->status = $status;
            $modified = true;
        }
        if (isset($timestart) and $ue->timestart != $timestart) {
            $ue->timestart = $timestart;
            $modified = true;
        }
        if (isset($timeend) and $ue->timeend != $timeend) {
            $ue->timeend = $timeend;
            $modified = true;
        }

        if (!$modified) {
            // no change
            return;
        }

        $ue->modifierid = $USER->id;
        $ue->timemodified = time();
        $DB->update_record('user_enrolments', $ue);

        // User enrolments have changed, so mark user as dirty.
        mark_user_dirty($userid);

        // Invalidate core_access cache for get_suspended_userids.
        cache_helper::invalidate_by_definition('core', 'suspended_userids', array(), array($instance->courseid));

        // Trigger event.
        $event = \core\event\user_enrolment_updated::create(
                array(
                    'objectid' => $ue->id,
                    'courseid' => $instance->courseid,
                    'context' => context_course::instance($instance->courseid),
                    'relateduserid' => $ue->userid,
                    'other' => array('enrol' => $name)
                    )
                );
        $event->trigger();

        core_course_category::user_enrolment_changed($instance->courseid, $ue->userid,
                $ue->status, $ue->timestart, $ue->timeend);
    }
1050433
public static function delete_data_for_users(approved_userlist $userlist) {
        global $DB;

        $context = $userlist->get_context();
        $lessonid = static::get_lesson_id_from_context($context);
        $userids = $userlist->get_userids();

        if (empty($lessonid)) {
            return;
        }

        // Prepare the SQL we'll need below.
        list($insql, $inparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED);
        $sql = "lessonid = :lessonid AND userid {$insql}";
        $params = array_merge($inparams, ['lessonid' => $lessonid]);

        // Delete the attempt files.
        $fs = get_file_storage();
        $recordset = $DB->get_recordset_select('lesson_attempts', $sql, $params, '', 'id, lessonid');
        foreach ($recordset as $record) {
            $fs->delete_area_files($context->id, 'mod_lesson', 'essay_responses', $record->id);
            $fs->delete_area_files($context->id, 'mod_lesson', 'essay_answers', $record->id);
        }
        $recordset->close();

        // Delete all the things.
        $DB->delete_records_select('lesson_attempts', $sql, $params);
        $DB->delete_records_select('lesson_branch', $sql, $params);
        $DB->delete_records_select('lesson_grades', $sql, $params);
        $DB->delete_records_select('lesson_timer', $sql, $params);
        $DB->delete_records_select('lesson_overrides', $sql, $params);
    }
1059772
protected function process_records(progress_trace $trace, $action, $roleid, $user, $course, $timestart, $timeend, $buffer_if_future = true) {
        global $CFG, $DB;

        // Check if timestart is for future processing.
        if ($timestart > time() and $buffer_if_future) {
            // Populate into enrol_flatfile table as a future role to be assigned by cron.
            // Note: since 2.0 future enrolments do not cause problems if you disable guest access.
            $future_en = new stdClass();
            $future_en->action       = $action;
            $future_en->roleid       = $roleid;
            $future_en->userid       = $user->id;
            $future_en->courseid     = $course->id;
            $future_en->timestart    = $timestart;
            $future_en->timeend      = $timeend;
            $future_en->timemodified = time();
            $DB->insert_record('enrol_flatfile', $future_en);
            $trace->output("User $user->id will be enrolled later into course $course->id using role $roleid ($timestart, $timeend)", 1);
            return;
        }

        $context = context_course::instance($course->id);

        if ($action === 'add') {
            // Clear the buffer just in case there were some future enrolments.
            $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));

            $instance = $DB->get_record('enrol', array('courseid' => $course->id, 'enrol' => 'flatfile'));
            if (empty($instance)) {
                // Only add an enrol instance to the course if non-existent.
                $enrolid = $this->add_instance($course);
                $instance = $DB->get_record('enrol', array('id' => $enrolid));
            }

            $notify = false;
            if ($ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
                // Update only.
                $this->update_user_enrol($instance, $user->id, ENROL_USER_ACTIVE, $timestart, $timeend);
                if (!$DB->record_exists('role_assignments', array('contextid'=>$context->id, 'roleid'=>$roleid, 'userid'=>$user->id, 'component'=>'enrol_flatfile', 'itemid'=>$instance->id))) {
                    role_assign($roleid, $user->id, $context->id, 'enrol_flatfile', $instance->id);
                }
                $trace->output("User $user->id enrolment updated in course $course->id using role $roleid ($timestart, $timeend)", 1);

            } else {
                // Enrol the user with this plugin instance.
                $this->enrol_user($instance, $user->id, $roleid, $timestart, $timeend);
                $trace->output("User $user->id enrolled in course $course->id using role $roleid ($timestart, $timeend)", 1);
                $notify = true;
            }

            if ($notify and $this->get_config('mailstudents')) {
                $oldforcelang = force_current_language($user->lang);

                // Send welcome notification to enrolled users.
                $a = new stdClass();
                $a->coursename = format_string($course->fullname, true, array('context' => $context));
                $a->profileurl = "$CFG->wwwroot/user/view.php?id=$user->id&amp;course=$course->id";
                $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));

                $eventdata = new \core\message\message();
                $eventdata->courseid          = $course->id;
                $eventdata->modulename        = 'moodle';
                $eventdata->component         = 'enrol_flatfile';
                $eventdata->name              = 'flatfile_enrolment';
                $eventdata->userfrom          = $this->get_enroller($course->id);
                $eventdata->userto            = $user;
                $eventdata->subject           = $subject;
                $eventdata->fullmessage       = get_string('welcometocoursetext', '', $a);
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml   = '';
                $eventdata->smallmessage      = '';
                if (message_send($eventdata)) {
                    $trace->output("Notified enrolled user", 1);
                } else {
                    $trace->output("Failed to notify enrolled user", 1);
                }

                force_current_language($oldforcelang);
            }

            if ($notify and $this->get_config('mailteachers', 0)) {
                // Notify person responsible for enrolments.
                $enroller = $this->get_enroller($course->id);

                $oldforcelang = force_current_language($enroller->lang);

                $a = new stdClass();
                $a->course = format_string($course->fullname, true, array('context' => $context));
                $a->user = fullname($user);
                $subject = get_string('enrolmentnew', 'enrol', format_string($course->shortname, true, array('context' => $context)));

                $eventdata = new \core\message\message();
                $eventdata->courseid          = $course->id;
                $eventdata->modulename        = 'moodle';
                $eventdata->component         = 'enrol_flatfile';
                $eventdata->name              = 'flatfile_enrolment';
                $eventdata->userfrom          = get_admin();
                $eventdata->userto            = $enroller;
                $eventdata->subject           = $subject;
                $eventdata->fullmessage       = get_string('enrolmentnewuser', 'enrol', $a);
                $eventdata->fullmessageformat = FORMAT_PLAIN;
                $eventdata->fullmessagehtml   = '';
                $eventdata->smallmessage      = '';
                if (message_send($eventdata)) {
                    $trace->output("Notified enroller {$eventdata->userto->id}", 1);
                } else {
                    $trace->output("Failed to notify enroller {$eventdata->userto->id}", 1);
                }

                force_current_language($oldforcelang);
            }
            return;

        } else if ($action === 'del') {
            // Clear the buffer just in case there were some future enrolments.
            $DB->delete_records('enrol_flatfile', array('userid'=>$user->id, 'courseid'=>$course->id, 'roleid'=>$roleid));

            $action = $this->get_config('unenrolaction');
            if ($action == ENROL_EXT_REMOVED_KEEP) {
                $trace->output("del action is ignored", 1);
                return;
            }

            // Loops through all enrolment methods, try to unenrol if roleid somehow matches.
            $instances = $DB->get_records('enrol', array('courseid' => $course->id));
            $unenrolled = false;
            foreach ($instances as $instance) {
                if (!$ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$user->id))) {
                    continue;
                }
                if ($instance->enrol === 'flatfile') {
                    $plugin = $this;
                } else {
                    if (!enrol_is_enabled($instance->enrol)) {
                        continue;
                    }
                    if (!$plugin = enrol_get_plugin($instance->enrol)) {
                        continue;
                    }
                    if (!$plugin->allow_unenrol_user($instance, $ue)) {
                        continue;
                    }
                }

                // For some reason the del action includes a role name, this complicates everything.
                $componentroles = array();
                $manualroles = array();
                $ras = $DB->get_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id));
                foreach ($ras as $ra) {
                    if ($ra->component === '') {
                        $manualroles[$ra->roleid] = $ra->roleid;
                    } else if ($ra->component === 'enrol_'.$instance->enrol and $ra->itemid == $instance->id) {
                        $componentroles[$ra->roleid] = $ra->roleid;
                    }
                }

                if ($componentroles and !isset($componentroles[$roleid])) {
                    // Do not unenrol using this method, user has some other protected role!
                    continue;

                } else if (empty($ras)) {
                    // If user does not have any roles then let's just suspend as many methods as possible.

                } else if (!$plugin->roles_protected()) {
                    if (!$componentroles and $manualroles and !isset($manualroles[$roleid])) {
                        // Most likely we want to keep users enrolled because they have some other course roles.
                        continue;
                    }
                }

                if ($action == ENROL_EXT_REMOVED_UNENROL) {
                    $unenrolled = true;
                    if (!$plugin->roles_protected()) {
                        role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
                    }
                    $plugin->unenrol_user($instance, $user->id);
                    $trace->output("User $user->id was unenrolled from course $course->id (enrol_$instance->enrol)", 1);

                } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
                    if ($plugin->allow_manage($instance)) {
                        if ($ue->status == ENROL_USER_ACTIVE) {
                            $unenrolled = true;
                            $plugin->update_user_enrol($instance, $user->id, ENROL_USER_SUSPENDED);
                            if (!$plugin->roles_protected()) {
                                role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'enrol_'.$instance->enrol, 'itemid'=>$instance->id), true);
                                role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'roleid'=>$roleid, 'component'=>'', 'itemid'=>0), true);
                            }
                            $trace->output("User $user->id enrolment was suspended in course $course->id (enrol_$instance->enrol)", 1);
                        }
                    }
                }
            }

            if (!$unenrolled) {
                if (0 == $DB->count_records('role_assignments', array('userid'=>$user->id, 'contextid'=>$context->id))) {
                    role_unassign_all(array('contextid'=>$context->id, 'userid'=>$user->id, 'component'=>'', 'itemid'=>0), true);
                }
                $trace->output("User $user->id (with role $roleid) not unenrolled from course $course->id", 1);
            }

            return;
        }
    }
33715
public function enrol_user(stdClass $instance, $userid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
        // no real enrolments here!
        return;
    }
1252386
public static function create_subscription($ruleid, $courseid, $cmid, $userid = 0) {
        global $DB, $USER;

        $subscription = new \stdClass();
        $subscription->ruleid = $ruleid;
        $subscription->courseid = $courseid;
        $subscription->cmid = $cmid;
        $subscription->userid = empty($userid) ? $USER->id : $userid;
        if ($DB->record_exists('tool_monitor_subscriptions', (array)$subscription)) {
            // Subscription already exists.
            return false;
        }

        $subscription->timecreated = time();
        $subscription->id = $DB->insert_record('tool_monitor_subscriptions', $subscription);

        // Trigger a subscription created event.
        if ($subscription->id) {
            if (!empty($subscription->courseid)) {
                $courseid = $subscription->courseid;
                $context = \context_course::instance($subscription->courseid);
            } else {
                $courseid = 0;
                $context = \context_system::instance();
            }

            $params = array(
                'objectid' => $subscription->id,
                'courseid' => $courseid,
                'context' => $context
            );
            $event = \tool_monitor\event\subscription_created::create($params);
            $event->trigger();

            // Let's invalidate the cache.
            $cache = \cache::make('tool_monitor', 'eventsubscriptions');
            $cache->delete($courseid);
        }

        return $subscription->id;
    }
279052
protected static function export_user_data_in_course_contexts_associations($userid, $courseids, $path) {
        global $DB;

        // Fetch all the courses with associations we created or modified.
        $compfields = competency::get_sql_fields('c', 'c_');
        $ccfields = course_competency::get_sql_fields('cc', 'cc_');
        $ctxfields = context_helper::get_preload_record_columns_sql('ctx');
        list($insql, $inparams) = $DB->get_in_or_equal($courseids, SQL_PARAMS_NAMED);
        $sql = "
            SELECT $compfields, $ccfields, $ctxfields
              FROM {" . course_competency::TABLE . "} cc
              JOIN {" . competency::TABLE . "} c
                ON c.id = cc.competencyid
              JOIN {" . competency_framework::TABLE . "} f
                ON f.id = c.competencyframeworkid
              JOIN {context} ctx
                ON ctx.id = f.contextid
             WHERE cc.usermodified = :userid
               AND cc.courseid $insql
          ORDER BY cc.courseid, c.id";
        $params = array_merge($inparams, ['userid' => $userid]);
        $recordset = $DB->get_recordset_sql($sql, $params);

        // Export the data.
        static::recordset_loop_and_export($recordset, 'cc_courseid', [], function($carry, $record) {
            context_helper::preload_from_record($record);
            $competency = new competency(null, competency::extract_record($record, 'c_'));
            $cc = new course_competency(null, course_competency::extract_record($record, 'cc_'));
            $carry[] = array_merge(static::transform_competency_brief($competency), [
                'timemodified' => transform::datetime($cc->get('timemodified')),
                'created_or_modified_by_you' => transform::yesno(true)
            ]);
            return $carry;

        }, function($courseid, $data) use ($path, $userid, $DB) {
            $context = context_course::instance($courseid);
            writer::with_context($context)->export_related_data($path, 'associations', (object) ['competencies' => $data]);
        });
    }
632727
protected function get_post_author($userid, $course, $forum, $cm, $context) {
        if (!isset($this->users[$userid])) {
            // This user no longer exists.
            return false;
        }

        $user = $this->users[$userid];

        if (!isset($user->groups)) {
            // Initialise the groups list.
            $user->groups = [];
        }

        if (!isset($user->groups[$forum->id])) {
            $user->groups[$forum->id] = groups_get_all_groups($course->id, $user->id, $cm->groupingid);
        }

        // Clone the user object to prevent leaks between messages.
        return (object) (array) $user;
    }
1219490
private function computeTimeForUserAndWorkspace($startDate, $userId, $workspaceId, $time)
    {
        // select first "out of this workspace event" (ie "workspace enter" on another workspace)
        $sql = "SELECT date_log FROM claro_log WHERE action LIKE 'workspace-enter' AND doer_id = :uid  AND date_log > :dateLog ORDER BY date_log ASC LIMIT 1";
        $stmt = $this->em->getConnection()->prepare($sql);
        $stmt->bindValue('uid', $userId);
        $stmt->bindValue('dateLog', $startDate);
        $stmt->execute();
        $action = $stmt->fetch();

        // if there is an action we can compute time
        if ($action['date_log']) {
            $t1 = strtotime($startDate);
            $t2 = strtotime($action['date_log']);
            $seconds = $t2 - $t1;

            // add time only if bewteen 30s and 2 hours <= totally arbitrary !
            if ($seconds > 5 && ($seconds / 60) <= 120) {
                $time += $seconds;
            }
            // get next "enter the requested workspace enter event"
            $sql = "SELECT date_log FROM claro_log WHERE action LIKE 'workspace-enter' AND doer_id = :uid AND date_log > :dateLog AND workspace_id = :wid ORDER BY date_log ASC LIMIT 1";
            $stmt = $this->em->getConnection()->prepare($sql);
            $stmt->bindValue('uid', $userId);
            $stmt->bindValue('dateLog', $action['date_log']);
            $stmt->bindValue('wid', $workspaceId);
            $stmt->execute();
            $nextEnterEvent = $stmt->fetch();
            // if there is an "enter-workspace" action after the current one recall the method
            if ($nextEnterEvent['date_log']) {
                return $this->computeTimeForUserAndWorkspace($nextEnterEvent['date_log'], $userId, $workspaceId, $time);
            } else {
                return $time;
            }
        }

        return $time;
    }
839567
public static function viewed($context, $courseid, $userid) {
        $event = \gradereport_overview\event\grade_report_viewed::create(
            array(
                'context' => $context,
                'courseid' => $courseid,
                'relateduserid' => $userid,
            )
        );
        $event->trigger();
    }
64652
public function checkinRecords(int $startTime, int $endTime, array $userList, int $type = 3)
    {
        $params = [
            'opencheckindatatype' => $type,
            'starttime' => $startTime,
            'endtime' => $endTime,
            'useridlist' => $userList,
        ];

        return $this->httpPostJson('cgi-bin/checkin/getcheckindata', $params);
    }
690442
public function execute($respTrackData = null, $userId = null)
    {
        $batch     = $this->getBatch();
        $tracker   = $this->loader->getTracker();
        $respTrack = $tracker->getRespondentTrack($respTrackData);

        $i = $batch->addToCounter('checkedRespondentTracks');

        if ($result = $respTrack->checkTrackTokens($userId)) {
            $a = $batch->addToCounter('tokenDateCauses');
            $b = $batch->addToCounter('tokenDateChanges', $result);
            $batch->setMessage('tokenDateChanges',
                    sprintf($this->_('%2$d token date changes in %1$d tracks.'), $a, $b)
                    );
        }

        $batch->setMessage('checkedRespondentTracks', sprintf($this->_('Checked %d tracks.'), $i));
    }
922316
protected function reset($course) {
        global $DB;

        $resetdata = new stdClass();
        $resetdata->id = $course->id;
        $resetdata->reset_start_date = time();
        $resetdata->reset_events = true;
        $resetdata->reset_notes = true;
        $resetdata->delete_blog_associations = true;
        $resetdata->reset_completion = true;
        $resetdata->reset_roles_overrides = true;
        $resetdata->reset_roles_local = true;
        $resetdata->reset_groups_members = true;
        $resetdata->reset_groups_remove = true;
        $resetdata->reset_groupings_members = true;
        $resetdata->reset_groupings_remove = true;
        $resetdata->reset_gradebook_items = true;
        $resetdata->reset_gradebook_grades = true;
        $resetdata->reset_comments = true;

        if (empty($course->startdate)) {
            $course->startdate = $DB->get_field_select('course', 'startdate', 'id = :id', array('id' => $course->id));
        }
        $resetdata->reset_start_date_old = $course->startdate;

        if (empty($course->enddate)) {
            $course->enddate = $DB->get_field_select('course', 'enddate', 'id = :id', array('id' => $course->id));
        }
        $resetdata->reset_end_date_old = $course->enddate;

        // Add roles.
        $roles = tool_uploadcourse_helper::get_role_ids();
        $resetdata->unenrol_users = array_values($roles);
        $resetdata->unenrol_users[] = 0;    // Enrolled without role.

        return reset_course_userdata($resetdata);
    }
965867
public static function data_for_report($courseid, $userid, $moduleid) {
        global $PAGE;

        $params = self::validate_parameters(
            self::data_for_report_parameters(),
            array(
                'courseid' => $courseid,
                'userid' => $userid,
                'moduleid' => $moduleid
            )
        );
        $context = context_course::instance($params['courseid']);
        self::validate_context($context);
        if (!is_enrolled($context, $params['userid'], 'moodle/competency:coursecompetencygradable')) {
            throw new coding_exception('invaliduser');
        }

        $renderable = new output\report($params['courseid'], $params['userid'], $params['moduleid']);
        $renderer = $PAGE->get_renderer('report_competency');

        $data = $renderable->export_for_template($renderer);

        return $data;
    }
853908
public function execute($respTrackData = null, $userId = null)
    {
        $batch     = $this->getBatch();
        $tracker   = $this->loader->getTracker();
        $respTrack = $tracker->getRespondentTrack($respTrackData);
        $engine    = $respTrack->getTrackEngine();

        $engine->checkRoundsFor($respTrack, $userId, $batch);
    }