This is executed every time we have one /MOODLE_BACKUP/COURSE/MODULES/MOD/WORKSHOP
data available
344436
public function process_workshop($data, $raw) {

        // re-use the upgrade function to convert workshop record
        $fakerecord = (object)$data;
        $fakerecord->course = 12345678;
        $this->currentworkshop = (array)workshop_upgrade_transform_instance($fakerecord);
        unset($this->currentworkshop['course']);

        // add the new fields with the default values
        $this->currentworkshop['id']                        = $data['id'];
        $this->currentworkshop['evaluation']                = 'best';
        $this->currentworkshop['examplesmode']              = workshop::EXAMPLES_VOLUNTARY;
        $this->currentworkshop['gradedecimals']             = 0;
        $this->currentworkshop['instructauthors']           = '';
        $this->currentworkshop['instructauthorsformat']     = FORMAT_HTML;
        $this->currentworkshop['instructreviewers']         = '';
        $this->currentworkshop['instructreviewersformat']   = FORMAT_HTML;
        $this->currentworkshop['latesubmissions']           = 0;
        $this->currentworkshop['conclusion']                = '';
        $this->currentworkshop['conclusionformat']          = FORMAT_HTML;

        foreach (array('submissionend', 'submissionstart', 'assessmentend', 'assessmentstart') as $field) {
            if (!array_key_exists($field, $this->currentworkshop)) {
                $this->currentworkshop[$field] = null;
            }
        }

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

        // get a fresh new inforef manager for this instance
        $this->inforefman = $this->converter->get_inforef_manager('activity', $moduleid);

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

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

        // write workshop.xml
        $this->open_xml_writer("activities/workshop_{$moduleid}/workshop.xml");
        $this->xmlwriter->begin_tag('activity', array('id' => $instanceid, 'moduleid' => $moduleid,
            'modulename' => 'workshop', 'contextid' => $contextid));
        $this->xmlwriter->begin_tag('workshop', array('id' => $instanceid));

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

        return $this->currentworkshop;
    }
438978
function init() {

      /// Moodle mods:  overrides the font path and encodings

      global $CFG;

      /// A default.ttf is searched for in this order:
      ///      dataroot/lang/xx_local/fonts
      ///      dataroot/lang/xx/fonts
      ///      dirroot/lang/xx/fonts
      ///      dataroot/lang
      ///      lib/

      $currlang = current_language();
      if (file_exists("$CFG->dataroot/lang/".$currlang."_local/fonts/default.ttf")) {
          $fontpath = "$CFG->dataroot/lang/".$currlang."_local/fonts/";
      } else if (file_exists("$CFG->dataroot/lang/$currlang/fonts/default.ttf")) {
          $fontpath = "$CFG->dataroot/lang/$currlang/fonts/";
      } else if (file_exists("$CFG->dirroot/lang/$currlang/fonts/default.ttf")) {
          $fontpath = "$CFG->dirroot/lang/$currlang/fonts/";
      } else if (file_exists("$CFG->dataroot/lang/default.ttf")) {
          $fontpath = "$CFG->dataroot/lang/";
      } else {
          $fontpath = "$CFG->libdir/";
      }

      $this->parameter['path_to_fonts'] = $fontpath;

      /// End Moodle mods



      $this->calculated['outer_border'] = $this->calculated['boundary_box'];

      // outer padding
      $this->calculated['boundary_box']['left']   += $this->parameter['outer_padding'];
      $this->calculated['boundary_box']['top']    += $this->parameter['outer_padding'];
      $this->calculated['boundary_box']['right']  -= $this->parameter['outer_padding'];
      $this->calculated['boundary_box']['bottom'] -= $this->parameter['outer_padding'];

      $this->init_x_axis();
      $this->init_y_axis();
      $this->init_legend();
      $this->init_labels();

      //  take into account tick lengths
      $this->calculated['bottom_inner_padding'] = $this->parameter['x_inner_padding'];
      if (($this->parameter['x_ticks_colour'] != 'none') && ($this->parameter['tick_length'] < 0))
        $this->calculated['bottom_inner_padding'] -= $this->parameter['tick_length'];
      $this->calculated['boundary_box']['bottom'] -= $this->calculated['bottom_inner_padding'];

      $this->calculated['left_inner_padding'] = $this->parameter['y_inner_padding'];
      if ($this->parameter['y_axis_text_left']) {
        if (($this->parameter['y_ticks_colour'] != 'none') && ($this->parameter['tick_length'] < 0))
          $this->calculated['left_inner_padding'] -= $this->parameter['tick_length'];
      }
      $this->calculated['boundary_box']['left'] += $this->calculated['left_inner_padding'];

      $this->calculated['right_inner_padding'] = $this->parameter['y_inner_padding'];
      if ($this->parameter['y_axis_text_right']) {
        if (($this->parameter['y_ticks_colour'] != 'none') && ($this->parameter['tick_length'] < 0))
          $this->calculated['right_inner_padding'] -= $this->parameter['tick_length'];
      }
      $this->calculated['boundary_box']['right'] -= $this->calculated['right_inner_padding'];

      // boundaryBox now has coords for plotting area.
      $this->calculated['inner_border'] = $this->calculated['boundary_box'];

      $this->init_data();
      $this->init_x_ticks();
      $this->init_y_ticks();
    }
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;
    }
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;
    }
