Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Adhoc task that performs asynchronous course copies.
  19   *
  20   * @package    core
  21   * @copyright  2020 onward The Moodle Users Association <https://moodleassociation.org/>
  22   * @author     Matt Porritt <mattp@catalyst-au.net>
  23   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24   */
  25  
  26  namespace core\task;
  27  
  28  use async_helper;
  29  
  30  defined('MOODLE_INTERNAL') || die();
  31  
  32  global $CFG;
  33  require_once($CFG->dirroot . '/backup/util/includes/backup_includes.php');
  34  require_once($CFG->dirroot . '/backup/moodle2/backup_plan_builder.class.php');
  35  require_once($CFG->libdir . '/externallib.php');
  36  
  37  /**
  38   * Adhoc task that performs asynchronous course copies.
  39   *
  40   * @package     core
  41   * @copyright  2020 onward The Moodle Users Association <https://moodleassociation.org/>
  42   * @author     Matt Porritt <mattp@catalyst-au.net>
  43   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  44   */
  45  class asynchronous_copy_task extends adhoc_task {
  46  
  47      /**
  48       * Run the adhoc task and preform the backup.
  49       */
  50      public function execute() {
  51          global $CFG, $DB;
  52          $started = time();
  53  
  54          $backupid = $this->get_custom_data()->backupid;
  55          $restoreid = $this->get_custom_data()->restoreid;
  56          $backuprecord = $DB->get_record('backup_controllers', array('backupid' => $backupid), 'id, itemid', MUST_EXIST);
  57          $restorerecord = $DB->get_record('backup_controllers', array('backupid' => $restoreid), 'id, itemid', MUST_EXIST);
  58  
  59          // First backup the course.
  60          mtrace('Course copy: Processing asynchronous course copy for course id: ' . $backuprecord->itemid);
  61          try {
  62              $bc = \backup_controller::load_controller($backupid); // Get the backup controller by backup id.
  63          } catch (\backup_dbops_exception $e) {
  64              mtrace('Course copy: Can not load backup controller for copy, marking job as failed');
  65              delete_course($restorerecord->itemid, false); // Clean up partially created destination course.
  66              return; // Return early as we can't continue.
  67          }
  68          $bc->set_progress(new \core\progress\db_updater($backuprecord->id, 'backup_controllers', 'progress'));
  69          $copyinfo = $bc->get_copy();
  70          $backupplan = $bc->get_plan();
  71  
  72          $keepuserdata = (bool)$copyinfo->userdata;
  73          $keptroles = $copyinfo->keptroles;
  74  
  75          $bc->set_kept_roles($keptroles);
  76  
  77          // If we are not keeping user data don't include users or data in the backup.
  78          // In this case we'll add the user enrolments at the end.
  79          // Also if we have no roles to keep don't backup users.
  80          if (empty($keptroles) || !$keepuserdata) {
  81              $backupplan->get_setting('users')->set_status(\backup_setting::NOT_LOCKED);
  82              $backupplan->get_setting('users')->set_value('0');
  83          } else {
  84              $backupplan->get_setting('users')->set_value('1');
  85          }
  86  
  87          // Do some preflight checks on the backup.
  88          $status = $bc->get_status();
  89          $execution = $bc->get_execution();
  90          // Check that the backup is in the correct status and
  91          // that is set for asynchronous execution.
  92          if ($status == \backup::STATUS_AWAITING && $execution == \backup::EXECUTION_DELAYED) {
  93              // Execute the backup.
  94              mtrace('Course copy: Backing up course, id: ' . $backuprecord->itemid);
  95              $bc->execute_plan();
  96  
  97          } else {
  98              // If status isn't 700, it means the process has failed.
  99              // Retrying isn't going to fix it, so marked operation as failed.
 100              mtrace('Course copy: Bad backup controller status, is: ' . $status . ' should be 700, marking job as failed.');
 101              $bc->set_status(\backup::STATUS_FINISHED_ERR);
 102              delete_course($restorerecord->itemid, false); // Clean up partially created destination course.
 103              $bc->destroy();
 104              return; // Return early as we can't continue.
 105  
 106          }
 107  
 108          $results = $bc->get_results();
 109          $backupbasepath = $backupplan->get_basepath();
 110          $file = $results['backup_destination'];
 111          $file->extract_to_pathname(get_file_packer('application/vnd.moodle.backup'), $backupbasepath);
 112          // Start the restore process.
 113          $rc = \restore_controller::load_controller($restoreid);  // Get the restore controller by restore id.
 114          $rc->set_progress(new \core\progress\db_updater($restorerecord->id, 'backup_controllers', 'progress'));
 115          $rc->prepare_copy();
 116  
 117          // Set the course settings we can do now (the remaining settings will be done after restore completes).
 118          $plan = $rc->get_plan();
 119  
 120          $startdate = $plan->get_setting('course_startdate');
 121          $startdate->set_value($copyinfo->startdate);
 122          $fullname = $plan->get_setting('course_fullname');
 123          $fullname->set_value($copyinfo->fullname);
 124          $shortname = $plan->get_setting('course_shortname');
 125          $shortname->set_value($copyinfo->shortname);
 126  
 127          // Do some preflight checks on the restore.
 128          $rc->execute_precheck();
 129          $status = $rc->get_status();
 130          $execution = $rc->get_execution();
 131  
 132          // Check that the restore is in the correct status and
 133          // that is set for asynchronous execution.
 134          if ($status == \backup::STATUS_AWAITING && $execution == \backup::EXECUTION_DELAYED) {
 135              // Execute the restore.
 136              mtrace('Course copy: Restoring into course, id: ' . $restorerecord->itemid);
 137              $rc->execute_plan();
 138  
 139          } else {
 140              // If status isn't 700, it means the process has failed.
 141              // Retrying isn't going to fix it, so marked operation as failed.
 142              mtrace('Course copy: Bad backup controller status, is: ' . $status . ' should be 700, marking job as failed.');
 143              $rc->set_status(\backup::STATUS_FINISHED_ERR);
 144              delete_course($restorerecord->itemid, false); // Clean up partially created destination course.
 145              $file->delete();
 146              if (empty($CFG->keeptempdirectoriesonbackup)) {
 147                  fulldelete($backupbasepath);
 148              }
 149              $rc->destroy();
 150              return; // Return early as we can't continue.
 151  
 152          }
 153  
 154          // Copy user enrolments from source course to destination.
 155          if (!empty($keptroles) && !$keepuserdata) {
 156              mtrace('Course copy: Creating user enrolments in destination course.');
 157              $context = \context_course::instance($backuprecord->itemid);
 158  
 159              $enrol = enrol_get_plugin('manual');
 160              $instance = null;
 161              $enrolinstances = enrol_get_instances($restorerecord->itemid, true);
 162              foreach ($enrolinstances as $courseenrolinstance) {
 163                  if ($courseenrolinstance->enrol == 'manual') {
 164                      $instance = $courseenrolinstance;
 165                      break;
 166                  }
 167              }
 168  
 169              // Abort if there enrolment plugin problems.
 170              if (empty($enrol) || empty($instance)) {
 171                  mtrace('Course copy: Could not enrol users in course.');;
 172                  delete_course($restorerecord->itemid, false);
 173                  return;
 174              }
 175  
 176              // Enrol the users from the source course to the destination.
 177              foreach ($keptroles as $roleid) {
 178                  $sourceusers = get_role_users($roleid, $context);
 179                  foreach ($sourceusers as $sourceuser) {
 180                      $enrol->enrol_user($instance, $sourceuser->id, $roleid);
 181                  }
 182              }
 183          }
 184  
 185          // Set up remaining course settings.
 186          $course = $DB->get_record('course', array('id' => $restorerecord->itemid), '*', MUST_EXIST);
 187          $course->visible = $copyinfo->visible;
 188          $course->idnumber = $copyinfo->idnumber;
 189          $course->enddate = $copyinfo->enddate;
 190  
 191          $DB->update_record('course', $course);
 192  
 193          // Send message to user if enabled.
 194          $messageenabled = (bool)get_config('backup', 'backup_async_message_users');
 195          if ($messageenabled && $rc->get_status() == \backup::STATUS_FINISHED_OK) {
 196              mtrace('Course copy: Sending user notification.');
 197              $asynchelper = new async_helper('copy', $restoreid);
 198              $messageid = $asynchelper->send_message();
 199              mtrace('Course copy: Sent message: ' . $messageid);
 200          }
 201  
 202          // Cleanup.
 203          $bc->destroy();
 204          $rc->destroy();
 205          $file->delete();
 206          if (empty($CFG->keeptempdirectoriesonbackup)) {
 207              fulldelete($backupbasepath);
 208          }
 209  
 210          $duration = time() - $started;
 211          mtrace('Course copy: Copy completed in: ' . $duration . ' seconds');
 212      }
 213  }