1240156
function(mod) {
  // XXX: consider using `Module.parent` and `delete require.cache[module.id]`
  if (!(mod instanceof Module)) {
    throw new TypeError(
      'Module required (e.g., "var __ = require(\'@carbon-io/fibers\').__(module)")')
  }
  var __ = function(f, cb) {
    if (typeof __ensure._getCurrentFiber() === 'undefined') {
      return __spawn(f, cb, _debugLogger.bind(undefined, mod))
    }
    var ret = undefined
    try {
      ret = f()
      if (cb) {
        cb(null, ret)
      }
    } catch (e) {
      // XXX: do we want to log to stderr here? setting mod to undefined for 
      //      now to disable stderr
      _debugLogger(
        undefined, 'Exception caught with cb undefined in __: ' + inspect(e))
      if (cb) {
        cb(e)
      } else {
        throw e
      }
    }
  }

  //  __(.main)?
  __.main = function() {
    console.warn('"__.main" is DEPRECATED and no longer necessary')
    return __.apply(undefined, arguments)
  }

  //  __(.ensure)*(.main)?
  __.ensure = __

  //  __(.(ensure|main))*
  __.main.ensure = __

  //  __(.(ensure|main))*(.spawn)?
  __.spawn = __spawn

  //  __(.(ensure|main))*(.spawn(.main(.(ensure|main))*)?)?
  __.spawn.main = __.main

  //  __(.(ensure|main))*(.spawn(.(ensure|main))*)?
  __.spawn.ensure = __

  //  __(.(spawn|ensure|main))*
  __.spawn.spawn = __spawn

  return __
}
544824
public function process_data($data) {
        global $DB;
        $warnings = array();

        $separategroups = false;
        $mygroups       = array();
        if ($this->groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $this->context)) {
            $separategroups = true;
            $mygroups = groups_get_user_groups($this->course->id);
            $mygroups = $mygroups[0]; // ignore groupings
            // reorder the groups fro better perf below
            $current = array_search($this->currentgroup, $mygroups);
            if ($current !== false) {
                unset($mygroups[$current]);
                array_unshift($mygroups, $this->currentgroup);
            }
        }
        $viewfullnames = has_capability('moodle/site:viewfullnames', $this->context);

        // always initialize all arrays
        $queue = array();

        $this->load_users();
        $this->load_final_grades();

        // Were any changes made?
        $changedgrades = false;
        $timepageload = clean_param($data->timepageload, PARAM_INT);

        foreach ($data as $varname => $students) {

            $needsupdate = false;

            // skip, not a grade nor feedback
            if (strpos($varname, 'grade') === 0) {
                $datatype = 'grade';
            } else if (strpos($varname, 'feedback') === 0) {
                $datatype = 'feedback';
            } else {
                continue;
            }

            foreach ($students as $userid => $items) {
                $userid = clean_param($userid, PARAM_INT);
                foreach ($items as $itemid => $postedvalue) {
                    $itemid = clean_param($itemid, PARAM_INT);

                    // Was change requested?
                    $oldvalue = $this->grades[$userid][$itemid];
                    if ($datatype === 'grade') {
                        // If there was no grade and there still isn't
                        if (is_null($oldvalue->finalgrade) && $postedvalue == -1) {
                            // -1 means no grade
                            continue;
                        }

                        // If the grade item uses a custom scale
                        if (!empty($oldvalue->grade_item->scaleid)) {

                            if ((int)$oldvalue->finalgrade === (int)$postedvalue) {
                                continue;
                            }
                        } else {
                            // The grade item uses a numeric scale

                            // Format the finalgrade from the DB so that it matches the grade from the client
                            if ($postedvalue === format_float($oldvalue->finalgrade, $oldvalue->grade_item->get_decimals())) {
                                continue;
                            }
                        }

                        $changedgrades = true;

                    } else if ($datatype === 'feedback') {
                        // If quick grading is on, feedback needs to be compared without line breaks.
                        if ($this->get_pref('quickgrading')) {
                            $oldvalue->feedback = preg_replace("/\r\n|\r|\n/", "", $oldvalue->feedback);
                        }
                        if (($oldvalue->feedback === $postedvalue) or ($oldvalue->feedback === null and empty($postedvalue))) {
                            continue;
                        }
                    }

                    if (!$gradeitem = grade_item::fetch(array('id'=>$itemid, 'courseid'=>$this->courseid))) {
                        print_error('invalidgradeitemid');
                    }

                    // Pre-process grade
                    if ($datatype == 'grade') {
                        $feedback = false;
                        $feedbackformat = false;
                        if ($gradeitem->gradetype == GRADE_TYPE_SCALE) {
                            if ($postedvalue == -1) { // -1 means no grade
                                $finalgrade = null;
                            } else {
                                $finalgrade = $postedvalue;
                            }
                        } else {
                            $finalgrade = unformat_float($postedvalue);
                        }

                        $errorstr = '';
                        $skip = false;

                        $dategraded = $oldvalue->get_dategraded();
                        if (!empty($dategraded) && $timepageload < $dategraded) {
                            // Warn if the grade was updated while we were editing this form.
                            $errorstr = 'gradewasmodifiedduringediting';
                            $skip = true;
                        } else if (!is_null($finalgrade)) {
                            // Warn if the grade is out of bounds.
                            $bounded = $gradeitem->bounded_grade($finalgrade);
                            if ($bounded > $finalgrade) {
                                $errorstr = 'lessthanmin';
                            } else if ($bounded < $finalgrade) {
                                $errorstr = 'morethanmax';
                            }
                        }

                        if ($errorstr) {
                            $userfields = 'id, ' . get_all_user_name_fields(true);
                            $user = $DB->get_record('user', array('id' => $userid), $userfields);
                            $gradestr = new stdClass();
                            $gradestr->username = fullname($user, $viewfullnames);
                            $gradestr->itemname = $gradeitem->get_name();
                            $warnings[] = get_string($errorstr, 'grades', $gradestr);
                            if ($skip) {
                                // Skipping the update of this grade it failed the tests above.
                                continue;
                            }
                        }

                    } else if ($datatype == 'feedback') {
                        $finalgrade = false;
                        $trimmed = trim($postedvalue);
                        if (empty($trimmed)) {
                             $feedback = null;
                        } else {
                             $feedback = $postedvalue;
                        }
                    }

                    // group access control
                    if ($separategroups) {
                        // note: we can not use $this->currentgroup because it would fail badly
                        //       when having two browser windows each with different group
                        $sharinggroup = false;
                        foreach ($mygroups as $groupid) {
                            if (groups_is_member($groupid, $userid)) {
                                $sharinggroup = true;
                                break;
                            }
                        }
                        if (!$sharinggroup) {
                            // either group membership changed or somebody is hacking grades of other group
                            $warnings[] = get_string('errorsavegrade', 'grades');
                            continue;
                        }
                    }

                    $gradeitem->update_final_grade($userid, $finalgrade, 'gradebook', $feedback, FORMAT_MOODLE);

                    // We can update feedback without reloading the grade item as it doesn't affect grade calculations
                    if ($datatype === 'feedback') {
                        $this->grades[$userid][$itemid]->feedback = $feedback;
                    }
                }
            }
        }

        if ($changedgrades) {
            // If a final grade was overriden reload grades so dependent grades like course total will be correct
            $this->grades = null;
        }

        return $warnings;
    }
1297583
public function moodleform_mod($current, $section, $cm, $course) {
        debugging('Use of class name as constructor is deprecated', DEBUG_DEVELOPER);
        self::__construct($current, $section, $cm, $course);
    }
1322159
public function set_module_viewed() {
        global $CFG;
        require_once($CFG->libdir . '/completionlib.php');

        // Mark viewed.
        $completion = new completion_info($this->course);
        $completion->set_module_viewed($this->cm);

        $eventdata = array();
        $eventdata['objectid'] = $this->id;
        $eventdata['context'] = $this->context;

        // Trigger module viewed event.
        $event = \mod_workshop\event\course_module_viewed::create($eventdata);
        $event->add_record_snapshot('course', $this->course);
        $event->add_record_snapshot('workshop', $this->dbrecord);
        $event->add_record_snapshot('course_modules', $this->cm);
        $event->trigger();
    }
827962
public function postAutoloadDump()
    {
        $graph = $this->getGraph();

        $this->io->write('<info>Pass 3/3: Performing individual generation</info>');
        $this->generateConcreteIndividualCode($graph);
    }
453541
private function setLoadAfterLegacyModules(): void
    {
        static $legacy = [
            'core',
            'calendar',
            'comments',
            'faq',
            'listing',
            'news',
            'newsletter',
        ];

        $modules = array_merge($legacy, [$this->getName()]);
        sort($modules);
        $modules = array_values($modules);
        array_splice($modules, array_search($this->getName(), $modules, true));

        if (!\in_array('core', $modules, true)) {
            $modules[] = 'core';
        }

        $this->setLoadAfter($modules);
    }
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();
        }
    }
436473
public function store_item($cm) {
        global $CFG, $DB;

        require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');

        // Get more information.
        $modinfo = get_fast_modinfo($cm->course);

        if (!isset($modinfo->cms[$cm->id])) {
            return; // Can't continue without the module information.
        }

        $cminfo = $modinfo->cms[$cm->id];

        // Check backup/restore support.
        if (!plugin_supports('mod', $cminfo->modname , FEATURE_BACKUP_MOODLE2)) {
            return;
        }

        // As far as recycle bin is using MODE_AUTOMATED, it observes the backup_auto_storage
        // setting (storing backups @ real location. For recycle bin we want to ensure that
        // backup files are always stored in Moodle file area. In order to achieve that, we
        // hack the setting here via $CFG->forced_plugin_settings, so it won't interfere other
        // operations.  See MDL-65218 for more information.
        // This hack will be removed once recycle bin switches to use its own backup mode, with
        // own preferences and 100% appart from MODLE_AUTOMATED.
        // TODO: Remove this as part of MDL-65228.
        $CFG->forced_plugin_settings['backup'] = ['backup_auto_storage' => 0];

        // Backup the activity.
        $user = get_admin();
        $controller = new \backup_controller(
            \backup::TYPE_1ACTIVITY,
            $cm->id,
            \backup::FORMAT_MOODLE,
            \backup::INTERACTIVE_NO,
            \backup::MODE_AUTOMATED,
            $user->id
        );
        $controller->execute_plan();

        // We don't need the forced setting anymore, hence unsetting it.
        // TODO: Remove this as part of MDL-65228.
        unset($CFG->forced_plugin_settings['backup']);

        // Grab the result.
        $result = $controller->get_results();
        if (!isset($result['backup_destination'])) {
            throw new \moodle_exception('Failed to backup activity prior to deletion.');
        }

        // Have finished with the controller, let's destroy it, freeing mem and resources.
        $controller->destroy();

        // Grab the filename.
        $file = $result['backup_destination'];
        if (!$file->get_contenthash()) {
            throw new \moodle_exception('Failed to backup activity prior to deletion (invalid file).');
        }

        // Record the activity, get an ID.
        $activity = new \stdClass();
        $activity->courseid = $cm->course;
        $activity->section = $cm->section;
        $activity->module = $cm->module;
        $activity->name = $cminfo->name;
        $activity->timecreated = time();
        $binid = $DB->insert_record('tool_recyclebin_course', $activity);

        // Create the location we want to copy this file to.
        $filerecord = array(
            'contextid' => \context_course::instance($this->_courseid)->id,
            'component' => 'tool_recyclebin',
            'filearea' => TOOL_RECYCLEBIN_COURSE_BIN_FILEAREA,
            'itemid' => $binid,
            'timemodified' => time()
        );

        // Move the file to our own special little place.
        $fs = get_file_storage();
        if (!$fs->create_file_from_storedfile($filerecord, $file)) {
            // Failed, cleanup first.
            $DB->delete_records('tool_recyclebin_course', array(
                'id' => $binid
            ));

            throw new \moodle_exception("Failed to copy backup file to recyclebin.");
        }

        // Delete the old file.
        $file->delete();

        // Fire event.
        $event = \tool_recyclebin\event\course_bin_item_created::create(array(
            'objectid' => $binid,
            'context' => \context_course::instance($cm->course)
        ));
        $event->trigger();
    }
186437
public function execute() {
        global $CFG;
        require_once($CFG->dirroot. '/course/lib.php');

        // Set the proper user.
        if ($this->get_custom_data()->userid !== $this->get_custom_data()->realuserid) {
            $realuser = \core_user::get_user($this->get_custom_data()->realuserid, '*', MUST_EXIST);
            cron_setup_user($realuser);
            \core\session\manager::loginas($this->get_custom_data()->userid, \context_system::instance(), false);
        } else {
            $user = \core_user::get_user($this->get_custom_data()->userid, '*', MUST_EXIST);
            cron_setup_user($user);
        }

        $cms = $this->get_custom_data()->cms;
        foreach ($cms as $cm) {
            try {
                course_delete_module($cm->id);
            } catch (\Exception $e) {
                throw new \coding_exception("The course module {$cm->id} could not be deleted. {$e->getTraceAsString()}");
            }
        }
    }
1098009
public function execute() {
        global $CFG;

        // The directories hosting the candidate stale temp files eventually are $CFG->tempdir and $CFG->backuptempdir.

        // Do the job on each of the directories above.
        // Let's start with $CFG->tempdir.
        $this->execute_on($CFG->tempdir);

        // Run on $CFG->backuptempdir too, if different from the default one, '$CFG->tempdir/backup'.
        if (realpath(dirname($CFG->backuptempdir)) !== realpath($CFG->tempdir)) {
            // The $CFG->backuptempdir setting is different from the default '$CFG->tempdir/backup'.
            $this->execute_on($CFG->backuptempdir);
        }
    }
303603
protected void initModule() {

        Object o;
        CmsModule module;

        if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) {
            // this is the initial dialog call
            if (CmsStringUtil.isNotEmpty(m_paramModule)) {
                // edit an existing module, get it from manager
                o = OpenCms.getModuleManager().getModule(m_paramModule);
            } else {
                // create a new module
                o = null;
            }
        } else {
            // this is not the initial call, get module from session
            o = getDialogObject();
        }

        if (!(o instanceof CmsModule)) {
            // create a new module
            module = new CmsModule();

        } else {
            // reuse module stored in session
            module = (CmsModule)((CmsModule)o).clone();
        }

        List exportpoints = module.getExportPoints();
        m_exportpoint = new CmsExportPoint();
        if ((exportpoints != null) && (exportpoints.size() > 0)) {
            Iterator i = exportpoints.iterator();
            while (i.hasNext()) {
                CmsExportPoint exportpoint = (CmsExportPoint)i.next();
                if (exportpoint.getUri().equals(m_paramExportpoint)) {
                    m_exportpoint = exportpoint;
                }
            }
        }

    }
504895
public function execute() {
        global $CFG;

        require_once($CFG->dirroot . '/course/lib.php');

        // Specific list of plugins that need to be refreshed. If not set, then all mod plugins will be refreshed.
        $pluginstorefresh = null;
        if (isset($this->get_custom_data()->plugins)) {
            $pluginstorefresh = $this->get_custom_data()->plugins;
        }

        // Is course id set?
        if (isset($this->get_custom_data()->courseid)) {
            $courseid = $this->get_custom_data()->courseid;
        } else {
            $courseid = 0;
        }

        $pluginmanager = core_plugin_manager::instance();
        $modplugins = $pluginmanager->get_plugins_of_type('mod');
        foreach ($modplugins as $plugin) {
            // Check if a specific list of plugins is defined and check if it contains the plugin that is currently being evaluated.
            if (!empty($pluginstorefresh) && !in_array($plugin->name, $pluginstorefresh)) {
                // This plugin is not in the list, move on to the next one.
                continue;
            }
            // Refresh events.
            mtrace('Refreshing events for ' . $plugin->name);
            course_module_bulk_update_calendar_events($plugin->name, $courseid);
        }
    }
1334268
protected void initModule() {

        Object o;

        if (CmsStringUtil.isEmpty(getParamAction()) || CmsDialog.DIALOG_INITIAL.equals(getParamAction())) {
            // this is the initial dialog call
            if (CmsStringUtil.isNotEmpty(m_paramModule)) {
                // edit an existing module, get it from manager
                o = OpenCms.getModuleManager().getModule(m_paramModule);
            } else {
                // create a new module
                o = null;
            }
        } else {
            // this is not the initial call, get module from session
            o = getDialogObject();
        }

        if (!(o instanceof CmsModule)) {
            // create a new module
            m_module = new CmsModule();

        } else {
            // reuse module stored in session
            m_module = (CmsModule)((CmsModule)o).clone();
        }
    }