Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

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

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Defines various restore steps that will be used by common tasks in restore
  20   *
  21   * @package     core_backup
  22   * @subpackage  moodle2
  23   * @category    backup
  24   * @copyright   2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
  25   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  defined('MOODLE_INTERNAL') || die();
  29  
  30  /**
  31   * delete old directories and conditionally create backup_temp_ids table
  32   */
  33  class restore_create_and_clean_temp_stuff extends restore_execution_step {
  34  
  35      protected function define_execution() {
  36          $exists = restore_controller_dbops::create_restore_temp_tables($this->get_restoreid()); // temp tables conditionally
  37          // If the table already exists, it's because restore_prechecks have been executed in the same
  38          // request (without problems) and it already contains a bunch of preloaded information (users...)
  39          // that we aren't going to execute again
  40          if ($exists) { // Inform plan about preloaded information
  41              $this->task->set_preloaded_information();
  42          }
  43          // Create the old-course-ctxid to new-course-ctxid mapping, we need that available since the beginning
  44          $itemid = $this->task->get_old_contextid();
  45          $newitemid = context_course::instance($this->get_courseid())->id;
  46          restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
  47          // Create the old-system-ctxid to new-system-ctxid mapping, we need that available since the beginning
  48          $itemid = $this->task->get_old_system_contextid();
  49          $newitemid = context_system::instance()->id;
  50          restore_dbops::set_backup_ids_record($this->get_restoreid(), 'context', $itemid, $newitemid);
  51          // Create the old-course-id to new-course-id mapping, we need that available since the beginning
  52          $itemid = $this->task->get_old_courseid();
  53          $newitemid = $this->get_courseid();
  54          restore_dbops::set_backup_ids_record($this->get_restoreid(), 'course', $itemid, $newitemid);
  55  
  56      }
  57  }
  58  
  59  /**
  60   * Drop temp ids table and delete the temp dir used by backup/restore (conditionally).
  61   */
  62  class restore_drop_and_clean_temp_stuff extends restore_execution_step {
  63  
  64      protected function define_execution() {
  65          global $CFG;
  66          restore_controller_dbops::drop_restore_temp_tables($this->get_restoreid()); // Drop ids temp table
  67          if (empty($CFG->keeptempdirectoriesonbackup)) { // Conditionally
  68              $progress = $this->task->get_progress();
  69              $progress->start_progress('Deleting backup dir');
  70              backup_helper::delete_backup_dir($this->task->get_tempdir(), $progress); // Empty restore dir
  71              $progress->end_progress();
  72          }
  73      }
  74  }
  75  
  76  /**
  77   * Restore calculated grade items, grade categories etc
  78   */
  79  class restore_gradebook_structure_step extends restore_structure_step {
  80  
  81      /**
  82       * To conditionally decide if this step must be executed
  83       * Note the "settings" conditions are evaluated in the
  84       * corresponding task. Here we check for other conditions
  85       * not being restore settings (files, site settings...)
  86       */
  87       protected function execute_condition() {
  88          global $CFG, $DB;
  89  
  90          if ($this->get_courseid() == SITEID) {
  91              return false;
  92          }
  93  
  94          // No gradebook info found, don't execute
  95          $fullpath = $this->task->get_taskbasepath();
  96          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
  97          if (!file_exists($fullpath)) {
  98              return false;
  99          }
 100  
 101          // Some module present in backup file isn't available to restore
 102          // in this site, don't execute
 103          if ($this->task->is_missing_modules()) {
 104              return false;
 105          }
 106  
 107          // Some activity has been excluded to be restored, don't execute
 108          if ($this->task->is_excluding_activities()) {
 109              return false;
 110          }
 111  
 112          // There should only be one grade category (the 1 associated with the course itself)
 113          // If other categories already exist we're restoring into an existing course.
 114          // Restoring categories into a course with an existing category structure is unlikely to go well
 115          $category = new stdclass();
 116          $category->courseid  = $this->get_courseid();
 117          $catcount = $DB->count_records('grade_categories', (array)$category);
 118          if ($catcount>1) {
 119              return false;
 120          }
 121  
 122          $restoretask = $this->get_task();
 123  
 124          // On older versions the freeze value has to be converted.
 125          // We do this from here as it is happening right before the file is read.
 126          // This only targets the backup files that can contain the legacy freeze.
 127          if ($restoretask->backup_version_compare(20150618, '>')
 128                  && $restoretask->backup_release_compare('3.0', '<')
 129                  || $restoretask->backup_version_compare(20160527, '<')) {
 130              $this->rewrite_step_backup_file_for_legacy_freeze($fullpath);
 131          }
 132  
 133          // Arrived here, execute the step
 134          return true;
 135       }
 136  
 137      protected function define_structure() {
 138          $paths = array();
 139          $userinfo = $this->task->get_setting_value('users');
 140  
 141          $paths[] = new restore_path_element('attributes', '/gradebook/attributes');
 142          $paths[] = new restore_path_element('grade_category', '/gradebook/grade_categories/grade_category');
 143  
 144          $gradeitem = new restore_path_element('grade_item', '/gradebook/grade_items/grade_item');
 145          $paths[] = $gradeitem;
 146          $this->add_plugin_structure('local', $gradeitem);
 147  
 148          if ($userinfo) {
 149              $paths[] = new restore_path_element('grade_grade', '/gradebook/grade_items/grade_item/grade_grades/grade_grade');
 150          }
 151          $paths[] = new restore_path_element('grade_letter', '/gradebook/grade_letters/grade_letter');
 152          $paths[] = new restore_path_element('grade_setting', '/gradebook/grade_settings/grade_setting');
 153  
 154          return $paths;
 155      }
 156  
 157      protected function process_attributes($data) {
 158          // For non-merge restore types:
 159          // Unset 'gradebook_calculations_freeze_' in the course and replace with the one from the backup.
 160          $target = $this->get_task()->get_target();
 161          if ($target == backup::TARGET_CURRENT_DELETING || $target == backup::TARGET_EXISTING_DELETING) {
 162              set_config('gradebook_calculations_freeze_' . $this->get_courseid(), null);
 163          }
 164          if (!empty($data['calculations_freeze'])) {
 165              if ($target == backup::TARGET_NEW_COURSE || $target == backup::TARGET_CURRENT_DELETING ||
 166                      $target == backup::TARGET_EXISTING_DELETING) {
 167                  set_config('gradebook_calculations_freeze_' . $this->get_courseid(), $data['calculations_freeze']);
 168              }
 169          }
 170      }
 171  
 172      protected function process_grade_item($data) {
 173          global $DB;
 174  
 175          $data = (object)$data;
 176  
 177          $oldid = $data->id;
 178          $data->course = $this->get_courseid();
 179  
 180          $data->courseid = $this->get_courseid();
 181  
 182          if ($data->itemtype=='manual') {
 183              // manual grade items store category id in categoryid
 184              $data->categoryid = $this->get_mappingid('grade_category', $data->categoryid, NULL);
 185              // if mapping failed put in course's grade category
 186              if (NULL == $data->categoryid) {
 187                  $coursecat = grade_category::fetch_course_category($this->get_courseid());
 188                  $data->categoryid = $coursecat->id;
 189              }
 190          } else if ($data->itemtype=='course') {
 191              // course grade item stores their category id in iteminstance
 192              $coursecat = grade_category::fetch_course_category($this->get_courseid());
 193              $data->iteminstance = $coursecat->id;
 194          } else if ($data->itemtype=='category') {
 195              // category grade items store their category id in iteminstance
 196              $data->iteminstance = $this->get_mappingid('grade_category', $data->iteminstance, NULL);
 197          } else {
 198              throw new restore_step_exception('unexpected_grade_item_type', $data->itemtype);
 199          }
 200  
 201          $data->scaleid   = $this->get_mappingid('scale', $data->scaleid, NULL);
 202          $data->outcomeid = $this->get_mappingid('outcome', $data->outcomeid, NULL);
 203  
 204          $data->locktime = $this->apply_date_offset($data->locktime);
 205  
 206          $coursecategory = $newitemid = null;
 207          //course grade item should already exist so updating instead of inserting
 208          if($data->itemtype=='course') {
 209              //get the ID of the already created grade item
 210              $gi = new stdclass();
 211              $gi->courseid  = $this->get_courseid();
 212              $gi->itemtype  = $data->itemtype;
 213  
 214              //need to get the id of the grade_category that was automatically created for the course
 215              $category = new stdclass();
 216              $category->courseid  = $this->get_courseid();
 217              $category->parent  = null;
 218              //course category fullname starts out as ? but may be edited
 219              //$category->fullname  = '?';
 220              $coursecategory = $DB->get_record('grade_categories', (array)$category);
 221              $gi->iteminstance = $coursecategory->id;
 222  
 223              $existinggradeitem = $DB->get_record('grade_items', (array)$gi);
 224              if (!empty($existinggradeitem)) {
 225                  $data->id = $newitemid = $existinggradeitem->id;
 226                  $DB->update_record('grade_items', $data);
 227              }
 228          } else if ($data->itemtype == 'manual') {
 229              // Manual items aren't assigned to a cm, so don't go duplicating them in the target if one exists.
 230              $gi = array(
 231                  'itemtype' => $data->itemtype,
 232                  'courseid' => $data->courseid,
 233                  'itemname' => $data->itemname,
 234                  'categoryid' => $data->categoryid,
 235              );
 236              $newitemid = $DB->get_field('grade_items', 'id', $gi);
 237          }
 238  
 239          if (empty($newitemid)) {
 240              //in case we found the course category but still need to insert the course grade item
 241              if ($data->itemtype=='course' && !empty($coursecategory)) {
 242                  $data->iteminstance = $coursecategory->id;
 243              }
 244  
 245              $newitemid = $DB->insert_record('grade_items', $data);
 246              $data->id = $newitemid;
 247              $gradeitem = new grade_item($data);
 248              core\event\grade_item_created::create_from_grade_item($gradeitem)->trigger();
 249          }
 250          $this->set_mapping('grade_item', $oldid, $newitemid);
 251      }
 252  
 253      protected function process_grade_grade($data) {
 254          global $DB;
 255  
 256          $data = (object)$data;
 257          $oldid = $data->id;
 258          $olduserid = $data->userid;
 259  
 260          $data->itemid = $this->get_new_parentid('grade_item');
 261  
 262          $data->userid = $this->get_mappingid('user', $data->userid, null);
 263          if (!empty($data->userid)) {
 264              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
 265              $data->locktime     = $this->apply_date_offset($data->locktime);
 266  
 267              $gradeexists = $DB->record_exists('grade_grades', array('userid' => $data->userid, 'itemid' => $data->itemid));
 268              if ($gradeexists) {
 269                  $message = "User id '{$data->userid}' already has a grade entry for grade item id '{$data->itemid}'";
 270                  $this->log($message, backup::LOG_DEBUG);
 271              } else {
 272                  $newitemid = $DB->insert_record('grade_grades', $data);
 273                  $this->set_mapping('grade_grades', $oldid, $newitemid);
 274              }
 275          } else {
 276              $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
 277              $this->log($message, backup::LOG_DEBUG);
 278          }
 279      }
 280  
 281      protected function process_grade_category($data) {
 282          global $DB;
 283  
 284          $data = (object)$data;
 285          $oldid = $data->id;
 286  
 287          $data->course = $this->get_courseid();
 288          $data->courseid = $data->course;
 289  
 290          $newitemid = null;
 291          //no parent means a course level grade category. That may have been created when the course was created
 292          if(empty($data->parent)) {
 293              //parent was being saved as 0 when it should be null
 294              $data->parent = null;
 295  
 296              //get the already created course level grade category
 297              $category = new stdclass();
 298              $category->courseid = $this->get_courseid();
 299              $category->parent = null;
 300  
 301              $coursecategory = $DB->get_record('grade_categories', (array)$category);
 302              if (!empty($coursecategory)) {
 303                  $data->id = $newitemid = $coursecategory->id;
 304                  $DB->update_record('grade_categories', $data);
 305              }
 306          }
 307  
 308          // Add a warning about a removed setting.
 309          if (!empty($data->aggregatesubcats)) {
 310              set_config('show_aggregatesubcats_upgrade_' . $data->courseid, 1);
 311          }
 312  
 313          //need to insert a course category
 314          if (empty($newitemid)) {
 315              $newitemid = $DB->insert_record('grade_categories', $data);
 316          }
 317          $this->set_mapping('grade_category', $oldid, $newitemid);
 318      }
 319      protected function process_grade_letter($data) {
 320          global $DB;
 321  
 322          $data = (object)$data;
 323          $oldid = $data->id;
 324  
 325          $data->contextid = context_course::instance($this->get_courseid())->id;
 326  
 327          $gradeletter = (array)$data;
 328          unset($gradeletter['id']);
 329          if (!$DB->record_exists('grade_letters', $gradeletter)) {
 330              $newitemid = $DB->insert_record('grade_letters', $data);
 331          } else {
 332              $newitemid = $data->id;
 333          }
 334  
 335          $this->set_mapping('grade_letter', $oldid, $newitemid);
 336      }
 337      protected function process_grade_setting($data) {
 338          global $DB;
 339  
 340          $data = (object)$data;
 341          $oldid = $data->id;
 342  
 343          $data->courseid = $this->get_courseid();
 344  
 345          $target = $this->get_task()->get_target();
 346          if ($data->name == 'minmaxtouse' &&
 347                  ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING)) {
 348              // We never restore minmaxtouse during merge.
 349              return;
 350          }
 351  
 352          if (!$DB->record_exists('grade_settings', array('courseid' => $data->courseid, 'name' => $data->name))) {
 353              $newitemid = $DB->insert_record('grade_settings', $data);
 354          } else {
 355              $newitemid = $data->id;
 356          }
 357  
 358          if (!empty($oldid)) {
 359              // In rare cases (minmaxtouse), it is possible that there wasn't any ID associated with the setting.
 360              $this->set_mapping('grade_setting', $oldid, $newitemid);
 361          }
 362      }
 363  
 364      /**
 365       * put all activity grade items in the correct grade category and mark all for recalculation
 366       */
 367      protected function after_execute() {
 368          global $DB;
 369  
 370          $conditions = array(
 371              'backupid' => $this->get_restoreid(),
 372              'itemname' => 'grade_item'//,
 373              //'itemid'   => $itemid
 374          );
 375          $rs = $DB->get_recordset('backup_ids_temp', $conditions);
 376  
 377          // We need this for calculation magic later on.
 378          $mappings = array();
 379  
 380          if (!empty($rs)) {
 381              foreach($rs as $grade_item_backup) {
 382  
 383                  // Store the oldid with the new id.
 384                  $mappings[$grade_item_backup->itemid] = $grade_item_backup->newitemid;
 385  
 386                  $updateobj = new stdclass();
 387                  $updateobj->id = $grade_item_backup->newitemid;
 388  
 389                  //if this is an activity grade item that needs to be put back in its correct category
 390                  if (!empty($grade_item_backup->parentitemid)) {
 391                      $oldcategoryid = $this->get_mappingid('grade_category', $grade_item_backup->parentitemid, null);
 392                      if (!is_null($oldcategoryid)) {
 393                          $updateobj->categoryid = $oldcategoryid;
 394                          $DB->update_record('grade_items', $updateobj);
 395                      }
 396                  } else {
 397                      //mark course and category items as needing to be recalculated
 398                      $updateobj->needsupdate=1;
 399                      $DB->update_record('grade_items', $updateobj);
 400                  }
 401              }
 402          }
 403          $rs->close();
 404  
 405          // We need to update the calculations for calculated grade items that may reference old
 406          // grade item ids using ##gi\d+##.
 407          // $mappings can be empty, use 0 if so (won't match ever)
 408          list($sql, $params) = $DB->get_in_or_equal(array_values($mappings), SQL_PARAMS_NAMED, 'param', true, 0);
 409          $sql = "SELECT gi.id, gi.calculation
 410                    FROM {grade_items} gi
 411                   WHERE gi.id {$sql} AND
 412                         calculation IS NOT NULL";
 413          $rs = $DB->get_recordset_sql($sql, $params);
 414          foreach ($rs as $gradeitem) {
 415              // Collect all of the used grade item id references
 416              if (preg_match_all('/##gi(\d+)##/', $gradeitem->calculation, $matches) < 1) {
 417                  // This calculation doesn't reference any other grade items... EASY!
 418                  continue;
 419              }
 420              // For this next bit we are going to do the replacement of id's in two steps:
 421              // 1. We will replace all old id references with a special mapping reference.
 422              // 2. We will replace all mapping references with id's
 423              // Why do we do this?
 424              // Because there potentially there will be an overlap of ids within the query and we
 425              // we substitute the wrong id.. safest way around this is the two step system
 426              $calculationmap = array();
 427              $mapcount = 0;
 428              foreach ($matches[1] as $match) {
 429                  // Check that the old id is known to us, if not it was broken to begin with and will
 430                  // continue to be broken.
 431                  if (!array_key_exists($match, $mappings)) {
 432                      continue;
 433                  }
 434                  // Our special mapping key
 435                  $mapping = '##MAPPING'.$mapcount.'##';
 436                  // The old id that exists within the calculation now
 437                  $oldid = '##gi'.$match.'##';
 438                  // The new id that we want to replace the old one with.
 439                  $newid = '##gi'.$mappings[$match].'##';
 440                  // Replace in the special mapping key
 441                  $gradeitem->calculation = str_replace($oldid, $mapping, $gradeitem->calculation);
 442                  // And record the mapping
 443                  $calculationmap[$mapping] = $newid;
 444                  $mapcount++;
 445              }
 446              // Iterate all special mappings for this calculation and replace in the new id's
 447              foreach ($calculationmap as $mapping => $newid) {
 448                  $gradeitem->calculation = str_replace($mapping, $newid, $gradeitem->calculation);
 449              }
 450              // Update the calculation now that its being remapped
 451              $DB->update_record('grade_items', $gradeitem);
 452          }
 453          $rs->close();
 454  
 455          // Need to correct the grade category path and parent
 456          $conditions = array(
 457              'courseid' => $this->get_courseid()
 458          );
 459  
 460          $rs = $DB->get_recordset('grade_categories', $conditions);
 461          // Get all the parents correct first as grade_category::build_path() loads category parents from the DB
 462          foreach ($rs as $gc) {
 463              if (!empty($gc->parent)) {
 464                  $grade_category = new stdClass();
 465                  $grade_category->id = $gc->id;
 466                  $grade_category->parent = $this->get_mappingid('grade_category', $gc->parent);
 467                  $DB->update_record('grade_categories', $grade_category);
 468              }
 469          }
 470          $rs->close();
 471  
 472          // Now we can rebuild all the paths
 473          $rs = $DB->get_recordset('grade_categories', $conditions);
 474          foreach ($rs as $gc) {
 475              $grade_category = new stdClass();
 476              $grade_category->id = $gc->id;
 477              $grade_category->path = grade_category::build_path($gc);
 478              $grade_category->depth = substr_count($grade_category->path, '/') - 1;
 479              $DB->update_record('grade_categories', $grade_category);
 480          }
 481          $rs->close();
 482  
 483          // Check what to do with the minmaxtouse setting.
 484          $this->check_minmaxtouse();
 485  
 486          // Freeze gradebook calculations if needed.
 487          $this->gradebook_calculation_freeze();
 488  
 489          // Ensure the module cache is current when recalculating grades.
 490          rebuild_course_cache($this->get_courseid(), true);
 491  
 492          // Restore marks items as needing update. Update everything now.
 493          grade_regrade_final_grades($this->get_courseid());
 494      }
 495  
 496      /**
 497       * Freeze gradebook calculation if needed.
 498       *
 499       * This is similar to various upgrade scripts that check if the freeze is needed.
 500       */
 501      protected function gradebook_calculation_freeze() {
 502          global $CFG;
 503          $gradebookcalculationsfreeze = get_config('core', 'gradebook_calculations_freeze_' . $this->get_courseid());
 504          $restoretask = $this->get_task();
 505  
 506          // Extra credits need adjustments only for backups made between 2.8 release (20141110) and the fix release (20150619).
 507          if (!$gradebookcalculationsfreeze && $restoretask->backup_version_compare(20141110, '>=')
 508                  && $restoretask->backup_version_compare(20150619, '<')) {
 509              require_once($CFG->libdir . '/db/upgradelib.php');
 510              upgrade_extra_credit_weightoverride($this->get_courseid());
 511          }
 512          // Calculated grade items need recalculating for backups made between 2.8 release (20141110) and the fix release (20150627).
 513          if (!$gradebookcalculationsfreeze && $restoretask->backup_version_compare(20141110, '>=')
 514                  && $restoretask->backup_version_compare(20150627, '<')) {
 515              require_once($CFG->libdir . '/db/upgradelib.php');
 516              upgrade_calculated_grade_items($this->get_courseid());
 517          }
 518          // Courses from before 3.1 (20160518) may have a letter boundary problem and should be checked for this issue.
 519          // Backups from before and including 2.9 could have a build number that is greater than 20160518 and should
 520          // be checked for this problem.
 521          if (!$gradebookcalculationsfreeze
 522                  && ($restoretask->backup_version_compare(20160518, '<') || $restoretask->backup_release_compare('2.9', '<='))) {
 523              require_once($CFG->libdir . '/db/upgradelib.php');
 524              upgrade_course_letter_boundary($this->get_courseid());
 525          }
 526  
 527      }
 528  
 529      /**
 530       * Checks what should happen with the course grade setting minmaxtouse.
 531       *
 532       * This is related to the upgrade step at the time the setting was added.
 533       *
 534       * @see MDL-48618
 535       * @return void
 536       */
 537      protected function check_minmaxtouse() {
 538          global $CFG, $DB;
 539          require_once($CFG->libdir . '/gradelib.php');
 540  
 541          $userinfo = $this->task->get_setting_value('users');
 542          $settingname = 'minmaxtouse';
 543          $courseid = $this->get_courseid();
 544          $minmaxtouse = $DB->get_field('grade_settings', 'value', array('courseid' => $courseid, 'name' => $settingname));
 545          $version28start = 2014111000.00;
 546          $version28last = 2014111006.05;
 547          $version29start = 2015051100.00;
 548          $version29last = 2015060400.02;
 549  
 550          $target = $this->get_task()->get_target();
 551          if ($minmaxtouse === false &&
 552                  ($target != backup::TARGET_CURRENT_ADDING && $target != backup::TARGET_EXISTING_ADDING)) {
 553              // The setting was not found because this setting did not exist at the time the backup was made.
 554              // And we are not restoring as merge, in which case we leave the course as it was.
 555              $version = $this->get_task()->get_info()->moodle_version;
 556  
 557              if ($version < $version28start) {
 558                  // We need to set it to use grade_item, but only if the site-wide setting is different. No need to notice them.
 559                  if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_ITEM) {
 560                      grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_ITEM);
 561                  }
 562  
 563              } else if (($version >= $version28start && $version < $version28last) ||
 564                      ($version >= $version29start && $version < $version29last)) {
 565                  // They should be using grade_grade when the course has inconsistencies.
 566  
 567                  $sql = "SELECT gi.id
 568                            FROM {grade_items} gi
 569                            JOIN {grade_grades} gg
 570                              ON gg.itemid = gi.id
 571                           WHERE gi.courseid = ?
 572                             AND (gi.itemtype != ? AND gi.itemtype != ?)
 573                             AND (gg.rawgrademax != gi.grademax OR gg.rawgrademin != gi.grademin)";
 574  
 575                  // The course can only have inconsistencies when we restore the user info,
 576                  // we do not need to act on existing grades that were not restored as part of this backup.
 577                  if ($userinfo && $DB->record_exists_sql($sql, array($courseid, 'course', 'category'))) {
 578  
 579                      // Display the notice as we do during upgrade.
 580                      set_config('show_min_max_grades_changed_' . $courseid, 1);
 581  
 582                      if ($CFG->grade_minmaxtouse != GRADE_MIN_MAX_FROM_GRADE_GRADE) {
 583                          // We need set the setting as their site-wise setting is not GRADE_MIN_MAX_FROM_GRADE_GRADE.
 584                          // If they are using the site-wide grade_grade setting, we only want to notice them.
 585                          grade_set_setting($courseid, $settingname, GRADE_MIN_MAX_FROM_GRADE_GRADE);
 586                      }
 587                  }
 588  
 589              } else {
 590                  // This should never happen because from now on minmaxtouse is always saved in backups.
 591              }
 592          }
 593      }
 594  
 595      /**
 596       * Rewrite step definition to handle the legacy freeze attribute.
 597       *
 598       * In previous backups the calculations_freeze property was stored as an attribute of the
 599       * top level node <gradebook>. The backup API, however, do not process grandparent nodes.
 600       * It only processes definitive children, and their parent attributes.
 601       *
 602       * We had:
 603       *
 604       * <gradebook calculations_freeze="20160511">
 605       *   <grade_categories>
 606       *     <grade_category id="10">
 607       *       <depth>1</depth>
 608       *       ...
 609       *     </grade_category>
 610       *   </grade_categories>
 611       *   ...
 612       * </gradebook>
 613       *
 614       * And this method will convert it to:
 615       *
 616       * <gradebook >
 617       *   <attributes>
 618       *     <calculations_freeze>20160511</calculations_freeze>
 619       *   </attributes>
 620       *   <grade_categories>
 621       *     <grade_category id="10">
 622       *       <depth>1</depth>
 623       *       ...
 624       *     </grade_category>
 625       *   </grade_categories>
 626       *   ...
 627       * </gradebook>
 628       *
 629       * Note that we cannot just load the XML file in memory as it could potentially be huge.
 630       * We can also completely ignore if the node <attributes> is already in the backup
 631       * file as it never existed before.
 632       *
 633       * @param string $filepath The absolute path to the XML file.
 634       * @return void
 635       */
 636      protected function rewrite_step_backup_file_for_legacy_freeze($filepath) {
 637          $foundnode = false;
 638          $newfile = make_request_directory(true) . DIRECTORY_SEPARATOR . 'file.xml';
 639          $fr = fopen($filepath, 'r');
 640          $fw = fopen($newfile, 'w');
 641          if ($fr && $fw) {
 642              while (($line = fgets($fr, 4096)) !== false) {
 643                  if (!$foundnode && strpos($line, '<gradebook ') === 0) {
 644                      $foundnode = true;
 645                      $matches = array();
 646                      $pattern = '@calculations_freeze=.([0-9]+).@';
 647                      if (preg_match($pattern, $line, $matches)) {
 648                          $freeze = $matches[1];
 649                          $line = preg_replace($pattern, '', $line);
 650                          $line .= "  <attributes>\n    <calculations_freeze>$freeze</calculations_freeze>\n  </attributes>\n";
 651                      }
 652                  }
 653                  fputs($fw, $line);
 654              }
 655              if (!feof($fr)) {
 656                  throw new restore_step_exception('Error while attempting to rewrite the gradebook step file.');
 657              }
 658              fclose($fr);
 659              fclose($fw);
 660              if (!rename($newfile, $filepath)) {
 661                  throw new restore_step_exception('Error while attempting to rename the gradebook step file.');
 662              }
 663          } else {
 664              if ($fr) {
 665                  fclose($fr);
 666              }
 667              if ($fw) {
 668                  fclose($fw);
 669              }
 670          }
 671      }
 672  
 673  }
 674  
 675  /**
 676   * Step in charge of restoring the grade history of a course.
 677   *
 678   * The execution conditions are itendical to {@link restore_gradebook_structure_step} because
 679   * we do not want to restore the history if the gradebook and its content has not been
 680   * restored. At least for now.
 681   */
 682  class restore_grade_history_structure_step extends restore_structure_step {
 683  
 684       protected function execute_condition() {
 685          global $CFG, $DB;
 686  
 687          if ($this->get_courseid() == SITEID) {
 688              return false;
 689          }
 690  
 691          // No gradebook info found, don't execute.
 692          $fullpath = $this->task->get_taskbasepath();
 693          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
 694          if (!file_exists($fullpath)) {
 695              return false;
 696          }
 697  
 698          // Some module present in backup file isn't available to restore in this site, don't execute.
 699          if ($this->task->is_missing_modules()) {
 700              return false;
 701          }
 702  
 703          // Some activity has been excluded to be restored, don't execute.
 704          if ($this->task->is_excluding_activities()) {
 705              return false;
 706          }
 707  
 708          // There should only be one grade category (the 1 associated with the course itself).
 709          $category = new stdclass();
 710          $category->courseid  = $this->get_courseid();
 711          $catcount = $DB->count_records('grade_categories', (array)$category);
 712          if ($catcount > 1) {
 713              return false;
 714          }
 715  
 716          // Arrived here, execute the step.
 717          return true;
 718       }
 719  
 720      protected function define_structure() {
 721          $paths = array();
 722  
 723          // Settings to use.
 724          $userinfo = $this->get_setting_value('users');
 725          $history = $this->get_setting_value('grade_histories');
 726  
 727          if ($userinfo && $history) {
 728              $paths[] = new restore_path_element('grade_grade',
 729                 '/grade_history/grade_grades/grade_grade');
 730          }
 731  
 732          return $paths;
 733      }
 734  
 735      protected function process_grade_grade($data) {
 736          global $DB;
 737  
 738          $data = (object)($data);
 739          $olduserid = $data->userid;
 740          unset($data->id);
 741  
 742          $data->userid = $this->get_mappingid('user', $data->userid, null);
 743          if (!empty($data->userid)) {
 744              // Do not apply the date offsets as this is history.
 745              $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
 746              $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
 747              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
 748              $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
 749              $DB->insert_record('grade_grades_history', $data);
 750          } else {
 751              $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
 752              $this->log($message, backup::LOG_DEBUG);
 753          }
 754      }
 755  
 756  }
 757  
 758  /**
 759   * decode all the interlinks present in restored content
 760   * relying 100% in the restore_decode_processor that handles
 761   * both the contents to modify and the rules to be applied
 762   */
 763  class restore_decode_interlinks extends restore_execution_step {
 764  
 765      protected function define_execution() {
 766          // Get the decoder (from the plan)
 767          /** @var restore_decode_processor $decoder */
 768          $decoder = $this->task->get_decoder();
 769          restore_decode_processor::register_link_decoders($decoder); // Add decoder contents and rules
 770          // And launch it, everything will be processed
 771          $decoder->execute();
 772      }
 773  }
 774  
 775  /**
 776   * first, ensure that we have no gaps in section numbers
 777   * and then, rebuid the course cache
 778   */
 779  class restore_rebuild_course_cache extends restore_execution_step {
 780  
 781      protected function define_execution() {
 782          global $DB;
 783  
 784          // Although there is some sort of auto-recovery of missing sections
 785          // present in course/formats... here we check that all the sections
 786          // from 0 to MAX(section->section) exist, creating them if necessary
 787          $maxsection = $DB->get_field('course_sections', 'MAX(section)', array('course' => $this->get_courseid()));
 788          // Iterate over all sections
 789          for ($i = 0; $i <= $maxsection; $i++) {
 790              // If the section $i doesn't exist, create it
 791              if (!$DB->record_exists('course_sections', array('course' => $this->get_courseid(), 'section' => $i))) {
 792                  $sectionrec = array(
 793                      'course' => $this->get_courseid(),
 794                      'section' => $i,
 795                      'timemodified' => time());
 796                  $DB->insert_record('course_sections', $sectionrec); // missing section created
 797              }
 798          }
 799  
 800          // Rebuild cache now that all sections are in place
 801          rebuild_course_cache($this->get_courseid());
 802          cache_helper::purge_by_event('changesincourse');
 803          cache_helper::purge_by_event('changesincoursecat');
 804      }
 805  }
 806  
 807  /**
 808   * Review all the tasks having one after_restore method
 809   * executing it to perform some final adjustments of information
 810   * not available when the task was executed.
 811   */
 812  class restore_execute_after_restore extends restore_execution_step {
 813  
 814      protected function define_execution() {
 815  
 816          // Simply call to the execute_after_restore() method of the task
 817          // that always is the restore_final_task
 818          $this->task->launch_execute_after_restore();
 819      }
 820  }
 821  
 822  
 823  /**
 824   * Review all the (pending) block positions in backup_ids, matching by
 825   * contextid, creating positions as needed. This is executed by the
 826   * final task, once all the contexts have been created
 827   */
 828  class restore_review_pending_block_positions extends restore_execution_step {
 829  
 830      protected function define_execution() {
 831          global $DB;
 832  
 833          // Get all the block_position objects pending to match
 834          $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'block_position');
 835          $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
 836          // Process block positions, creating them or accumulating for final step
 837          foreach($rs as $posrec) {
 838              // Get the complete position object out of the info field.
 839              $position = backup_controller_dbops::decode_backup_temp_info($posrec->info);
 840              // If position is for one already mapped (known) contextid
 841              // process it now, creating the position, else nothing to
 842              // do, position finally discarded
 843              if ($newctx = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $position->contextid)) {
 844                  $position->contextid = $newctx->newitemid;
 845                  // Create the block position
 846                  $DB->insert_record('block_positions', $position);
 847              }
 848          }
 849          $rs->close();
 850      }
 851  }
 852  
 853  
 854  /**
 855   * Updates the availability data for course modules and sections.
 856   *
 857   * Runs after the restore of all course modules, sections, and grade items has
 858   * completed. This is necessary in order to update IDs that have changed during
 859   * restore.
 860   *
 861   * @package core_backup
 862   * @copyright 2014 The Open University
 863   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 864   */
 865  class restore_update_availability extends restore_execution_step {
 866  
 867      protected function define_execution() {
 868          global $CFG, $DB;
 869  
 870          // Note: This code runs even if availability is disabled when restoring.
 871          // That will ensure that if you later turn availability on for the site,
 872          // there will be no incorrect IDs. (It doesn't take long if the restored
 873          // data does not contain any availability information.)
 874  
 875          // Get modinfo with all data after resetting cache.
 876          rebuild_course_cache($this->get_courseid(), true);
 877          $modinfo = get_fast_modinfo($this->get_courseid());
 878  
 879          // Get the date offset for this restore.
 880          $dateoffset = $this->apply_date_offset(1) - 1;
 881  
 882          // Update all sections that were restored.
 883          $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_section');
 884          $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
 885          $sectionsbyid = null;
 886          foreach ($rs as $rec) {
 887              if (is_null($sectionsbyid)) {
 888                  $sectionsbyid = array();
 889                  foreach ($modinfo->get_section_info_all() as $section) {
 890                      $sectionsbyid[$section->id] = $section;
 891                  }
 892              }
 893              if (!array_key_exists($rec->newitemid, $sectionsbyid)) {
 894                  // If the section was not fully restored for some reason
 895                  // (e.g. due to an earlier error), skip it.
 896                  $this->get_logger()->process('Section not fully restored: id ' .
 897                          $rec->newitemid, backup::LOG_WARNING);
 898                  continue;
 899              }
 900              $section = $sectionsbyid[$rec->newitemid];
 901              if (!is_null($section->availability)) {
 902                  $info = new \core_availability\info_section($section);
 903                  $info->update_after_restore($this->get_restoreid(),
 904                          $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
 905              }
 906          }
 907          $rs->close();
 908  
 909          // Update all modules that were restored.
 910          $params = array('backupid' => $this->get_restoreid(), 'itemname' => 'course_module');
 911          $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'newitemid');
 912          foreach ($rs as $rec) {
 913              if (!array_key_exists($rec->newitemid, $modinfo->cms)) {
 914                  // If the module was not fully restored for some reason
 915                  // (e.g. due to an earlier error), skip it.
 916                  $this->get_logger()->process('Module not fully restored: id ' .
 917                          $rec->newitemid, backup::LOG_WARNING);
 918                  continue;
 919              }
 920              $cm = $modinfo->get_cm($rec->newitemid);
 921              if (!is_null($cm->availability)) {
 922                  $info = new \core_availability\info_module($cm);
 923                  $info->update_after_restore($this->get_restoreid(),
 924                          $this->get_courseid(), $this->get_logger(), $dateoffset, $this->task);
 925              }
 926          }
 927          $rs->close();
 928      }
 929  }
 930  
 931  
 932  /**
 933   * Process legacy module availability records in backup_ids.
 934   *
 935   * Matches course modules and grade item id once all them have been already restored.
 936   * Only if all matchings are satisfied the availability condition will be created.
 937   * At the same time, it is required for the site to have that functionality enabled.
 938   *
 939   * This step is included only to handle legacy backups (2.6 and before). It does not
 940   * do anything for newer backups.
 941   *
 942   * @copyright 2014 The Open University
 943   * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
 944   */
 945  class restore_process_course_modules_availability extends restore_execution_step {
 946  
 947      protected function define_execution() {
 948          global $CFG, $DB;
 949  
 950          // Site hasn't availability enabled
 951          if (empty($CFG->enableavailability)) {
 952              return;
 953          }
 954  
 955          // Do both modules and sections.
 956          foreach (array('module', 'section') as $table) {
 957              // Get all the availability objects to process.
 958              $params = array('backupid' => $this->get_restoreid(), 'itemname' => $table . '_availability');
 959              $rs = $DB->get_recordset('backup_ids_temp', $params, '', 'itemid, info');
 960              // Process availabilities, creating them if everything matches ok.
 961              foreach ($rs as $availrec) {
 962                  $allmatchesok = true;
 963                  // Get the complete legacy availability object.
 964                  $availability = backup_controller_dbops::decode_backup_temp_info($availrec->info);
 965  
 966                  // Note: This code used to update IDs, but that is now handled by the
 967                  // current code (after restore) instead of this legacy code.
 968  
 969                  // Get showavailability option.
 970                  $thingid = ($table === 'module') ? $availability->coursemoduleid :
 971                          $availability->coursesectionid;
 972                  $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
 973                          $table . '_showavailability', $thingid);
 974                  if (!$showrec) {
 975                      // Should not happen.
 976                      throw new coding_exception('No matching showavailability record');
 977                  }
 978                  $show = $showrec->info->showavailability;
 979  
 980                  // The $availability object is now in the format used in the old
 981                  // system. Interpret this and convert to new system.
 982                  $currentvalue = $DB->get_field('course_' . $table . 's', 'availability',
 983                          array('id' => $thingid), MUST_EXIST);
 984                  $newvalue = \core_availability\info::add_legacy_availability_condition(
 985                          $currentvalue, $availability, $show);
 986                  $DB->set_field('course_' . $table . 's', 'availability', $newvalue,
 987                          array('id' => $thingid));
 988              }
 989              $rs->close();
 990          }
 991      }
 992  }
 993  
 994  
 995  /*
 996   * Execution step that, *conditionally* (if there isn't preloaded information)
 997   * will load the inforef files for all the included course/section/activity tasks
 998   * to backup_temp_ids. They will be stored with "xxxxref" as itemname
 999   */
1000  class restore_load_included_inforef_records extends restore_execution_step {
1001  
1002      protected function define_execution() {
1003  
1004          if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1005              return;
1006          }
1007  
1008          // Get all the included tasks
1009          $tasks = restore_dbops::get_included_tasks($this->get_restoreid());
1010          $progress = $this->task->get_progress();
1011          $progress->start_progress($this->get_name(), count($tasks));
1012          foreach ($tasks as $task) {
1013              // Load the inforef.xml file if exists
1014              $inforefpath = $task->get_taskbasepath() . '/inforef.xml';
1015              if (file_exists($inforefpath)) {
1016                  // Load each inforef file to temp_ids.
1017                  restore_dbops::load_inforef_to_tempids($this->get_restoreid(), $inforefpath, $progress);
1018              }
1019          }
1020          $progress->end_progress();
1021      }
1022  }
1023  
1024  /*
1025   * Execution step that will load all the needed files into backup_files_temp
1026   *   - info: contains the whole original object (times, names...)
1027   * (all them being original ids as loaded from xml)
1028   */
1029  class restore_load_included_files extends restore_structure_step {
1030  
1031      protected function define_structure() {
1032  
1033          $file = new restore_path_element('file', '/files/file');
1034  
1035          return array($file);
1036      }
1037  
1038      /**
1039       * Process one <file> element from files.xml
1040       *
1041       * @param array $data the element data
1042       */
1043      public function process_file($data) {
1044  
1045          $data = (object)$data; // handy
1046  
1047          // load it if needed:
1048          //   - it it is one of the annotated inforef files (course/section/activity/block)
1049          //   - it is one "user", "group", "grouping", "grade", "question" or "qtype_xxxx" component file (that aren't sent to inforef ever)
1050          // TODO: qtype_xxx should be replaced by proper backup_qtype_plugin::get_components_and_fileareas() use,
1051          //       but then we'll need to change it to load plugins itself (because this is executed too early in restore)
1052          $isfileref   = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'fileref', $data->id);
1053          $iscomponent = ($data->component == 'user' || $data->component == 'group' || $data->component == 'badges' ||
1054                          $data->component == 'grouping' || $data->component == 'grade' ||
1055                          $data->component == 'question' || substr($data->component, 0, 5) == 'qtype');
1056          if ($isfileref || $iscomponent) {
1057              restore_dbops::set_backup_files_record($this->get_restoreid(), $data);
1058          }
1059      }
1060  }
1061  
1062  /**
1063   * Execution step that, *conditionally* (if there isn't preloaded information),
1064   * will load all the needed roles to backup_temp_ids. They will be stored with
1065   * "role" itemname. Also it will perform one automatic mapping to roles existing
1066   * in the target site, based in permissions of the user performing the restore,
1067   * archetypes and other bits. At the end, each original role will have its associated
1068   * target role or 0 if it's going to be skipped. Note we wrap everything over one
1069   * restore_dbops method, as far as the same stuff is going to be also executed
1070   * by restore prechecks
1071   */
1072  class restore_load_and_map_roles extends restore_execution_step {
1073  
1074      protected function define_execution() {
1075          if ($this->task->get_preloaded_information()) { // if info is already preloaded
1076              return;
1077          }
1078  
1079          $file = $this->get_basepath() . '/roles.xml';
1080          // Load needed toles to temp_ids
1081          restore_dbops::load_roles_to_tempids($this->get_restoreid(), $file);
1082  
1083          // Process roles, mapping/skipping. Any error throws exception
1084          // Note we pass controller's info because it can contain role mapping information
1085          // about manual mappings performed by UI
1086          restore_dbops::process_included_roles($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_info()->role_mappings);
1087      }
1088  }
1089  
1090  /**
1091   * Execution step that, *conditionally* (if there isn't preloaded information
1092   * and users have been selected in settings, will load all the needed users
1093   * to backup_temp_ids. They will be stored with "user" itemname and with
1094   * their original contextid as paremitemid
1095   */
1096  class restore_load_included_users extends restore_execution_step {
1097  
1098      protected function define_execution() {
1099  
1100          if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1101              return;
1102          }
1103          if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1104              return;
1105          }
1106          $file = $this->get_basepath() . '/users.xml';
1107          // Load needed users to temp_ids.
1108          restore_dbops::load_users_to_tempids($this->get_restoreid(), $file, $this->task->get_progress());
1109      }
1110  }
1111  
1112  /**
1113   * Execution step that, *conditionally* (if there isn't preloaded information
1114   * and users have been selected in settings, will process all the needed users
1115   * in order to decide and perform any action with them (create / map / error)
1116   * Note: Any error will cause exception, as far as this is the same processing
1117   * than the one into restore prechecks (that should have stopped process earlier)
1118   */
1119  class restore_process_included_users extends restore_execution_step {
1120  
1121      protected function define_execution() {
1122  
1123          if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1124              return;
1125          }
1126          if (!$this->task->get_setting_value('users')) { // No userinfo being restored, nothing to do
1127              return;
1128          }
1129          restore_dbops::process_included_users($this->get_restoreid(), $this->task->get_courseid(),
1130                  $this->task->get_userid(), $this->task->is_samesite(), $this->task->get_progress());
1131      }
1132  }
1133  
1134  /**
1135   * Execution step that will create all the needed users as calculated
1136   * by @restore_process_included_users (those having newiteind = 0)
1137   */
1138  class restore_create_included_users extends restore_execution_step {
1139  
1140      protected function define_execution() {
1141  
1142          restore_dbops::create_included_users($this->get_basepath(), $this->get_restoreid(),
1143                  $this->task->get_userid(), $this->task->get_progress(), $this->task->get_courseid());
1144      }
1145  }
1146  
1147  /**
1148   * Structure step that will create all the needed groups and groupings
1149   * by loading them from the groups.xml file performing the required matches.
1150   * Note group members only will be added if restoring user info
1151   */
1152  class restore_groups_structure_step extends restore_structure_step {
1153  
1154      protected function define_structure() {
1155  
1156          $paths = array(); // Add paths here
1157  
1158          // Do not include group/groupings information if not requested.
1159          $groupinfo = $this->get_setting_value('groups');
1160          if ($groupinfo) {
1161              $paths[] = new restore_path_element('group', '/groups/group');
1162              $paths[] = new restore_path_element('grouping', '/groups/groupings/grouping');
1163              $paths[] = new restore_path_element('grouping_group', '/groups/groupings/grouping/grouping_groups/grouping_group');
1164          }
1165          return $paths;
1166      }
1167  
1168      // Processing functions go here
1169      public function process_group($data) {
1170          global $DB;
1171  
1172          $data = (object)$data; // handy
1173          $data->courseid = $this->get_courseid();
1174  
1175          // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1176          // another a group in the same course
1177          $context = context_course::instance($data->courseid);
1178          if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1179              if (groups_get_group_by_idnumber($data->courseid, $data->idnumber)) {
1180                  unset($data->idnumber);
1181              }
1182          } else {
1183              unset($data->idnumber);
1184          }
1185  
1186          $oldid = $data->id;    // need this saved for later
1187  
1188          $restorefiles = false; // Only if we end creating the group
1189  
1190          // This is for backwards compatibility with old backups. If the backup data for a group contains a non-empty value of
1191          // hidepicture, then we'll exclude this group's picture from being restored.
1192          if (!empty($data->hidepicture)) {
1193              // Exclude the group picture from being restored if hidepicture is set to 1 in the backup data.
1194              unset($data->picture);
1195          }
1196  
1197          // Search if the group already exists (by name & description) in the target course
1198          $description_clause = '';
1199          $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1200          if (!empty($data->description)) {
1201              $description_clause = ' AND ' .
1202                                    $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1203             $params['description'] = $data->description;
1204          }
1205          if (!$groupdb = $DB->get_record_sql("SELECT *
1206                                                 FROM {groups}
1207                                                WHERE courseid = :courseid
1208                                                  AND name = :grname $description_clause", $params)) {
1209              // group doesn't exist, create
1210              $newitemid = $DB->insert_record('groups', $data);
1211              $restorefiles = true; // We'll restore the files
1212          } else {
1213              // group exists, use it
1214              $newitemid = $groupdb->id;
1215          }
1216          // Save the id mapping
1217          $this->set_mapping('group', $oldid, $newitemid, $restorefiles);
1218  
1219          // Add the related group picture file if it's available at this point.
1220          if (!empty($data->picture)) {
1221              $this->add_related_files('group', 'icon', 'group', null, $oldid);
1222          }
1223  
1224          // Invalidate the course group data cache just in case.
1225          cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1226      }
1227  
1228      public function process_grouping($data) {
1229          global $DB;
1230  
1231          $data = (object)$data; // handy
1232          $data->courseid = $this->get_courseid();
1233  
1234          // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1235          // another a grouping in the same course
1236          $context = context_course::instance($data->courseid);
1237          if (isset($data->idnumber) and has_capability('moodle/course:changeidnumber', $context, $this->task->get_userid())) {
1238              if (groups_get_grouping_by_idnumber($data->courseid, $data->idnumber)) {
1239                  unset($data->idnumber);
1240              }
1241          } else {
1242              unset($data->idnumber);
1243          }
1244  
1245          $oldid = $data->id;    // need this saved for later
1246          $restorefiles = false; // Only if we end creating the grouping
1247  
1248          // Search if the grouping already exists (by name & description) in the target course
1249          $description_clause = '';
1250          $params = array('courseid' => $this->get_courseid(), 'grname' => $data->name);
1251          if (!empty($data->description)) {
1252              $description_clause = ' AND ' .
1253                                    $DB->sql_compare_text('description') . ' = ' . $DB->sql_compare_text(':description');
1254             $params['description'] = $data->description;
1255          }
1256          if (!$groupingdb = $DB->get_record_sql("SELECT *
1257                                                    FROM {groupings}
1258                                                   WHERE courseid = :courseid
1259                                                     AND name = :grname $description_clause", $params)) {
1260              // grouping doesn't exist, create
1261              $newitemid = $DB->insert_record('groupings', $data);
1262              $restorefiles = true; // We'll restore the files
1263          } else {
1264              // grouping exists, use it
1265              $newitemid = $groupingdb->id;
1266          }
1267          // Save the id mapping
1268          $this->set_mapping('grouping', $oldid, $newitemid, $restorefiles);
1269          // Invalidate the course group data cache just in case.
1270          cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($data->courseid));
1271      }
1272  
1273      public function process_grouping_group($data) {
1274          global $CFG;
1275  
1276          require_once($CFG->dirroot.'/group/lib.php');
1277  
1278          $data = (object)$data;
1279          groups_assign_grouping($this->get_new_parentid('grouping'), $this->get_mappingid('group', $data->groupid), $data->timeadded);
1280      }
1281  
1282      protected function after_execute() {
1283          // Add group related files, matching with "group" mappings.
1284          $this->add_related_files('group', 'description', 'group');
1285          // Add grouping related files, matching with "grouping" mappings
1286          $this->add_related_files('grouping', 'description', 'grouping');
1287          // Invalidate the course group data.
1288          cache_helper::invalidate_by_definition('core', 'groupdata', array(), array($this->get_courseid()));
1289      }
1290  
1291  }
1292  
1293  /**
1294   * Structure step that will create all the needed group memberships
1295   * by loading them from the groups.xml file performing the required matches.
1296   */
1297  class restore_groups_members_structure_step extends restore_structure_step {
1298  
1299      protected $plugins = null;
1300  
1301      protected function define_structure() {
1302  
1303          $paths = array(); // Add paths here
1304  
1305          if ($this->get_setting_value('groups') && $this->get_setting_value('users')) {
1306              $paths[] = new restore_path_element('group', '/groups/group');
1307              $paths[] = new restore_path_element('member', '/groups/group/group_members/group_member');
1308          }
1309  
1310          return $paths;
1311      }
1312  
1313      public function process_group($data) {
1314          $data = (object)$data; // handy
1315  
1316          // HACK ALERT!
1317          // Not much to do here, this groups mapping should be already done from restore_groups_structure_step.
1318          // Let's fake internal state to make $this->get_new_parentid('group') work.
1319  
1320          $this->set_mapping('group', $data->id, $this->get_mappingid('group', $data->id));
1321      }
1322  
1323      public function process_member($data) {
1324          global $DB, $CFG;
1325          require_once("$CFG->dirroot/group/lib.php");
1326  
1327          // NOTE: Always use groups_add_member() because it triggers events and verifies if user is enrolled.
1328  
1329          $data = (object)$data; // handy
1330  
1331          // get parent group->id
1332          $data->groupid = $this->get_new_parentid('group');
1333  
1334          // map user newitemid and insert if not member already
1335          if ($data->userid = $this->get_mappingid('user', $data->userid)) {
1336              if (!$DB->record_exists('groups_members', array('groupid' => $data->groupid, 'userid' => $data->userid))) {
1337                  // Check the component, if any, exists.
1338                  if (empty($data->component)) {
1339                      groups_add_member($data->groupid, $data->userid);
1340  
1341                  } else if ((strpos($data->component, 'enrol_') === 0)) {
1342                      // Deal with enrolment groups - ignore the component and just find out the instance via new id,
1343                      // it is possible that enrolment was restored using different plugin type.
1344                      if (!isset($this->plugins)) {
1345                          $this->plugins = enrol_get_plugins(true);
1346                      }
1347                      if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
1348                          if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
1349                              if (isset($this->plugins[$instance->enrol])) {
1350                                  $this->plugins[$instance->enrol]->restore_group_member($instance, $data->groupid, $data->userid);
1351                              }
1352                          }
1353                      }
1354  
1355                  } else {
1356                      $dir = core_component::get_component_directory($data->component);
1357                      if ($dir and is_dir($dir)) {
1358                          if (component_callback($data->component, 'restore_group_member', array($this, $data), true)) {
1359                              return;
1360                          }
1361                      }
1362                      // Bad luck, plugin could not restore the data, let's add normal membership.
1363                      groups_add_member($data->groupid, $data->userid);
1364                      $message = "Restore of '$data->component/$data->itemid' group membership is not supported, using standard group membership instead.";
1365                      $this->log($message, backup::LOG_WARNING);
1366                  }
1367              }
1368          }
1369      }
1370  }
1371  
1372  /**
1373   * Structure step that will create all the needed scales
1374   * by loading them from the scales.xml
1375   */
1376  class restore_scales_structure_step extends restore_structure_step {
1377  
1378      protected function define_structure() {
1379  
1380          $paths = array(); // Add paths here
1381          $paths[] = new restore_path_element('scale', '/scales_definition/scale');
1382          return $paths;
1383      }
1384  
1385      protected function process_scale($data) {
1386          global $DB;
1387  
1388          $data = (object)$data;
1389  
1390          $restorefiles = false; // Only if we end creating the group
1391  
1392          $oldid = $data->id;    // need this saved for later
1393  
1394          // Look for scale (by 'scale' both in standard (course=0) and current course
1395          // with priority to standard scales (ORDER clause)
1396          // scale is not course unique, use get_record_sql to suppress warning
1397          // Going to compare LOB columns so, use the cross-db sql_compare_text() in both sides
1398          $compare_scale_clause = $DB->sql_compare_text('scale')  . ' = ' . $DB->sql_compare_text(':scaledesc');
1399          $params = array('courseid' => $this->get_courseid(), 'scaledesc' => $data->scale);
1400          if (!$scadb = $DB->get_record_sql("SELECT *
1401                                              FROM {scale}
1402                                             WHERE courseid IN (0, :courseid)
1403                                               AND $compare_scale_clause
1404                                          ORDER BY courseid", $params, IGNORE_MULTIPLE)) {
1405              // Remap the user if possible, defaut to user performing the restore if not
1406              $userid = $this->get_mappingid('user', $data->userid);
1407              $data->userid = $userid ? $userid : $this->task->get_userid();
1408              // Remap the course if course scale
1409              $data->courseid = $data->courseid ? $this->get_courseid() : 0;
1410              // If global scale (course=0), check the user has perms to create it
1411              // falling to course scale if not
1412              $systemctx = context_system::instance();
1413              if ($data->courseid == 0 && !has_capability('moodle/course:managescales', $systemctx , $this->task->get_userid())) {
1414                  $data->courseid = $this->get_courseid();
1415              }
1416              // scale doesn't exist, create
1417              $newitemid = $DB->insert_record('scale', $data);
1418              $restorefiles = true; // We'll restore the files
1419          } else {
1420              // scale exists, use it
1421              $newitemid = $scadb->id;
1422          }
1423          // Save the id mapping (with files support at system context)
1424          $this->set_mapping('scale', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1425      }
1426  
1427      protected function after_execute() {
1428          // Add scales related files, matching with "scale" mappings
1429          $this->add_related_files('grade', 'scale', 'scale', $this->task->get_old_system_contextid());
1430      }
1431  }
1432  
1433  
1434  /**
1435   * Structure step that will create all the needed outocomes
1436   * by loading them from the outcomes.xml
1437   */
1438  class restore_outcomes_structure_step extends restore_structure_step {
1439  
1440      protected function define_structure() {
1441  
1442          $paths = array(); // Add paths here
1443          $paths[] = new restore_path_element('outcome', '/outcomes_definition/outcome');
1444          return $paths;
1445      }
1446  
1447      protected function process_outcome($data) {
1448          global $DB;
1449  
1450          $data = (object)$data;
1451  
1452          $restorefiles = false; // Only if we end creating the group
1453  
1454          $oldid = $data->id;    // need this saved for later
1455  
1456          // Look for outcome (by shortname both in standard (courseid=null) and current course
1457          // with priority to standard outcomes (ORDER clause)
1458          // outcome is not course unique, use get_record_sql to suppress warning
1459          $params = array('courseid' => $this->get_courseid(), 'shortname' => $data->shortname);
1460          if (!$outdb = $DB->get_record_sql('SELECT *
1461                                               FROM {grade_outcomes}
1462                                              WHERE shortname = :shortname
1463                                                AND (courseid = :courseid OR courseid IS NULL)
1464                                           ORDER BY COALESCE(courseid, 0)', $params, IGNORE_MULTIPLE)) {
1465              // Remap the user
1466              $userid = $this->get_mappingid('user', $data->usermodified);
1467              $data->usermodified = $userid ? $userid : $this->task->get_userid();
1468              // Remap the scale
1469              $data->scaleid = $this->get_mappingid('scale', $data->scaleid);
1470              // Remap the course if course outcome
1471              $data->courseid = $data->courseid ? $this->get_courseid() : null;
1472              // If global outcome (course=null), check the user has perms to create it
1473              // falling to course outcome if not
1474              $systemctx = context_system::instance();
1475              if (is_null($data->courseid) && !has_capability('moodle/grade:manageoutcomes', $systemctx , $this->task->get_userid())) {
1476                  $data->courseid = $this->get_courseid();
1477              }
1478              // outcome doesn't exist, create
1479              $newitemid = $DB->insert_record('grade_outcomes', $data);
1480              $restorefiles = true; // We'll restore the files
1481          } else {
1482              // scale exists, use it
1483              $newitemid = $outdb->id;
1484          }
1485          // Set the corresponding grade_outcomes_courses record
1486          $outcourserec = new stdclass();
1487          $outcourserec->courseid  = $this->get_courseid();
1488          $outcourserec->outcomeid = $newitemid;
1489          if (!$DB->record_exists('grade_outcomes_courses', (array)$outcourserec)) {
1490              $DB->insert_record('grade_outcomes_courses', $outcourserec);
1491          }
1492          // Save the id mapping (with files support at system context)
1493          $this->set_mapping('outcome', $oldid, $newitemid, $restorefiles, $this->task->get_old_system_contextid());
1494      }
1495  
1496      protected function after_execute() {
1497          // Add outcomes related files, matching with "outcome" mappings
1498          $this->add_related_files('grade', 'outcome', 'outcome', $this->task->get_old_system_contextid());
1499      }
1500  }
1501  
1502  /**
1503   * Execution step that, *conditionally* (if there isn't preloaded information
1504   * will load all the question categories and questions (header info only)
1505   * to backup_temp_ids. They will be stored with "question_category" and
1506   * "question" itemnames and with their original contextid and question category
1507   * id as paremitemids
1508   */
1509  class restore_load_categories_and_questions extends restore_execution_step {
1510  
1511      protected function define_execution() {
1512  
1513          if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1514              return;
1515          }
1516          $file = $this->get_basepath() . '/questions.xml';
1517          restore_dbops::load_categories_and_questions_to_tempids($this->get_restoreid(), $file);
1518      }
1519  }
1520  
1521  /**
1522   * Execution step that, *conditionally* (if there isn't preloaded information)
1523   * will process all the needed categories and questions
1524   * in order to decide and perform any action with them (create / map / error)
1525   * Note: Any error will cause exception, as far as this is the same processing
1526   * than the one into restore prechecks (that should have stopped process earlier)
1527   */
1528  class restore_process_categories_and_questions extends restore_execution_step {
1529  
1530      protected function define_execution() {
1531  
1532          if ($this->task->get_preloaded_information()) { // if info is already preloaded, nothing to do
1533              return;
1534          }
1535          restore_dbops::process_categories_and_questions($this->get_restoreid(), $this->task->get_courseid(), $this->task->get_userid(), $this->task->is_samesite());
1536      }
1537  }
1538  
1539  /**
1540   * Structure step that will read the section.xml creating/updating sections
1541   * as needed, rebuilding course cache and other friends
1542   */
1543  class restore_section_structure_step extends restore_structure_step {
1544      /** @var array Cache: Array of id => course format */
1545      private static $courseformats = array();
1546  
1547      /**
1548       * Resets a static cache of course formats. Required for unit testing.
1549       */
1550      public static function reset_caches() {
1551          self::$courseformats = array();
1552      }
1553  
1554      protected function define_structure() {
1555          global $CFG;
1556  
1557          $paths = array();
1558  
1559          $section = new restore_path_element('section', '/section');
1560          $paths[] = $section;
1561          if ($CFG->enableavailability) {
1562              $paths[] = new restore_path_element('availability', '/section/availability');
1563              $paths[] = new restore_path_element('availability_field', '/section/availability_field');
1564          }
1565          $paths[] = new restore_path_element('course_format_options', '/section/course_format_options');
1566  
1567          // Apply for 'format' plugins optional paths at section level
1568          $this->add_plugin_structure('format', $section);
1569  
1570          // Apply for 'local' plugins optional paths at section level
1571          $this->add_plugin_structure('local', $section);
1572  
1573          return $paths;
1574      }
1575  
1576      public function process_section($data) {
1577          global $CFG, $DB;
1578          $data = (object)$data;
1579          $oldid = $data->id; // We'll need this later
1580  
1581          $restorefiles = false;
1582  
1583          // Look for the section
1584          $section = new stdclass();
1585          $section->course  = $this->get_courseid();
1586          $section->section = $data->number;
1587          $section->timemodified = $data->timemodified ?? 0;
1588          // Section doesn't exist, create it with all the info from backup
1589          if (!$secrec = $DB->get_record('course_sections', ['course' => $this->get_courseid(), 'section' => $data->number])) {
1590              $section->name = $data->name;
1591              $section->summary = $data->summary;
1592              $section->summaryformat = $data->summaryformat;
1593              $section->sequence = '';
1594              $section->visible = $data->visible;
1595              if (empty($CFG->enableavailability)) { // Process availability information only if enabled.
1596                  $section->availability = null;
1597              } else {
1598                  $section->availability = isset($data->availabilityjson) ? $data->availabilityjson : null;
1599                  // Include legacy [<2.7] availability data if provided.
1600                  if (is_null($section->availability)) {
1601                      $section->availability = \core_availability\info::convert_legacy_fields(
1602                              $data, true);
1603                  }
1604              }
1605              $newitemid = $DB->insert_record('course_sections', $section);
1606              $section->id = $newitemid;
1607  
1608              core\event\course_section_created::create_from_section($section)->trigger();
1609  
1610              $restorefiles = true;
1611  
1612          // Section exists, update non-empty information
1613          } else {
1614              $section->id = $secrec->id;
1615              if ((string)$secrec->name === '') {
1616                  $section->name = $data->name;
1617              }
1618              if (empty($secrec->summary)) {
1619                  $section->summary = $data->summary;
1620                  $section->summaryformat = $data->summaryformat;
1621                  $restorefiles = true;
1622              }
1623  
1624              // Don't update availability (I didn't see a useful way to define
1625              // whether existing or new one should take precedence).
1626  
1627              $DB->update_record('course_sections', $section);
1628              $newitemid = $secrec->id;
1629  
1630              // Trigger an event for course section update.
1631              $event = \core\event\course_section_updated::create(
1632                  array(
1633                      'objectid' => $section->id,
1634                      'courseid' => $section->course,
1635                      'context' => context_course::instance($section->course),
1636                      'other' => array('sectionnum' => $section->section)
1637                  )
1638              );
1639              $event->trigger();
1640          }
1641  
1642          // Annotate the section mapping, with restorefiles option if needed
1643          $this->set_mapping('course_section', $oldid, $newitemid, $restorefiles);
1644  
1645          // set the new course_section id in the task
1646          $this->task->set_sectionid($newitemid);
1647  
1648          // If there is the legacy showavailability data, store this for later use.
1649          // (This data is not present when restoring 'new' backups.)
1650          if (isset($data->showavailability)) {
1651              // Cache the showavailability flag using the backup_ids data field.
1652              restore_dbops::set_backup_ids_record($this->get_restoreid(),
1653                      'section_showavailability', $newitemid, 0, null,
1654                      (object)array('showavailability' => $data->showavailability));
1655          }
1656  
1657          // Commented out. We never modify course->numsections as far as that is used
1658          // by a lot of people to "hide" sections on purpose (so this remains as used to be in Moodle 1.x)
1659          // Note: We keep the code here, to know about and because of the possibility of making this
1660          // optional based on some setting/attribute in the future
1661          // If needed, adjust course->numsections
1662          //if ($numsections = $DB->get_field('course', 'numsections', array('id' => $this->get_courseid()))) {
1663          //    if ($numsections < $section->section) {
1664          //        $DB->set_field('course', 'numsections', $section->section, array('id' => $this->get_courseid()));
1665          //    }
1666          //}
1667      }
1668  
1669      /**
1670       * Process the legacy availability table record. This table does not exist
1671       * in Moodle 2.7+ but we still support restore.
1672       *
1673       * @param stdClass $data Record data
1674       */
1675      public function process_availability($data) {
1676          $data = (object)$data;
1677          // Simply going to store the whole availability record now, we'll process
1678          // all them later in the final task (once all activities have been restored)
1679          // Let's call the low level one to be able to store the whole object.
1680          $data->coursesectionid = $this->task->get_sectionid();
1681          restore_dbops::set_backup_ids_record($this->get_restoreid(),
1682                  'section_availability', $data->id, 0, null, $data);
1683      }
1684  
1685      /**
1686       * Process the legacy availability fields table record. This table does not
1687       * exist in Moodle 2.7+ but we still support restore.
1688       *
1689       * @param stdClass $data Record data
1690       */
1691      public function process_availability_field($data) {
1692          global $DB, $CFG;
1693          require_once($CFG->dirroot.'/user/profile/lib.php');
1694  
1695          $data = (object)$data;
1696          // Mark it is as passed by default
1697          $passed = true;
1698          $customfieldid = null;
1699  
1700          // If a customfield has been used in order to pass we must be able to match an existing
1701          // customfield by name (data->customfield) and type (data->customfieldtype)
1702          if (is_null($data->customfield) xor is_null($data->customfieldtype)) {
1703              // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
1704              // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
1705              $passed = false;
1706          } else if (!is_null($data->customfield)) {
1707              $field = profile_get_custom_field_data_by_shortname($data->customfield);
1708              $passed = $field && $field->datatype == $data->customfieldtype;
1709          }
1710  
1711          if ($passed) {
1712              // Create the object to insert into the database
1713              $availfield = new stdClass();
1714              $availfield->coursesectionid = $this->task->get_sectionid();
1715              $availfield->userfield = $data->userfield;
1716              $availfield->customfieldid = $customfieldid;
1717              $availfield->operator = $data->operator;
1718              $availfield->value = $data->value;
1719  
1720              // Get showavailability option.
1721              $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
1722                      'section_showavailability', $availfield->coursesectionid);
1723              if (!$showrec) {
1724                  // Should not happen.
1725                  throw new coding_exception('No matching showavailability record');
1726              }
1727              $show = $showrec->info->showavailability;
1728  
1729              // The $availfield object is now in the format used in the old
1730              // system. Interpret this and convert to new system.
1731              $currentvalue = $DB->get_field('course_sections', 'availability',
1732                      array('id' => $availfield->coursesectionid), MUST_EXIST);
1733              $newvalue = \core_availability\info::add_legacy_availability_field_condition(
1734                      $currentvalue, $availfield, $show);
1735  
1736              $section = new stdClass();
1737              $section->id = $availfield->coursesectionid;
1738              $section->availability = $newvalue;
1739              $section->timemodified = time();
1740              $DB->update_record('course_sections', $section);
1741          }
1742      }
1743  
1744      public function process_course_format_options($data) {
1745          global $DB;
1746          $courseid = $this->get_courseid();
1747          if (!array_key_exists($courseid, self::$courseformats)) {
1748              // It is safe to have a static cache of course formats because format can not be changed after this point.
1749              self::$courseformats[$courseid] = $DB->get_field('course', 'format', array('id' => $courseid));
1750          }
1751          $data = (array)$data;
1752          if (self::$courseformats[$courseid] === $data['format']) {
1753              // Import section format options only if both courses (the one that was backed up
1754              // and the one we are restoring into) have same formats.
1755              $params = array(
1756                  'courseid' => $this->get_courseid(),
1757                  'sectionid' => $this->task->get_sectionid(),
1758                  'format' => $data['format'],
1759                  'name' => $data['name']
1760              );
1761              if ($record = $DB->get_record('course_format_options', $params, 'id, value')) {
1762                  // Do not overwrite existing information.
1763                  $newid = $record->id;
1764              } else {
1765                  $params['value'] = $data['value'];
1766                  $newid = $DB->insert_record('course_format_options', $params);
1767              }
1768              $this->set_mapping('course_format_options', $data['id'], $newid);
1769          }
1770      }
1771  
1772      protected function after_execute() {
1773          // Add section related files, with 'course_section' itemid to match
1774          $this->add_related_files('course', 'section', 'course_section');
1775      }
1776  }
1777  
1778  /**
1779   * Structure step that will read the course.xml file, loading it and performing
1780   * various actions depending of the site/restore settings. Note that target
1781   * course always exist before arriving here so this step will be updating
1782   * the course record (never inserting)
1783   */
1784  class restore_course_structure_step extends restore_structure_step {
1785      /**
1786       * @var bool this gets set to true by {@link process_course()} if we are
1787       * restoring an old coures that used the legacy 'module security' feature.
1788       * If so, we have to do more work in {@link after_execute()}.
1789       */
1790      protected $legacyrestrictmodules = false;
1791  
1792      /**
1793       * @var array Used when {@link $legacyrestrictmodules} is true. This is an
1794       * array with array keys the module names ('forum', 'quiz', etc.). These are
1795       * the modules that are allowed according to the data in the backup file.
1796       * In {@link after_execute()} we then have to prevent adding of all the other
1797       * types of activity.
1798       */
1799      protected $legacyallowedmodules = array();
1800  
1801      protected function define_structure() {
1802  
1803          $course = new restore_path_element('course', '/course');
1804          $category = new restore_path_element('category', '/course/category');
1805          $tag = new restore_path_element('tag', '/course/tags/tag');
1806          $customfield = new restore_path_element('customfield', '/course/customfields/customfield');
1807          $courseformatoptions = new restore_path_element('course_format_option', '/course/courseformatoptions/courseformatoption');
1808          $allowedmodule = new restore_path_element('allowed_module', '/course/allowed_modules/module');
1809  
1810          // Apply for 'format' plugins optional paths at course level
1811          $this->add_plugin_structure('format', $course);
1812  
1813          // Apply for 'theme' plugins optional paths at course level
1814          $this->add_plugin_structure('theme', $course);
1815  
1816          // Apply for 'report' plugins optional paths at course level
1817          $this->add_plugin_structure('report', $course);
1818  
1819          // Apply for 'course report' plugins optional paths at course level
1820          $this->add_plugin_structure('coursereport', $course);
1821  
1822          // Apply for plagiarism plugins optional paths at course level
1823          $this->add_plugin_structure('plagiarism', $course);
1824  
1825          // Apply for local plugins optional paths at course level
1826          $this->add_plugin_structure('local', $course);
1827  
1828          // Apply for admin tool plugins optional paths at course level.
1829          $this->add_plugin_structure('tool', $course);
1830  
1831          return array($course, $category, $tag, $customfield, $allowedmodule, $courseformatoptions);
1832      }
1833  
1834      /**
1835       * Processing functions go here
1836       *
1837       * @global moodledatabase $DB
1838       * @param stdClass $data
1839       */
1840      public function process_course($data) {
1841          global $CFG, $DB;
1842          $context = context::instance_by_id($this->task->get_contextid());
1843          $userid = $this->task->get_userid();
1844          $target = $this->get_task()->get_target();
1845          $isnewcourse = $target == backup::TARGET_NEW_COURSE;
1846  
1847          // When restoring to a new course we can set all the things except for the ID number.
1848          $canchangeidnumber = $isnewcourse || has_capability('moodle/course:changeidnumber', $context, $userid);
1849          $canchangesummary = $isnewcourse || has_capability('moodle/course:changesummary', $context, $userid);
1850          $canforcelanguage = has_capability('moodle/course:setforcedlanguage', $context, $userid);
1851  
1852          $data = (object)$data;
1853          $data->id = $this->get_courseid();
1854  
1855          // Calculate final course names, to avoid dupes.
1856          $fullname  = $this->get_setting_value('course_fullname');
1857          $shortname = $this->get_setting_value('course_shortname');
1858          list($data->fullname, $data->shortname) = restore_dbops::calculate_course_names($this->get_courseid(),
1859              $fullname === false ? $data->fullname : $fullname,
1860              $shortname === false ? $data->shortname : $shortname);
1861          // Do not modify the course names at all when merging and user selected to keep the names (or prohibited by cap).
1862          if (!$isnewcourse && $fullname === false) {
1863              unset($data->fullname);
1864          }
1865          if (!$isnewcourse && $shortname === false) {
1866              unset($data->shortname);
1867          }
1868  
1869          // Unset summary if user can't change it.
1870          if (!$canchangesummary) {
1871              unset($data->summary);
1872              unset($data->summaryformat);
1873          }
1874  
1875          // Unset lang if user can't change it.
1876          if (!$canforcelanguage) {
1877              unset($data->lang);
1878          }
1879  
1880          // Only allow the idnumber to be set if the user has permission and the idnumber is not already in use by
1881          // another course on this site.
1882          if (!empty($data->idnumber) && $canchangeidnumber && $this->task->is_samesite()
1883                  && !$DB->record_exists('course', array('idnumber' => $data->idnumber))) {
1884              // Do not reset idnumber.
1885  
1886          } else if (!$isnewcourse) {
1887              // Prevent override when restoring as merge.
1888              unset($data->idnumber);
1889  
1890          } else {
1891              $data->idnumber = '';
1892          }
1893  
1894          // If we restore a course from this site, let's capture the original course id.
1895          if ($isnewcourse && $this->get_task()->is_samesite()) {
1896              $data->originalcourseid = $this->get_task()->get_old_courseid();
1897          }
1898  
1899          // Any empty value for course->hiddensections will lead to 0 (default, show collapsed).
1900          // It has been reported that some old 1.9 courses may have it null leading to DB error. MDL-31532
1901          if (empty($data->hiddensections)) {
1902              $data->hiddensections = 0;
1903          }
1904  
1905          // Set legacyrestrictmodules to true if the course was resticting modules. If so
1906          // then we will need to process restricted modules after execution.
1907          $this->legacyrestrictmodules = !empty($data->restrictmodules);
1908  
1909          $data->startdate= $this->apply_date_offset($data->startdate);
1910          if (isset($data->enddate)) {
1911              $data->enddate = $this->apply_date_offset($data->enddate);
1912          }
1913  
1914          if ($data->defaultgroupingid) {
1915              $data->defaultgroupingid = $this->get_mappingid('grouping', $data->defaultgroupingid);
1916          }
1917  
1918          $courseconfig = get_config('moodlecourse');
1919  
1920          if (empty($CFG->enablecompletion)) {
1921              // Completion is disabled globally.
1922              $data->enablecompletion = 0;
1923              $data->completionstartonenrol = 0;
1924              $data->completionnotify = 0;
1925              $data->showcompletionconditions = null;
1926          } else {
1927              $showcompletionconditionsdefault = ($courseconfig->showcompletionconditions ?? null);
1928              $data->showcompletionconditions = $data->showcompletionconditions ?? $showcompletionconditionsdefault;
1929          }
1930  
1931          $showactivitydatesdefault = ($courseconfig->showactivitydates ?? null);
1932          $data->showactivitydates = $data->showactivitydates ?? $showactivitydatesdefault;
1933  
1934          $pdffontdefault = ($courseconfig->pdfexportfont ?? null);
1935          $data->pdfexportfont = $data->pdfexportfont ?? $pdffontdefault;
1936  
1937          $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1938          if (isset($data->lang) && !array_key_exists($data->lang, $languages)) {
1939              $data->lang = '';
1940          }
1941  
1942          $themes = get_list_of_themes(); // Get themes for quick search later
1943          if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1944              $data->theme = '';
1945          }
1946  
1947          // Check if this is an old SCORM course format.
1948          if ($data->format == 'scorm') {
1949              $data->format = 'singleactivity';
1950              $data->activitytype = 'scorm';
1951          }
1952  
1953          // Course record ready, update it
1954          $DB->update_record('course', $data);
1955  
1956          // Apply any course format options that may be saved against the course
1957          // entity in earlier-version backups.
1958          course_get_format($data)->update_course_format_options($data);
1959  
1960          // Role name aliases
1961          restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1962      }
1963  
1964      public function process_category($data) {
1965          // Nothing to do with the category. UI sets it before restore starts
1966      }
1967  
1968      public function process_tag($data) {
1969          global $CFG, $DB;
1970  
1971          $data = (object)$data;
1972  
1973          core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
1974                  context_course::instance($this->get_courseid()), $data->rawname);
1975      }
1976  
1977      /**
1978       * Process custom fields
1979       *
1980       * @param array $data
1981       */
1982      public function process_customfield($data) {
1983          $handler = core_course\customfield\course_handler::create();
1984          $handler->restore_instance_data_from_backup($this->task, $data);
1985      }
1986  
1987      /**
1988       * Processes a course format option.
1989       *
1990       * @param array $data The record being restored.
1991       * @throws base_step_exception
1992       * @throws dml_exception
1993       */
1994      public function process_course_format_option(array $data) : void {
1995          global $DB;
1996  
1997          if ($data['sectionid']) {
1998              // Ignore section-level format options saved course-level in earlier-version backups.
1999              return;
2000          }
2001  
2002          $courseid = $this->get_courseid();
2003          $record = $DB->get_record('course_format_options', [ 'courseid' => $courseid, 'name' => $data['name'],
2004                  'format' => $data['format'], 'sectionid' => 0 ], 'id');
2005          if ($record !== false) {
2006              $DB->update_record('course_format_options', (object) [ 'id' => $record->id, 'value' => $data['value'] ]);
2007          } else {
2008              $data['courseid'] = $courseid;
2009              $DB->insert_record('course_format_options', (object) $data);
2010          }
2011      }
2012  
2013      public function process_allowed_module($data) {
2014          $data = (object)$data;
2015  
2016          // Backwards compatiblity support for the data that used to be in the
2017          // course_allowed_modules table.
2018          if ($this->legacyrestrictmodules) {
2019              $this->legacyallowedmodules[$data->modulename] = 1;
2020          }
2021      }
2022  
2023      protected function after_execute() {
2024          global $DB;
2025  
2026          // Add course related files, without itemid to match
2027          $this->add_related_files('course', 'summary', null);
2028          $this->add_related_files('course', 'overviewfiles', null);
2029  
2030          // Deal with legacy allowed modules.
2031          if ($this->legacyrestrictmodules) {
2032              $context = context_course::instance($this->get_courseid());
2033  
2034              list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
2035              list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
2036              foreach ($managerroleids as $roleid) {
2037                  unset($roleids[$roleid]);
2038              }
2039  
2040              foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
2041                  if (isset($this->legacyallowedmodules[$modname])) {
2042                      // Module is allowed, no worries.
2043                      continue;
2044                  }
2045  
2046                  $capability = 'mod/' . $modname . ':addinstance';
2047  
2048                  if (!get_capability_info($capability)) {
2049                      $this->log("Capability '{$capability}' was not found!", backup::LOG_WARNING);
2050                      continue;
2051                  }
2052  
2053                  foreach ($roleids as $roleid) {
2054                      assign_capability($capability, CAP_PREVENT, $roleid, $context);
2055                  }
2056              }
2057          }
2058      }
2059  }
2060  
2061  /**
2062   * Execution step that will migrate legacy files if present.
2063   */
2064  class restore_course_legacy_files_step extends restore_execution_step {
2065      public function define_execution() {
2066          global $DB;
2067  
2068          // Do a check for legacy files and skip if there are none.
2069          $sql = 'SELECT count(*)
2070                    FROM {backup_files_temp}
2071                   WHERE backupid = ?
2072                     AND contextid = ?
2073                     AND component = ?
2074                     AND filearea  = ?';
2075          $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
2076  
2077          if ($DB->count_records_sql($sql, $params)) {
2078              $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
2079              restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
2080                  'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
2081          }
2082      }
2083  }
2084  
2085  /*
2086   * Structure step that will read the roles.xml file (at course/activity/block levels)
2087   * containing all the role_assignments and overrides for that context. If corresponding to
2088   * one mapped role, they will be applied to target context. Will observe the role_assignments
2089   * setting to decide if ras are restored.
2090   *
2091   * Note: this needs to be executed after all users are enrolled.
2092   */
2093  class restore_ras_and_caps_structure_step extends restore_structure_step {
2094      protected $plugins = null;
2095  
2096      protected function define_structure() {
2097  
2098          $paths = array();
2099  
2100          // Observe the role_assignments setting
2101          if ($this->get_setting_value('role_assignments')) {
2102              $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
2103          }
2104          if ($this->get_setting_value('permissions')) {
2105              $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2106          }
2107  
2108          return $paths;
2109      }
2110  
2111      /**
2112       * Assign roles
2113       *
2114       * This has to be called after enrolments processing.
2115       *
2116       * @param mixed $data
2117       * @return void
2118       */
2119      public function process_assignment($data) {
2120          global $DB;
2121  
2122          $data = (object)$data;
2123  
2124          // Check roleid, userid are one of the mapped ones
2125          if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
2126              return;
2127          }
2128          if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
2129              return;
2130          }
2131          if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2132              // Only assign roles to not deleted users
2133              return;
2134          }
2135          if (!$contextid = $this->task->get_contextid()) {
2136              return;
2137          }
2138  
2139          if (empty($data->component)) {
2140              // assign standard manual roles
2141              // TODO: role_assign() needs one userid param to be able to specify our restore userid
2142              role_assign($newroleid, $newuserid, $contextid);
2143  
2144          } else if ((strpos($data->component, 'enrol_') === 0)) {
2145              // Deal with enrolment roles - ignore the component and just find out the instance via new id,
2146              // it is possible that enrolment was restored using different plugin type.
2147              if (!isset($this->plugins)) {
2148                  $this->plugins = enrol_get_plugins(true);
2149              }
2150              if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
2151                  if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2152                      if (isset($this->plugins[$instance->enrol])) {
2153                          $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
2154                      }
2155                  }
2156              }
2157  
2158          } else {
2159              $data->roleid    = $newroleid;
2160              $data->userid    = $newuserid;
2161              $data->contextid = $contextid;
2162              $dir = core_component::get_component_directory($data->component);
2163              if ($dir and is_dir($dir)) {
2164                  if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
2165                      return;
2166                  }
2167              }
2168              // Bad luck, plugin could not restore the data, let's add normal membership.
2169              role_assign($data->roleid, $data->userid, $data->contextid);
2170              $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
2171              $this->log($message, backup::LOG_WARNING);
2172          }
2173      }
2174  
2175      public function process_override($data) {
2176          $data = (object)$data;
2177          // Check roleid is one of the mapped ones
2178          $newrole = $this->get_mapping('role', $data->roleid);
2179          $newroleid = $newrole->newitemid ?? false;
2180          $userid = $this->task->get_userid();
2181  
2182          // If newroleid and context are valid assign it via API (it handles dupes and so on)
2183          if ($newroleid && $this->task->get_contextid()) {
2184              if (!$capability = get_capability_info($data->capability)) {
2185                  $this->log("Capability '{$data->capability}' was not found!", backup::LOG_WARNING);
2186              } else {
2187                  $context = context::instance_by_id($this->task->get_contextid());
2188                  $overrideableroles = get_overridable_roles($context, ROLENAME_SHORT);
2189                  $safecapability = is_safe_capability($capability);
2190  
2191                  // Check if the new role is an overrideable role AND if the user performing the restore has the
2192                  // capability to assign the capability.
2193                  if (in_array($newrole->info['shortname'], $overrideableroles) &&
2194                      (has_capability('moodle/role:override', $context, $userid) ||
2195                              ($safecapability && has_capability('moodle/role:safeoverride', $context, $userid)))
2196                  ) {
2197                      assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
2198                  } else {
2199                      $this->log("Insufficient capability to assign capability '{$data->capability}' to role!", backup::LOG_WARNING);
2200                  }
2201              }
2202          }
2203      }
2204  }
2205  
2206  /**
2207   * If no instances yet add default enrol methods the same way as when creating new course in UI.
2208   */
2209  class restore_default_enrolments_step extends restore_execution_step {
2210  
2211      public function define_execution() {
2212          global $DB;
2213  
2214          // No enrolments in front page.
2215          if ($this->get_courseid() == SITEID) {
2216              return;
2217          }
2218  
2219          $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
2220          // Return any existing course enrolment instances.
2221          $enrolinstances = enrol_get_instances($course->id, false);
2222  
2223          if ($enrolinstances) {
2224              // Something already added instances.
2225              // Get the existing enrolment methods in the course.
2226              $enrolmethods = array_map(function($enrolinstance) {
2227                  return $enrolinstance->enrol;
2228              }, $enrolinstances);
2229  
2230              $plugins = enrol_get_plugins(true);
2231              foreach ($plugins as $pluginname => $plugin) {
2232                  // Make sure all default enrolment methods exist in the course.
2233                  if (!in_array($pluginname, $enrolmethods)) {
2234                      $plugin->course_updated(true, $course, null);
2235                  }
2236                  $plugin->restore_sync_course($course);
2237              }
2238  
2239          } else {
2240              // Looks like a newly created course.
2241              enrol_course_updated(true, $course, null);
2242          }
2243      }
2244  }
2245  
2246  /**
2247   * This structure steps restores the enrol plugins and their underlying
2248   * enrolments, performing all the mappings and/or movements required
2249   */
2250  class restore_enrolments_structure_step extends restore_structure_step {
2251      protected $enrolsynced = false;
2252      protected $plugins = null;
2253      protected $originalstatus = array();
2254  
2255      /**
2256       * Conditionally decide if this step should be executed.
2257       *
2258       * This function checks the following parameter:
2259       *
2260       *   1. the course/enrolments.xml file exists
2261       *
2262       * @return bool true is safe to execute, false otherwise
2263       */
2264      protected function execute_condition() {
2265  
2266          if ($this->get_courseid() == SITEID) {
2267              return false;
2268          }
2269  
2270          // Check it is included in the backup
2271          $fullpath = $this->task->get_taskbasepath();
2272          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2273          if (!file_exists($fullpath)) {
2274              // Not found, can't restore enrolments info
2275              return false;
2276          }
2277  
2278          return true;
2279      }
2280  
2281      protected function define_structure() {
2282  
2283          $userinfo = $this->get_setting_value('users');
2284  
2285          $paths = [];
2286          $paths[] = $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2287          if ($userinfo) {
2288              $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2289          }
2290          // Attach local plugin stucture to enrol element.
2291          $this->add_plugin_structure('enrol', $enrol);
2292  
2293          return $paths;
2294      }
2295  
2296      /**
2297       * Create enrolment instances.
2298       *
2299       * This has to be called after creation of roles
2300       * and before adding of role assignments.
2301       *
2302       * @param mixed $data
2303       * @return void
2304       */
2305      public function process_enrol($data) {
2306          global $DB;
2307  
2308          $data = (object)$data;
2309          $oldid = $data->id; // We'll need this later.
2310          unset($data->id);
2311  
2312          $this->originalstatus[$oldid] = $data->status;
2313  
2314          if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2315              $this->set_mapping('enrol', $oldid, 0);
2316              return;
2317          }
2318  
2319          if (!isset($this->plugins)) {
2320              $this->plugins = enrol_get_plugins(true);
2321          }
2322  
2323          if (!$this->enrolsynced) {
2324              // Make sure that all plugin may create instances and enrolments automatically
2325              // before the first instance restore - this is suitable especially for plugins
2326              // that synchronise data automatically using course->idnumber or by course categories.
2327              foreach ($this->plugins as $plugin) {
2328                  $plugin->restore_sync_course($courserec);
2329              }
2330              $this->enrolsynced = true;
2331          }
2332  
2333          // Map standard fields - plugin has to process custom fields manually.
2334          $data->roleid   = $this->get_mappingid('role', $data->roleid);
2335          $data->courseid = $courserec->id;
2336  
2337          if (!$this->get_setting_value('users') && $this->get_setting_value('enrolments') == backup::ENROL_WITHUSERS) {
2338              $converttomanual = true;
2339          } else {
2340              $converttomanual = ($this->get_setting_value('enrolments') == backup::ENROL_NEVER);
2341          }
2342  
2343          if ($converttomanual) {
2344              // Restore enrolments as manual enrolments.
2345              unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2346              if (!enrol_is_enabled('manual')) {
2347                  $this->set_mapping('enrol', $oldid, 0);
2348                  return;
2349              }
2350              if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2351                  $instance = reset($instances);
2352                  $this->set_mapping('enrol', $oldid, $instance->id);
2353              } else {
2354                  if ($data->enrol === 'manual') {
2355                      $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2356                  } else {
2357                      $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2358                  }
2359                  $this->set_mapping('enrol', $oldid, $instanceid);
2360              }
2361  
2362          } else {
2363              if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2364                  $this->set_mapping('enrol', $oldid, 0);
2365                  $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, consider restoring without enrolment methods";
2366                  $this->log($message, backup::LOG_WARNING);
2367                  return;
2368              }
2369              if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2370                  // Let's keep the sortorder in old backups.
2371              } else {
2372                  // Prevent problems with colliding sortorders in old backups,
2373                  // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2374                  unset($data->sortorder);
2375              }
2376              // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2377              $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2378          }
2379      }
2380  
2381      /**
2382       * Create user enrolments.
2383       *
2384       * This has to be called after creation of enrolment instances
2385       * and before adding of role assignments.
2386       *
2387       * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2388       *
2389       * @param mixed $data
2390       * @return void
2391       */
2392      public function process_enrolment($data) {
2393          global $DB;
2394  
2395          if (!isset($this->plugins)) {
2396              $this->plugins = enrol_get_plugins(true);
2397          }
2398  
2399          $data = (object)$data;
2400  
2401          // Process only if parent instance have been mapped.
2402          if ($enrolid = $this->get_new_parentid('enrol')) {
2403              $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2404              $oldenrolid = $this->get_old_parentid('enrol');
2405              if (isset($this->originalstatus[$oldenrolid])) {
2406                  $oldinstancestatus = $this->originalstatus[$oldenrolid];
2407              }
2408              if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2409                  // And only if user is a mapped one.
2410                  if ($userid = $this->get_mappingid('user', $data->userid)) {
2411                      if (isset($this->plugins[$instance->enrol])) {
2412                          $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2413                      }
2414                  }
2415              }
2416          }
2417      }
2418  }
2419  
2420  
2421  /**
2422   * Make sure the user restoring the course can actually access it.
2423   */
2424  class restore_fix_restorer_access_step extends restore_execution_step {
2425      protected function define_execution() {
2426          global $CFG, $DB;
2427  
2428          if (!$userid = $this->task->get_userid()) {
2429              return;
2430          }
2431  
2432          if (empty($CFG->restorernewroleid)) {
2433              // Bad luck, no fallback role for restorers specified
2434              return;
2435          }
2436  
2437          $courseid = $this->get_courseid();
2438          $context = context_course::instance($courseid);
2439  
2440          if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2441              // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2442              return;
2443          }
2444  
2445          // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2446          role_assign($CFG->restorernewroleid, $userid, $context);
2447  
2448          if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2449              // Extra role is enough, yay!
2450              return;
2451          }
2452  
2453          // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2454          // hopefully admin selected suitable $CFG->restorernewroleid ...
2455          if (!enrol_is_enabled('manual')) {
2456              return;
2457          }
2458          if (!$enrol = enrol_get_plugin('manual')) {
2459              return;
2460          }
2461          if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2462              $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2463              $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2464              $enrol->add_instance($course, $fields);
2465          }
2466  
2467          enrol_try_internal_enrol($courseid, $userid);
2468      }
2469  }
2470  
2471  
2472  /**
2473   * This structure steps restores the filters and their configs
2474   */
2475  class restore_filters_structure_step extends restore_structure_step {
2476  
2477      protected function define_structure() {
2478  
2479          $paths = array();
2480  
2481          $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2482          $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2483  
2484          return $paths;
2485      }
2486  
2487      public function process_active($data) {
2488  
2489          $data = (object)$data;
2490  
2491          if (strpos($data->filter, 'filter/') === 0) {
2492              $data->filter = substr($data->filter, 7);
2493  
2494          } else if (strpos($data->filter, '/') !== false) {
2495              // Unsupported old filter.
2496              return;
2497          }
2498  
2499          if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2500              return;
2501          }
2502          filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2503      }
2504  
2505      public function process_config($data) {
2506  
2507          $data = (object)$data;
2508  
2509          if (strpos($data->filter, 'filter/') === 0) {
2510              $data->filter = substr($data->filter, 7);
2511  
2512          } else if (strpos($data->filter, '/') !== false) {
2513              // Unsupported old filter.
2514              return;
2515          }
2516  
2517          if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2518              return;
2519          }
2520          filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2521      }
2522  }
2523  
2524  
2525  /**
2526   * This structure steps restores the comments
2527   * Note: Cannot use the comments API because defaults to USER->id.
2528   * That should change allowing to pass $userid
2529   */
2530  class restore_comments_structure_step extends restore_structure_step {
2531  
2532      protected function define_structure() {
2533  
2534          $paths = array();
2535  
2536          $paths[] = new restore_path_element('comment', '/comments/comment');
2537  
2538          return $paths;
2539      }
2540  
2541      public function process_comment($data) {
2542          global $DB;
2543  
2544          $data = (object)$data;
2545  
2546          // First of all, if the comment has some itemid, ask to the task what to map
2547          $mapping = false;
2548          if ($data->itemid) {
2549              $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2550              $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2551          }
2552          // Only restore the comment if has no mapping OR we have found the matching mapping
2553          if (!$mapping || $data->itemid) {
2554              // Only if user mapping and context
2555              $data->userid = $this->get_mappingid('user', $data->userid);
2556              if ($data->userid && $this->task->get_contextid()) {
2557                  $data->contextid = $this->task->get_contextid();
2558                  // Only if there is another comment with same context/user/timecreated
2559                  $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2560                  if (!$DB->record_exists('comments', $params)) {
2561                      $DB->insert_record('comments', $data);
2562                  }
2563              }
2564          }
2565      }
2566  }
2567  
2568  /**
2569   * This structure steps restores the badges and their configs
2570   */
2571  class restore_badges_structure_step extends restore_structure_step {
2572  
2573      /**
2574       * Conditionally decide if this step should be executed.
2575       *
2576       * This function checks the following parameters:
2577       *
2578       *   1. Badges and course badges are enabled on the site.
2579       *   2. The course/badges.xml file exists.
2580       *   3. All modules are restorable.
2581       *   4. All modules are marked for restore.
2582       *
2583       * @return bool True is safe to execute, false otherwise
2584       */
2585      protected function execute_condition() {
2586          global $CFG;
2587  
2588          // First check is badges and course level badges are enabled on this site.
2589          if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2590              // Disabled, don't restore course badges.
2591              return false;
2592          }
2593  
2594          // Check if badges.xml is included in the backup.
2595          $fullpath = $this->task->get_taskbasepath();
2596          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2597          if (!file_exists($fullpath)) {
2598              // Not found, can't restore course badges.
2599              return false;
2600          }
2601  
2602          // Check we are able to restore all backed up modules.
2603          if ($this->task->is_missing_modules()) {
2604              return false;
2605          }
2606  
2607          // Finally check all modules within the backup are being restored.
2608          if ($this->task->is_excluding_activities()) {
2609              return false;
2610          }
2611  
2612          return true;
2613      }
2614  
2615      protected function define_structure() {
2616          $paths = array();
2617          $paths[] = new restore_path_element('badge', '/badges/badge');
2618          $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2619          $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2620          $paths[] = new restore_path_element('endorsement', '/badges/badge/endorsement');
2621          $paths[] = new restore_path_element('alignment', '/badges/badge/alignments/alignment');
2622          $paths[] = new restore_path_element('relatedbadge', '/badges/badge/relatedbadges/relatedbadge');
2623          $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2624  
2625          return $paths;
2626      }
2627  
2628      public function process_badge($data) {
2629          global $DB, $CFG;
2630  
2631          require_once($CFG->libdir . '/badgeslib.php');
2632  
2633          $data = (object)$data;
2634          $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2635          if (empty($data->usercreated)) {
2636              $data->usercreated = $this->task->get_userid();
2637          }
2638          $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2639          if (empty($data->usermodified)) {
2640              $data->usermodified = $this->task->get_userid();
2641          }
2642  
2643          // We'll restore the badge image.
2644          $restorefiles = true;
2645  
2646          $courseid = $this->get_courseid();
2647  
2648          $params = array(
2649                  'name'           => $data->name,
2650                  'description'    => $data->description,
2651                  'timecreated'    => $data->timecreated,
2652                  'timemodified'   => $data->timemodified,
2653                  'usercreated'    => $data->usercreated,
2654                  'usermodified'   => $data->usermodified,
2655                  'issuername'     => $data->issuername,
2656                  'issuerurl'      => $data->issuerurl,
2657                  'issuercontact'  => $data->issuercontact,
2658                  'expiredate'     => $this->apply_date_offset($data->expiredate),
2659                  'expireperiod'   => $data->expireperiod,
2660                  'type'           => BADGE_TYPE_COURSE,
2661                  'courseid'       => $courseid,
2662                  'message'        => $data->message,
2663                  'messagesubject' => $data->messagesubject,
2664                  'attachment'     => $data->attachment,
2665                  'notification'   => $data->notification,
2666                  'status'         => BADGE_STATUS_INACTIVE,
2667                  'nextcron'       => $data->nextcron,
2668                  'version'        => $data->version,
2669                  'language'       => $data->language,
2670                  'imageauthorname' => $data->imageauthorname,
2671                  'imageauthoremail' => $data->imageauthoremail,
2672                  'imageauthorurl' => $data->imageauthorurl,
2673                  'imagecaption'   => $data->imagecaption
2674          );
2675  
2676          $newid = $DB->insert_record('badge', $params);
2677          $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2678      }
2679  
2680      /**
2681       * Create an endorsement for a badge.
2682       *
2683       * @param mixed $data
2684       * @return void
2685       */
2686      public function process_endorsement($data) {
2687          global $DB;
2688  
2689          $data = (object)$data;
2690  
2691          $params = [
2692              'badgeid' => $this->get_new_parentid('badge'),
2693              'issuername' => $data->issuername,
2694              'issuerurl' => $data->issuerurl,
2695              'issueremail' => $data->issueremail,
2696              'claimid' => $data->claimid,
2697              'claimcomment' => $data->claimcomment,
2698              'dateissued' => $this->apply_date_offset($data->dateissued)
2699          ];
2700          $newid = $DB->insert_record('badge_endorsement', $params);
2701          $this->set_mapping('endorsement', $data->id, $newid);
2702      }
2703  
2704      /**
2705       * Link to related badges for a badge. This relies on post processing in after_execute().
2706       *
2707       * @param mixed $data
2708       * @return void
2709       */
2710      public function process_relatedbadge($data) {
2711          global $DB;
2712  
2713          $data = (object)$data;
2714          $relatedbadgeid = $data->relatedbadgeid;
2715  
2716          if ($relatedbadgeid) {
2717              // Only backup and restore related badges if they are contained in the backup file.
2718              $params = array(
2719                      'badgeid'           => $this->get_new_parentid('badge'),
2720                      'relatedbadgeid'    => $relatedbadgeid
2721              );
2722              $newid = $DB->insert_record('badge_related', $params);
2723          }
2724      }
2725  
2726      /**
2727       * Link to an alignment for a badge.
2728       *
2729       * @param mixed $data
2730       * @return void
2731       */
2732      public function process_alignment($data) {
2733          global $DB;
2734  
2735          $data = (object)$data;
2736          $params = array(
2737                  'badgeid'           => $this->get_new_parentid('badge'),
2738                  'targetname'        => $data->targetname,
2739                  'targeturl'         => $data->targeturl,
2740                  'targetdescription' => $data->targetdescription,
2741                  'targetframework'   => $data->targetframework,
2742                  'targetcode'        => $data->targetcode
2743          );
2744          $newid = $DB->insert_record('badge_alignment', $params);
2745          $this->set_mapping('alignment', $data->id, $newid);
2746      }
2747  
2748      public function process_criterion($data) {
2749          global $DB;
2750  
2751          $data = (object)$data;
2752  
2753          $params = array(
2754                  'badgeid'           => $this->get_new_parentid('badge'),
2755                  'criteriatype'      => $data->criteriatype,
2756                  'method'            => $data->method,
2757                  'description'       => isset($data->description) ? $data->description : '',
2758                  'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2759          );
2760  
2761          $newid = $DB->insert_record('badge_criteria', $params);
2762          $this->set_mapping('criterion', $data->id, $newid);
2763      }
2764  
2765      public function process_parameter($data) {
2766          global $DB, $CFG;
2767  
2768          require_once($CFG->libdir . '/badgeslib.php');
2769  
2770          $data = (object)$data;
2771          $criteriaid = $this->get_new_parentid('criterion');
2772  
2773          // Parameter array that will go to database.
2774          $params = array();
2775          $params['critid'] = $criteriaid;
2776  
2777          $oldparam = explode('_', $data->name);
2778  
2779          if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2780              $module = $this->get_mappingid('course_module', $oldparam[1]);
2781              $params['name'] = $oldparam[0] . '_' . $module;
2782              $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2783          } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2784              $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2785              $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2786          } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2787              $role = $this->get_mappingid('role', $data->value);
2788              if (!empty($role)) {
2789                  $params['name'] = 'role_' . $role;
2790                  $params['value'] = $role;
2791              } else {
2792                  return;
2793              }
2794          } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COMPETENCY) {
2795              $competencyid = $this->get_mappingid('competency', $data->value);
2796              if (!empty($competencyid)) {
2797                  $params['name'] = 'competency_' . $competencyid;
2798                  $params['value'] = $competencyid;
2799              } else {
2800                  return;
2801              }
2802          }
2803  
2804          if (!$DB->record_exists('badge_criteria_param', $params)) {
2805              $DB->insert_record('badge_criteria_param', $params);
2806          }
2807      }
2808  
2809      public function process_manual_award($data) {
2810          global $DB;
2811  
2812          $data = (object)$data;
2813          $role = $this->get_mappingid('role', $data->issuerrole);
2814  
2815          if (!empty($role)) {
2816              $award = array(
2817                  'badgeid'     => $this->get_new_parentid('badge'),
2818                  'recipientid' => $this->get_mappingid('user', $data->recipientid),
2819                  'issuerid'    => $this->get_mappingid('user', $data->issuerid),
2820                  'issuerrole'  => $role,
2821                  'datemet'     => $this->apply_date_offset($data->datemet)
2822              );
2823  
2824              // Skip the manual award if recipient or issuer can not be mapped to.
2825              if (empty($award['recipientid']) || empty($award['issuerid'])) {
2826                  return;
2827              }
2828  
2829              $DB->insert_record('badge_manual_award', $award);
2830          }
2831      }
2832  
2833      protected function after_execute() {
2834          global $DB;
2835          // Add related files.
2836          $this->add_related_files('badges', 'badgeimage', 'badge');
2837  
2838          $badgeid = $this->get_new_parentid('badge');
2839          // Remap any related badges.
2840          // We do this in the DB directly because this is backup/restore it is not valid to call into
2841          // the component API.
2842          $params = array('badgeid' => $badgeid);
2843          $query = "SELECT DISTINCT br.id, br.badgeid, br.relatedbadgeid
2844                      FROM {badge_related} br
2845                     WHERE (br.badgeid = :badgeid)";
2846          $relatedbadges = $DB->get_records_sql($query, $params);
2847          $newrelatedids = [];
2848          foreach ($relatedbadges as $relatedbadge) {
2849              $relatedid = $this->get_mappingid('badge', $relatedbadge->relatedbadgeid);
2850              $params['relatedbadgeid'] = $relatedbadge->relatedbadgeid;
2851              $DB->delete_records_select('badge_related', '(badgeid = :badgeid AND relatedbadgeid = :relatedbadgeid)', $params);
2852              if ($relatedid) {
2853                  $newrelatedids[] = $relatedid;
2854              }
2855          }
2856          if (!empty($newrelatedids)) {
2857              $relatedbadges = [];
2858              foreach ($newrelatedids as $relatedid) {
2859                  $relatedbadge = new stdClass();
2860                  $relatedbadge->badgeid = $badgeid;
2861                  $relatedbadge->relatedbadgeid = $relatedid;
2862                  $relatedbadges[] = $relatedbadge;
2863              }
2864              $DB->insert_records('badge_related', $relatedbadges);
2865          }
2866      }
2867  }
2868  
2869  /**
2870   * This structure steps restores the calendar events
2871   */
2872  class restore_calendarevents_structure_step extends restore_structure_step {
2873  
2874      protected function define_structure() {
2875  
2876          $paths = array();
2877  
2878          $paths[] = new restore_path_element('calendarevents', '/events/event');
2879  
2880          return $paths;
2881      }
2882  
2883      public function process_calendarevents($data) {
2884          global $DB, $SITE, $USER;
2885  
2886          $data = (object)$data;
2887          $oldid = $data->id;
2888          $restorefiles = true; // We'll restore the files
2889  
2890          // If this is a new action event, it will automatically be populated by the adhoc task.
2891          // Nothing to do here.
2892          if (isset($data->type) && $data->type == CALENDAR_EVENT_TYPE_ACTION) {
2893              return;
2894          }
2895  
2896          // User overrides for activities are identified by having a courseid of zero with
2897          // both a modulename and instance value set.
2898          $isuseroverride = !$data->courseid && $data->modulename && $data->instance;
2899  
2900          // If we don't want to include user data and this record is a user override event
2901          // for an activity then we should not create it. (Only activity events can be user override events - which must have this
2902          // setting).
2903          if ($isuseroverride && $this->task->setting_exists('userinfo') && !$this->task->get_setting_value('userinfo')) {
2904              return;
2905          }
2906  
2907          // Find the userid and the groupid associated with the event.
2908          $data->userid = $this->get_mappingid('user', $data->userid);
2909          if ($data->userid === false) {
2910              // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2911              // Use the current user ID for these events.
2912              $data->userid = $USER->id;
2913          }
2914          if (!empty($data->groupid)) {
2915              $data->groupid = $this->get_mappingid('group', $data->groupid);
2916              if ($data->groupid === false) {
2917                  return;
2918              }
2919          }
2920          // Handle events with empty eventtype //MDL-32827
2921          if(empty($data->eventtype)) {
2922              if ($data->courseid == $SITE->id) {                                // Site event
2923                  $data->eventtype = "site";
2924              } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2925                  // Course assingment event
2926                  $data->eventtype = "due";
2927              } else if ($data->courseid != 0 && $data->groupid == 0) {      // Course event
2928                  $data->eventtype = "course";
2929              } else if ($data->groupid) {                                      // Group event
2930                  $data->eventtype = "group";
2931              } else if ($data->userid) {                                       // User event
2932                  $data->eventtype = "user";
2933              } else {
2934                  return;
2935              }
2936          }
2937  
2938          $params = array(
2939                  'name'           => $data->name,
2940                  'description'    => $data->description,
2941                  'format'         => $data->format,
2942                  // User overrides in activities use a course id of zero. All other event types
2943                  // must use the mapped course id.
2944                  'courseid'       => $data->courseid ? $this->get_courseid() : 0,
2945                  'groupid'        => $data->groupid,
2946                  'userid'         => $data->userid,
2947                  'repeatid'       => $this->get_mappingid('event', $data->repeatid),
2948                  'modulename'     => $data->modulename,
2949                  'type'           => isset($data->type) ? $data->type : 0,
2950                  'eventtype'      => $data->eventtype,
2951                  'timestart'      => $this->apply_date_offset($data->timestart),
2952                  'timeduration'   => $data->timeduration,
2953                  'timesort'       => isset($data->timesort) ? $this->apply_date_offset($data->timesort) : null,
2954                  'visible'        => $data->visible,
2955                  'uuid'           => $data->uuid,
2956                  'sequence'       => $data->sequence,
2957                  'timemodified'   => $data->timemodified,
2958                  'priority'       => isset($data->priority) ? $data->priority : null,
2959                  'location'       => isset($data->location) ? $data->location : null);
2960          if ($this->name == 'activity_calendar') {
2961              $params['instance'] = $this->task->get_activityid();
2962          } else {
2963              $params['instance'] = 0;
2964          }
2965          $sql = "SELECT id
2966                    FROM {event}
2967                   WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2968                     AND courseid = ?
2969                     AND modulename = ?
2970                     AND instance = ?
2971                     AND timestart = ?
2972                     AND timeduration = ?
2973                     AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2974          $arg = array ($params['name'], $params['courseid'], $params['modulename'], $params['instance'], $params['timestart'], $params['timeduration'], $params['description']);
2975          $result = $DB->record_exists_sql($sql, $arg);
2976          if (empty($result)) {
2977              $newitemid = $DB->insert_record('event', $params);
2978              $this->set_mapping('event', $oldid, $newitemid);
2979              $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2980          }
2981          // With repeating events, each event has the repeatid pointed at the first occurrence.
2982          // Since the repeatid will be empty when the first occurrence is restored,
2983          // Get the repeatid from the second occurrence of the repeating event and use that to update the first occurrence.
2984          // Then keep a list of repeatids so we only perform this update once.
2985          static $repeatids = array();
2986          if (!empty($params['repeatid']) && !in_array($params['repeatid'], $repeatids)) {
2987              // This entry is repeated so the repeatid field must be set.
2988              $DB->set_field('event', 'repeatid', $params['repeatid'], array('id' => $params['repeatid']));
2989              $repeatids[] = $params['repeatid'];
2990          }
2991  
2992      }
2993      protected function after_execute() {
2994          // Add related files
2995          $this->add_related_files('calendar', 'event_description', 'event_description');
2996      }
2997  }
2998  
2999  class restore_course_completion_structure_step extends restore_structure_step {
3000  
3001      /**
3002       * Conditionally decide if this step should be executed.
3003       *
3004       * This function checks parameters that are not immediate settings to ensure
3005       * that the enviroment is suitable for the restore of course completion info.
3006       *
3007       * This function checks the following four parameters:
3008       *
3009       *   1. Course completion is enabled on the site
3010       *   2. The backup includes course completion information
3011       *   3. All modules are restorable
3012       *   4. All modules are marked for restore.
3013       *   5. No completion criteria already exist for the course.
3014       *
3015       * @return bool True is safe to execute, false otherwise
3016       */
3017      protected function execute_condition() {
3018          global $CFG, $DB;
3019  
3020          // First check course completion is enabled on this site
3021          if (empty($CFG->enablecompletion)) {
3022              // Disabled, don't restore course completion
3023              return false;
3024          }
3025  
3026          // No course completion on the front page.
3027          if ($this->get_courseid() == SITEID) {
3028              return false;
3029          }
3030  
3031          // Check it is included in the backup
3032          $fullpath = $this->task->get_taskbasepath();
3033          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3034          if (!file_exists($fullpath)) {
3035              // Not found, can't restore course completion
3036              return false;
3037          }
3038  
3039          // Check we are able to restore all backed up modules
3040          if ($this->task->is_missing_modules()) {
3041              return false;
3042          }
3043  
3044          // Check all modules within the backup are being restored.
3045          if ($this->task->is_excluding_activities()) {
3046              return false;
3047          }
3048  
3049          // Check that no completion criteria is already set for the course.
3050          if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
3051              return false;
3052          }
3053  
3054          return true;
3055      }
3056  
3057      /**
3058       * Define the course completion structure
3059       *
3060       * @return array Array of restore_path_element
3061       */
3062      protected function define_structure() {
3063  
3064          // To know if we are including user completion info
3065          $userinfo = $this->get_setting_value('userscompletion');
3066  
3067          $paths = array();
3068          $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
3069          $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
3070  
3071          if ($userinfo) {
3072              $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
3073              $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
3074          }
3075  
3076          return $paths;
3077  
3078      }
3079  
3080      /**
3081       * Process course completion criteria
3082       *
3083       * @global moodle_database $DB
3084       * @param stdClass $data
3085       */
3086      public function process_course_completion_criteria($data) {
3087          global $DB;
3088  
3089          $data = (object)$data;
3090          $data->course = $this->get_courseid();
3091  
3092          // Apply the date offset to the time end field
3093          $data->timeend = $this->apply_date_offset($data->timeend);
3094  
3095          // Map the role from the criteria
3096          if (isset($data->role) && $data->role != '') {
3097              // Newer backups should include roleshortname, which makes this much easier.
3098              if (!empty($data->roleshortname)) {
3099                  $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
3100                  if (!$roleinstanceid) {
3101                      $this->log(
3102                          'Could not match the role shortname in course_completion_criteria, so skipping',
3103                          backup::LOG_DEBUG
3104                      );
3105                      return;
3106                  }
3107                  $data->role = $roleinstanceid;
3108              } else {
3109                  $data->role = $this->get_mappingid('role', $data->role);
3110              }
3111  
3112              // Check we have an id, otherwise it causes all sorts of bugs.
3113              if (!$data->role) {
3114                  $this->log(
3115                      'Could not match role in course_completion_criteria, so skipping',
3116                      backup::LOG_DEBUG
3117                  );
3118                  return;
3119              }
3120          }
3121  
3122          // If the completion criteria is for a module we need to map the module instance
3123          // to the new module id.
3124          if (!empty($data->moduleinstance) && !empty($data->module)) {
3125              $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
3126              if (empty($data->moduleinstance)) {
3127                  $this->log(
3128                      'Could not match the module instance in course_completion_criteria, so skipping',
3129                      backup::LOG_DEBUG
3130                  );
3131                  return;
3132              }
3133          } else {
3134              $data->module = null;
3135              $data->moduleinstance = null;
3136          }
3137  
3138          // We backup the course shortname rather than the ID so that we can match back to the course
3139          if (!empty($data->courseinstanceshortname)) {
3140              $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
3141              if (!$courseinstanceid) {
3142                  $this->log(
3143                      'Could not match the course instance in course_completion_criteria, so skipping',
3144                      backup::LOG_DEBUG
3145                  );
3146                  return;
3147              }
3148          } else {
3149              $courseinstanceid = null;
3150          }
3151          $data->courseinstance = $courseinstanceid;
3152  
3153          $params = array(
3154              'course'         => $data->course,
3155              'criteriatype'   => $data->criteriatype,
3156              'enrolperiod'    => $data->enrolperiod,
3157              'courseinstance' => $data->courseinstance,
3158              'module'         => $data->module,
3159              'moduleinstance' => $data->moduleinstance,
3160              'timeend'        => $data->timeend,
3161              'gradepass'      => $data->gradepass,
3162              'role'           => $data->role
3163          );
3164          $newid = $DB->insert_record('course_completion_criteria', $params);
3165          $this->set_mapping('course_completion_criteria', $data->id, $newid);
3166      }
3167  
3168      /**
3169       * Processes course compltion criteria complete records
3170       *
3171       * @global moodle_database $DB
3172       * @param stdClass $data
3173       */
3174      public function process_course_completion_crit_compl($data) {
3175          global $DB;
3176  
3177          $data = (object)$data;
3178  
3179          // This may be empty if criteria could not be restored
3180          $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
3181  
3182          $data->course = $this->get_courseid();
3183          $data->userid = $this->get_mappingid('user', $data->userid);
3184  
3185          if (!empty($data->criteriaid) && !empty($data->userid)) {
3186              $params = array(
3187                  'userid' => $data->userid,
3188                  'course' => $data->course,
3189                  'criteriaid' => $data->criteriaid,
3190                  'timecompleted' => $data->timecompleted
3191              );
3192              if (isset($data->gradefinal)) {
3193                  $params['gradefinal'] = $data->gradefinal;
3194              }
3195              if (isset($data->unenroled)) {
3196                  $params['unenroled'] = $data->unenroled;
3197              }
3198              $DB->insert_record('course_completion_crit_compl', $params);
3199          }
3200      }
3201  
3202      /**
3203       * Process course completions
3204       *
3205       * @global moodle_database $DB
3206       * @param stdClass $data
3207       */
3208      public function process_course_completions($data) {
3209          global $DB;
3210  
3211          $data = (object)$data;
3212  
3213          $data->course = $this->get_courseid();
3214          $data->userid = $this->get_mappingid('user', $data->userid);
3215  
3216          if (!empty($data->userid)) {
3217              $params = array(
3218                  'userid' => $data->userid,
3219                  'course' => $data->course,
3220                  'timeenrolled' => $data->timeenrolled,
3221                  'timestarted' => $data->timestarted,
3222                  'timecompleted' => $data->timecompleted,
3223                  'reaggregate' => $data->reaggregate
3224              );
3225  
3226              $existing = $DB->get_record('course_completions', array(
3227                  'userid' => $data->userid,
3228                  'course' => $data->course
3229              ));
3230  
3231              // MDL-46651 - If cron writes out a new record before we get to it
3232              // then we should replace it with the Truth data from the backup.
3233              // This may be obsolete after MDL-48518 is resolved
3234              if ($existing) {
3235                  $params['id'] = $existing->id;
3236                  $DB->update_record('course_completions', $params);
3237              } else {
3238                  $DB->insert_record('course_completions', $params);
3239              }
3240          }
3241      }
3242  
3243      /**
3244       * Process course completion aggregate methods
3245       *
3246       * @global moodle_database $DB
3247       * @param stdClass $data
3248       */
3249      public function process_course_completion_aggr_methd($data) {
3250          global $DB;
3251  
3252          $data = (object)$data;
3253  
3254          $data->course = $this->get_courseid();
3255  
3256          // Only create the course_completion_aggr_methd records if
3257          // the target course has not them defined. MDL-28180
3258          if (!$DB->record_exists('course_completion_aggr_methd', array(
3259                      'course' => $data->course,
3260                      'criteriatype' => $data->criteriatype))) {
3261              $params = array(
3262                  'course' => $data->course,
3263                  'criteriatype' => $data->criteriatype,
3264                  'method' => $data->method,
3265                  'value' => $data->value,
3266              );
3267              $DB->insert_record('course_completion_aggr_methd', $params);
3268          }
3269      }
3270  }
3271  
3272  
3273  /**
3274   * This structure step restores course logs (cmid = 0), delegating
3275   * the hard work to the corresponding {@link restore_logs_processor} passing the
3276   * collection of {@link restore_log_rule} rules to be observed as they are defined
3277   * by the task. Note this is only executed based in the 'logs' setting.
3278   *
3279   * NOTE: This is executed by final task, to have all the activities already restored
3280   *
3281   * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
3282   * records are. There are others like 'calendar' and 'upload' that will be handled
3283   * later.
3284   *
3285   * NOTE: All the missing actions (not able to be restored) are sent to logs for
3286   * debugging purposes
3287   */
3288  class restore_course_logs_structure_step extends restore_structure_step {
3289  
3290      /**
3291       * Conditionally decide if this step should be executed.
3292       *
3293       * This function checks the following parameter:
3294       *
3295       *   1. the course/logs.xml file exists
3296       *
3297       * @return bool true is safe to execute, false otherwise
3298       */
3299      protected function execute_condition() {
3300  
3301          // Check it is included in the backup
3302          $fullpath = $this->task->get_taskbasepath();
3303          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3304          if (!file_exists($fullpath)) {
3305              // Not found, can't restore course logs
3306              return false;
3307          }
3308  
3309          return true;
3310      }
3311  
3312      protected function define_structure() {
3313  
3314          $paths = array();
3315  
3316          // Simple, one plain level of information contains them
3317          $paths[] = new restore_path_element('log', '/logs/log');
3318  
3319          return $paths;
3320      }
3321  
3322      protected function process_log($data) {
3323          global $DB;
3324  
3325          $data = (object)($data);
3326  
3327          // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3328  
3329          $data->userid = $this->get_mappingid('user', $data->userid);
3330          $data->course = $this->get_courseid();
3331          $data->cmid = 0;
3332  
3333          // For any reason user wasn't remapped ok, stop processing this
3334          if (empty($data->userid)) {
3335              return;
3336          }
3337  
3338          // Everything ready, let's delegate to the restore_logs_processor
3339  
3340          // Set some fixed values that will save tons of DB requests
3341          $values = array(
3342              'course' => $this->get_courseid());
3343          // Get instance and process log record
3344          $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3345  
3346          // If we have data, insert it, else something went wrong in the restore_logs_processor
3347          if ($data) {
3348              if (empty($data->url)) {
3349                  $data->url = '';
3350              }
3351              if (empty($data->info)) {
3352                  $data->info = '';
3353              }
3354              // Store the data in the legacy log table if we are still using it.
3355              $manager = get_log_manager();
3356              if (method_exists($manager, 'legacy_add_to_log')) {
3357                  $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3358                      $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3359              }
3360          }
3361      }
3362  }
3363  
3364  /**
3365   * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
3366   * sharing its same structure but modifying the way records are handled
3367   */
3368  class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
3369  
3370      protected function process_log($data) {
3371          global $DB;
3372  
3373          $data = (object)($data);
3374  
3375          // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3376  
3377          $data->userid = $this->get_mappingid('user', $data->userid);
3378          $data->course = $this->get_courseid();
3379          $data->cmid = $this->task->get_moduleid();
3380  
3381          // For any reason user wasn't remapped ok, stop processing this
3382          if (empty($data->userid)) {
3383              return;
3384          }
3385  
3386          // Everything ready, let's delegate to the restore_logs_processor
3387  
3388          // Set some fixed values that will save tons of DB requests
3389          $values = array(
3390              'course' => $this->get_courseid(),
3391              'course_module' => $this->task->get_moduleid(),
3392              $this->task->get_modulename() => $this->task->get_activityid());
3393          // Get instance and process log record
3394          $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3395  
3396          // If we have data, insert it, else something went wrong in the restore_logs_processor
3397          if ($data) {
3398              if (empty($data->url)) {
3399                  $data->url = '';
3400              }
3401              if (empty($data->info)) {
3402                  $data->info = '';
3403              }
3404              // Store the data in the legacy log table if we are still using it.
3405              $manager = get_log_manager();
3406              if (method_exists($manager, 'legacy_add_to_log')) {
3407                  $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3408                      $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3409              }
3410          }
3411      }
3412  }
3413  
3414  /**
3415   * Structure step in charge of restoring the logstores.xml file for the course logs.
3416   *
3417   * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3418   * it, for logs belonging to the course level.
3419   */
3420  class restore_course_logstores_structure_step extends restore_structure_step {
3421  
3422      /**
3423       * Conditionally decide if this step should be executed.
3424       *
3425       * This function checks the following parameter:
3426       *
3427       *   1. the logstores.xml file exists
3428       *
3429       * @return bool true is safe to execute, false otherwise
3430       */
3431      protected function execute_condition() {
3432  
3433          // Check it is included in the backup.
3434          $fullpath = $this->task->get_taskbasepath();
3435          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3436          if (!file_exists($fullpath)) {
3437              // Not found, can't restore logstores.xml information.
3438              return false;
3439          }
3440  
3441          return true;
3442      }
3443  
3444      /**
3445       * Return the elements to be processed on restore of logstores.
3446       *
3447       * @return restore_path_element[] array of elements to be processed on restore.
3448       */
3449      protected function define_structure() {
3450  
3451          $paths = array();
3452  
3453          $logstore = new restore_path_element('logstore', '/logstores/logstore');
3454          $paths[] = $logstore;
3455  
3456          // Add logstore subplugin support to the 'logstore' element.
3457          $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3458  
3459          return array($logstore);
3460      }
3461  
3462      /**
3463       * Process the 'logstore' element,
3464       *
3465       * Note: This is empty by definition in backup, because stores do not share any
3466       * data between them, so there is nothing to process here.
3467       *
3468       * @param array $data element data
3469       */
3470      protected function process_logstore($data) {
3471          return;
3472      }
3473  }
3474  
3475  /**
3476   * Structure step in charge of restoring the loglastaccess.xml file for the course logs.
3477   *
3478   * This restore step will rebuild the table for user_lastaccess table.
3479   */
3480  class restore_course_loglastaccess_structure_step extends restore_structure_step {
3481  
3482      /**
3483       * Conditionally decide if this step should be executed.
3484       *
3485       * This function checks the following parameter:
3486       *
3487       *   1. the loglastaccess.xml file exists
3488       *
3489       * @return bool true is safe to execute, false otherwise
3490       */
3491      protected function execute_condition() {
3492          // Check it is included in the backup.
3493          $fullpath = $this->task->get_taskbasepath();
3494          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3495          if (!file_exists($fullpath)) {
3496              // Not found, can't restore loglastaccess.xml information.
3497              return false;
3498          }
3499  
3500          return true;
3501      }
3502  
3503      /**
3504       * Return the elements to be processed on restore of loglastaccess.
3505       *
3506       * @return restore_path_element[] array of elements to be processed on restore.
3507       */
3508      protected function define_structure() {
3509  
3510          $paths = array();
3511          // To know if we are including userinfo.
3512          $userinfo = $this->get_setting_value('users');
3513  
3514          if ($userinfo) {
3515              $paths[] = new restore_path_element('lastaccess', '/lastaccesses/lastaccess');
3516          }
3517          // Return the paths wrapped.
3518          return $paths;
3519      }
3520  
3521      /**
3522       * Process the 'lastaccess' elements.
3523       *
3524       * @param array $data element data
3525       */
3526      protected function process_lastaccess($data) {
3527          global $DB;
3528  
3529          $data = (object)$data;
3530  
3531          $data->courseid = $this->get_courseid();
3532          if (!$data->userid = $this->get_mappingid('user', $data->userid)) {
3533              return; // Nothing to do, not able to find the user to set the lastaccess time.
3534          }
3535  
3536          // Check if record does exist.
3537          $exists = $DB->get_record('user_lastaccess', array('courseid' => $data->courseid, 'userid' => $data->userid));
3538          if ($exists) {
3539              // If the time of last access of the restore is newer, then replace and update.
3540              if ($exists->timeaccess < $data->timeaccess) {
3541                  $exists->timeaccess = $data->timeaccess;
3542                  $DB->update_record('user_lastaccess', $exists);
3543              }
3544          } else {
3545              $DB->insert_record('user_lastaccess', $data);
3546          }
3547      }
3548  }
3549  
3550  /**
3551   * Structure step in charge of restoring the logstores.xml file for the activity logs.
3552   *
3553   * Note: Activity structure is completely equivalent to the course one, so just extend it.
3554   */
3555  class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3556  }
3557  
3558  /**
3559   * Restore course competencies structure step.
3560   */
3561  class restore_course_competencies_structure_step extends restore_structure_step {
3562  
3563      /**
3564       * Returns the structure.
3565       *
3566       * @return array
3567       */
3568      protected function define_structure() {
3569          $userinfo = $this->get_setting_value('users');
3570          $paths = array(
3571              new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3572              new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3573          );
3574          if ($userinfo) {
3575              $paths[] = new restore_path_element('user_competency_course',
3576                  '/course_competencies/user_competencies/user_competency');
3577          }
3578          return $paths;
3579      }
3580  
3581      /**
3582       * Process a course competency settings.
3583       *
3584       * @param array $data The data.
3585       */
3586      public function process_course_competency_settings($data) {
3587          global $DB;
3588          $data = (object) $data;
3589  
3590          // We do not restore the course settings during merge.
3591          $target = $this->get_task()->get_target();
3592          if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3593              return;
3594          }
3595  
3596          $courseid = $this->task->get_courseid();
3597          $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3598              array('courseid' => $courseid));
3599  
3600          // Strangely the course settings already exist, let's just leave them as is then.
3601          if ($exists) {
3602              $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3603              return;
3604          }
3605  
3606          $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3607          $settings = new \core_competency\course_competency_settings(0, $data);
3608          $settings->create();
3609      }
3610  
3611      /**
3612       * Process a course competency.
3613       *
3614       * @param array $data The data.
3615       */
3616      public function process_course_competency($data) {
3617          $data = (object) $data;
3618  
3619          // Mapping the competency by ID numbers.
3620          $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3621          if (!$framework) {
3622              return;
3623          }
3624          $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3625              'competencyframeworkid' => $framework->get('id')));
3626          if (!$competency) {
3627              return;
3628          }
3629          $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get('id'));
3630  
3631          $params = array(
3632              'competencyid' => $competency->get('id'),
3633              'courseid' => $this->task->get_courseid()
3634          );
3635          $query = 'competencyid = :competencyid AND courseid = :courseid';
3636          $existing = \core_competency\course_competency::record_exists_select($query, $params);
3637  
3638          if (!$existing) {
3639              // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3640              $record = (object) $params;
3641              $record->ruleoutcome = $data->ruleoutcome;
3642              $coursecompetency = new \core_competency\course_competency(0, $record);
3643              $coursecompetency->create();
3644          }
3645      }
3646  
3647      /**
3648       * Process the user competency course.
3649       *
3650       * @param array $data The data.
3651       */
3652      public function process_user_competency_course($data) {
3653          global $USER, $DB;
3654          $data = (object) $data;
3655  
3656          $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3657          if (!$data->competencyid) {
3658              // This is strange, the competency does not belong to the course.
3659              return;
3660          } else if ($data->grade === null) {
3661              // We do not need to do anything when there is no grade.
3662              return;
3663          }
3664  
3665          $data->userid = $this->get_mappingid('user', $data->userid);
3666          $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3667  
3668          // The method add_evidence also sets the course rating.
3669          \core_competency\api::add_evidence($data->userid,
3670                                             $data->competencyid,
3671                                             $this->task->get_contextid(),
3672                                             \core_competency\evidence::ACTION_OVERRIDE,
3673                                             'evidence_courserestored',
3674                                             'core_competency',
3675                                             $shortname,
3676                                             false,
3677                                             null,
3678                                             $data->grade,
3679                                             $USER->id);
3680      }
3681  
3682      /**
3683       * Execute conditions.
3684       *
3685       * @return bool
3686       */
3687      protected function execute_condition() {
3688  
3689          // Do not execute if competencies are not included.
3690          if (!$this->get_setting_value('competencies')) {
3691              return false;
3692          }
3693  
3694          // Do not execute if the competencies XML file is not found.
3695          $fullpath = $this->task->get_taskbasepath();
3696          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3697          if (!file_exists($fullpath)) {
3698              return false;
3699          }
3700  
3701          return true;
3702      }
3703  }
3704  
3705  /**
3706   * Restore activity competencies structure step.
3707   */
3708  class restore_activity_competencies_structure_step extends restore_structure_step {
3709  
3710      /**
3711       * Defines the structure.
3712       *
3713       * @return array
3714       */
3715      protected function define_structure() {
3716          $paths = array(
3717              new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3718          );
3719          return $paths;
3720      }
3721  
3722      /**
3723       * Process a course module competency.
3724       *
3725       * @param array $data The data.
3726       */
3727      public function process_course_module_competency($data) {
3728          $data = (object) $data;
3729  
3730          // Mapping the competency by ID numbers.
3731          $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3732          if (!$framework) {
3733              return;
3734          }
3735          $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3736              'competencyframeworkid' => $framework->get('id')));
3737          if (!$competency) {
3738              return;
3739          }
3740  
3741          $params = array(
3742              'competencyid' => $competency->get('id'),
3743              'cmid' => $this->task->get_moduleid()
3744          );
3745          $query = 'competencyid = :competencyid AND cmid = :cmid';
3746          $existing = \core_competency\course_module_competency::record_exists_select($query, $params);
3747  
3748          if (!$existing) {
3749              // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3750              $record = (object) $params;
3751              $record->ruleoutcome = $data->ruleoutcome;
3752              $record->overridegrade = $data->overridegrade;
3753              $coursemodulecompetency = new \core_competency\course_module_competency(0, $record);
3754              $coursemodulecompetency->create();
3755          }
3756      }
3757  
3758      /**
3759       * Execute conditions.
3760       *
3761       * @return bool
3762       */
3763      protected function execute_condition() {
3764  
3765          // Do not execute if competencies are not included.
3766          if (!$this->get_setting_value('competencies')) {
3767              return false;
3768          }
3769  
3770          // Do not execute if the competencies XML file is not found.
3771          $fullpath = $this->task->get_taskbasepath();
3772          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3773          if (!file_exists($fullpath)) {
3774              return false;
3775          }
3776  
3777          return true;
3778      }
3779  }
3780  
3781  /**
3782   * Defines the restore step for advanced grading methods attached to the activity module
3783   */
3784  class restore_activity_grading_structure_step extends restore_structure_step {
3785  
3786      /**
3787       * This step is executed only if the grading file is present
3788       */
3789       protected function execute_condition() {
3790  
3791          if ($this->get_courseid() == SITEID) {
3792              return false;
3793          }
3794  
3795          $fullpath = $this->task->get_taskbasepath();
3796          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3797          if (!file_exists($fullpath)) {
3798              return false;
3799          }
3800  
3801          return true;
3802      }
3803  
3804  
3805      /**
3806       * Declares paths in the grading.xml file we are interested in
3807       */
3808      protected function define_structure() {
3809  
3810          $paths = array();
3811          $userinfo = $this->get_setting_value('userinfo');
3812  
3813          $area = new restore_path_element('grading_area', '/areas/area');
3814          $paths[] = $area;
3815          // attach local plugin stucture to $area element
3816          $this->add_plugin_structure('local', $area);
3817  
3818          $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3819          $paths[] = $definition;
3820          $this->add_plugin_structure('gradingform', $definition);
3821          // attach local plugin stucture to $definition element
3822          $this->add_plugin_structure('local', $definition);
3823  
3824  
3825          if ($userinfo) {
3826              $instance = new restore_path_element('grading_instance',
3827                  '/areas/area/definitions/definition/instances/instance');
3828              $paths[] = $instance;
3829              $this->add_plugin_structure('gradingform', $instance);
3830              // attach local plugin stucture to $intance element
3831              $this->add_plugin_structure('local', $instance);
3832          }
3833  
3834          return $paths;
3835      }
3836  
3837      /**
3838       * Processes one grading area element
3839       *
3840       * @param array $data element data
3841       */
3842      protected function process_grading_area($data) {
3843          global $DB;
3844  
3845          $task = $this->get_task();
3846          $data = (object)$data;
3847          $oldid = $data->id;
3848          $data->component = 'mod_'.$task->get_modulename();
3849          $data->contextid = $task->get_contextid();
3850  
3851          $newid = $DB->insert_record('grading_areas', $data);
3852          $this->set_mapping('grading_area', $oldid, $newid);
3853      }
3854  
3855      /**
3856       * Processes one grading definition element
3857       *
3858       * @param array $data element data
3859       */
3860      protected function process_grading_definition($data) {
3861          global $DB;
3862  
3863          $task = $this->get_task();
3864          $data = (object)$data;
3865          $oldid = $data->id;
3866          $data->areaid = $this->get_new_parentid('grading_area');
3867          $data->copiedfromid = null;
3868          $data->timecreated = time();
3869          $data->usercreated = $task->get_userid();
3870          $data->timemodified = $data->timecreated;
3871          $data->usermodified = $data->usercreated;
3872  
3873          $newid = $DB->insert_record('grading_definitions', $data);
3874          $this->set_mapping('grading_definition', $oldid, $newid, true);
3875      }
3876  
3877      /**
3878       * Processes one grading form instance element
3879       *
3880       * @param array $data element data
3881       */
3882      protected function process_grading_instance($data) {
3883          global $DB;
3884  
3885          $data = (object)$data;
3886  
3887          // new form definition id
3888          $newformid = $this->get_new_parentid('grading_definition');
3889  
3890          // get the name of the area we are restoring to
3891          $sql = "SELECT ga.areaname
3892                    FROM {grading_definitions} gd
3893                    JOIN {grading_areas} ga ON gd.areaid = ga.id
3894                   WHERE gd.id = ?";
3895          $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3896  
3897          // get the mapped itemid - the activity module is expected to define the mappings
3898          // for each gradable area
3899          $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3900  
3901          $oldid = $data->id;
3902          $data->definitionid = $newformid;
3903          $data->raterid = $this->get_mappingid('user', $data->raterid);
3904          $data->itemid = $newitemid;
3905  
3906          $newid = $DB->insert_record('grading_instances', $data);
3907          $this->set_mapping('grading_instance', $oldid, $newid);
3908      }
3909  
3910      /**
3911       * Final operations when the database records are inserted
3912       */
3913      protected function after_execute() {
3914          // Add files embedded into the definition description
3915          $this->add_related_files('grading', 'description', 'grading_definition');
3916      }
3917  }
3918  
3919  
3920  /**
3921   * This structure step restores the grade items associated with one activity
3922   * All the grade items are made child of the "course" grade item but the original
3923   * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3924   * the complete gradebook (categories and calculations), that information is
3925   * available there
3926   */
3927  class restore_activity_grades_structure_step extends restore_structure_step {
3928  
3929      /**
3930       * No grades in front page.
3931       * @return bool
3932       */
3933      protected function execute_condition() {
3934          return ($this->get_courseid() != SITEID);
3935      }
3936  
3937      protected function define_structure() {
3938  
3939          $paths = array();
3940          $userinfo = $this->get_setting_value('userinfo');
3941  
3942          $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3943          $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3944          if ($userinfo) {
3945              $paths[] = new restore_path_element('grade_grade',
3946                             '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3947          }
3948          return $paths;
3949      }
3950  
3951      protected function process_grade_item($data) {
3952          global $DB;
3953  
3954          $data = (object)($data);
3955          $oldid       = $data->id;        // We'll need these later
3956          $oldparentid = $data->categoryid;
3957          $courseid = $this->get_courseid();
3958  
3959          $idnumber = null;
3960          if (!empty($data->idnumber)) {
3961              // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
3962              // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
3963              // so the best is to keep the ones already in the gradebook
3964              // Potential problem: duplicates if same items are restored more than once. :-(
3965              // This needs to be fixed in some way (outcomes & activities with multiple items)
3966              // $data->idnumber     = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
3967              // In any case, verify always for uniqueness
3968              $sql = "SELECT cm.id
3969                        FROM {course_modules} cm
3970                       WHERE cm.course = :courseid AND
3971                             cm.idnumber = :idnumber AND
3972                             cm.id <> :cmid";
3973              $params = array(
3974                  'courseid' => $courseid,
3975                  'idnumber' => $data->idnumber,
3976                  'cmid' => $this->task->get_moduleid()
3977              );
3978              if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
3979                  $idnumber = $data->idnumber;
3980              }
3981          }
3982  
3983          if (!empty($data->categoryid)) {
3984              // If the grade category id of the grade item being restored belongs to this course
3985              // then it is a fair assumption that this is the correct grade category for the activity
3986              // and we should leave it in place, if not then unset it.
3987              // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
3988              $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
3989              if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
3990                  unset($data->categoryid);
3991              }
3992          }
3993  
3994          unset($data->id);
3995          $data->courseid     = $this->get_courseid();
3996          $data->iteminstance = $this->task->get_activityid();
3997          $data->idnumber     = $idnumber;
3998          $data->scaleid      = $this->get_mappingid('scale', $data->scaleid);
3999          $data->outcomeid    = $this->get_mappingid('outcome', $data->outcomeid);
4000  
4001          $gradeitem = new grade_item($data, false);
4002          $gradeitem->insert('restore');
4003  
4004          //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
4005          $gradeitem->sortorder = $data->sortorder;
4006          $gradeitem->update('restore');
4007  
4008          // Set mapping, saving the original category id into parentitemid
4009          // gradebook restore (final task) will need it to reorganise items
4010          $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
4011      }
4012  
4013      protected function process_grade_grade($data) {
4014          global $CFG;
4015  
4016          require_once($CFG->libdir . '/grade/constants.php');
4017  
4018          $data = (object)($data);
4019          $olduserid = $data->userid;
4020          $oldid = $data->id;
4021          unset($data->id);
4022  
4023          $data->itemid = $this->get_new_parentid('grade_item');
4024  
4025          $data->userid = $this->get_mappingid('user', $data->userid, null);
4026          if (!empty($data->userid)) {
4027              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4028              $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4029  
4030              $grade = new grade_grade($data, false);
4031              $grade->insert('restore');
4032  
4033              $this->set_mapping('grade_grades', $oldid, $grade->id, true);
4034  
4035              $this->add_related_files(
4036                  GRADE_FILE_COMPONENT,
4037                  GRADE_FEEDBACK_FILEAREA,
4038                  'grade_grades',
4039                  null,
4040                  $oldid
4041              );
4042          } else {
4043              debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
4044          }
4045      }
4046  
4047      /**
4048       * process activity grade_letters. Note that, while these are possible,
4049       * because grade_letters are contextid based, in practice, only course
4050       * context letters can be defined. So we keep here this method knowing
4051       * it won't be executed ever. gradebook restore will restore course letters.
4052       */
4053      protected function process_grade_letter($data) {
4054          global $DB;
4055  
4056          $data['contextid'] = $this->task->get_contextid();
4057          $gradeletter = (object)$data;
4058  
4059          // Check if it exists before adding it
4060          unset($data['id']);
4061          if (!$DB->record_exists('grade_letters', $data)) {
4062              $newitemid = $DB->insert_record('grade_letters', $gradeletter);
4063          }
4064          // no need to save any grade_letter mapping
4065      }
4066  
4067      public function after_restore() {
4068          // Fix grade item's sortorder after restore, as it might have duplicates.
4069          $courseid = $this->get_task()->get_courseid();
4070          grade_item::fix_duplicate_sortorder($courseid);
4071      }
4072  }
4073  
4074  /**
4075   * Step in charge of restoring the grade history of an activity.
4076   *
4077   * This step is added to the task regardless of the setting 'grade_histories'.
4078   * The reason is to allow for a more flexible step in case the logic needs to be
4079   * split accross different settings to control the history of items and/or grades.
4080   */
4081  class restore_activity_grade_history_structure_step extends restore_structure_step {
4082  
4083      /**
4084       * This step is executed only if the grade history file is present.
4085       */
4086       protected function execute_condition() {
4087  
4088          if ($this->get_courseid() == SITEID) {
4089              return false;
4090          }
4091  
4092          $fullpath = $this->task->get_taskbasepath();
4093          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4094          if (!file_exists($fullpath)) {
4095              return false;
4096          }
4097          return true;
4098      }
4099  
4100      protected function define_structure() {
4101          $paths = array();
4102  
4103          // Settings to use.
4104          $userinfo = $this->get_setting_value('userinfo');
4105          $history = $this->get_setting_value('grade_histories');
4106  
4107          if ($userinfo && $history) {
4108              $paths[] = new restore_path_element('grade_grade',
4109                 '/grade_history/grade_grades/grade_grade');
4110          }
4111  
4112          return $paths;
4113      }
4114  
4115      protected function process_grade_grade($data) {
4116          global $CFG, $DB;
4117  
4118          require_once($CFG->libdir . '/grade/constants.php');
4119  
4120          $data = (object) $data;
4121          $oldhistoryid = $data->id;
4122          $olduserid = $data->userid;
4123          unset($data->id);
4124  
4125          $data->userid = $this->get_mappingid('user', $data->userid, null);
4126          if (!empty($data->userid)) {
4127              // Do not apply the date offsets as this is history.
4128              $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
4129              $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
4130              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4131              $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4132  
4133              $newhistoryid = $DB->insert_record('grade_grades_history', $data);
4134  
4135              $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
4136  
4137              $this->add_related_files(
4138                  GRADE_FILE_COMPONENT,
4139                  GRADE_HISTORY_FEEDBACK_FILEAREA,
4140                  'grade_grades_history',
4141                  null,
4142                  $oldhistoryid
4143              );
4144          } else {
4145              $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
4146              $this->log($message, backup::LOG_DEBUG);
4147          }
4148      }
4149  }
4150  
4151  /**
4152   * This structure steps restores the content bank content
4153   */
4154  class restore_contentbankcontent_structure_step extends restore_structure_step {
4155  
4156      /**
4157       * Define structure for content bank step
4158       */
4159      protected function define_structure() {
4160  
4161          $paths = [];
4162          $paths[] = new restore_path_element('contentbankcontent', '/contents/content');
4163  
4164          return $paths;
4165      }
4166  
4167      /**
4168       * Define data processed for content bank
4169       *
4170       * @param mixed  $data
4171       */
4172      public function process_contentbankcontent($data) {
4173          global $DB;
4174  
4175          $data = (object)$data;
4176          $oldid = $data->id;
4177  
4178          $params = [
4179              'name'           => $data->name,
4180              'contextid'      => $this->task->get_contextid(),
4181              'contenttype'    => $data->contenttype,
4182              'instanceid'     => $data->instanceid,
4183              'timecreated'    => $data->timecreated,
4184          ];
4185          $exists = $DB->record_exists('contentbank_content', $params);
4186          if (!$exists) {
4187              $params['configdata'] = $data->configdata;
4188              $params['timemodified'] = time();
4189  
4190              // Trying to map users. Users cannot always be mapped, e.g. when copying.
4191              $params['usercreated'] = $this->get_mappingid('user', $data->usercreated);
4192              if (!$params['usercreated']) {
4193                  // Leave the content creator unchanged when we are restoring the same site.
4194                  // Otherwise use current user id.
4195                  if ($this->task->is_samesite()) {
4196                      $params['usercreated'] = $data->usercreated;
4197                  } else {
4198                      $params['usercreated'] = $this->task->get_userid();
4199                  }
4200              }
4201              $params['usermodified'] = $this->get_mappingid('user', $data->usermodified);
4202              if (!$params['usermodified']) {
4203                  // Leave the content modifier unchanged when we are restoring the same site.
4204                  // Otherwise use current user id.
4205                  if ($this->task->is_samesite()) {
4206                      $params['usermodified'] = $data->usermodified;
4207                  } else {
4208                      $params['usermodified'] = $this->task->get_userid();
4209                  }
4210              }
4211  
4212              $newitemid = $DB->insert_record('contentbank_content', $params);
4213              $this->set_mapping('contentbank_content', $oldid, $newitemid, true);
4214          }
4215      }
4216  
4217      /**
4218       * Define data processed after execute for content bank
4219       */
4220      protected function after_execute() {
4221          // Add related files.
4222          $this->add_related_files('contentbank', 'public', 'contentbank_content');
4223      }
4224  }
4225  
4226  /**
4227   * This structure steps restores the xAPI states.
4228   */
4229  class restore_xapistate_structure_step extends restore_structure_step {
4230  
4231      /**
4232       * Define structure for xAPI state step
4233       */
4234      protected function define_structure() {
4235          return [new restore_path_element('xapistate', '/states/state')];
4236      }
4237  
4238      /**
4239       * Define data processed for xAPI state.
4240       *
4241       * @param array|stdClass $data
4242       */
4243      public function process_xapistate($data) {
4244          global $DB;
4245  
4246          $data = (object)$data;
4247          $oldid = $data->id;
4248          $exists = false;
4249  
4250          $params = [
4251              'component' => $data->component,
4252              'itemid' => $this->task->get_contextid(),
4253              // Set stateid to 'restored', to let plugins identify the origin of this state is a backup.
4254              'stateid' => 'restored',
4255              'statedata' => $data->statedata,
4256              'registration' => $data->registration,
4257              'timecreated' => $data->timecreated,
4258              'timemodified' => time(),
4259          ];
4260  
4261          // Trying to map users. Users cannot always be mapped, for instance, when copying.
4262          $params['userid'] = $this->get_mappingid('user', $data->userid);
4263          if (!$params['userid']) {
4264              // Leave the userid unchanged when we are restoring the same site.
4265              if ($this->task->is_samesite()) {
4266                  $params['userid'] = $data->userid;
4267              }
4268              $filter = $params;
4269              unset($filter['statedata']);
4270              $exists = $DB->record_exists('xapi_states', $filter);
4271          }
4272  
4273          if (!$exists && $params['userid']) {
4274              // Only insert the record if the user exists or can be mapped.
4275              $newitemid = $DB->insert_record('xapi_states', $params);
4276              $this->set_mapping('xapi_states', $oldid, $newitemid, true);
4277          }
4278      }
4279  }
4280  
4281  /**
4282   * This structure steps restores one instance + positions of one block
4283   * Note: Positions corresponding to one existing context are restored
4284   * here, but all the ones having unknown contexts are sent to backup_ids
4285   * for a later chance to be restored at the end (final task)
4286   */
4287  class restore_block_instance_structure_step extends restore_structure_step {
4288  
4289      protected function define_structure() {
4290  
4291          $paths = array();
4292  
4293          $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
4294          $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
4295  
4296          return $paths;
4297      }
4298  
4299      public function process_block($data) {
4300          global $DB, $CFG;
4301  
4302          $data = (object)$data; // Handy
4303          $oldcontextid = $data->contextid;
4304          $oldid        = $data->id;
4305          $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
4306  
4307          // Look for the parent contextid
4308          if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
4309              // Parent contextid does not exist, ignore this block.
4310              return false;
4311          }
4312  
4313          // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
4314          // If there is already one block of that type in the parent context
4315          // and the block is not multiple, stop processing
4316          // Use blockslib loader / method executor
4317          if (!$bi = block_instance($data->blockname)) {
4318              return false;
4319          }
4320  
4321          if (!$bi->instance_allow_multiple()) {
4322              // The block cannot be added twice, so we will check if the same block is already being
4323              // displayed on the same page. For this, rather than mocking a page and using the block_manager
4324              // we use a similar query to the one in block_manager::load_blocks(), this will give us
4325              // a very good idea of the blocks already displayed in the context.
4326              $params =  array(
4327                  'blockname' => $data->blockname
4328              );
4329  
4330              // Context matching test.
4331              $context = context::instance_by_id($data->parentcontextid);
4332              $contextsql = 'bi.parentcontextid = :contextid';
4333              $params['contextid'] = $context->id;
4334  
4335              $parentcontextids = $context->get_parent_context_ids();
4336              if ($parentcontextids) {
4337                  list($parentcontextsql, $parentcontextparams) =
4338                          $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
4339                  $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
4340                  $params = array_merge($params, $parentcontextparams);
4341              }
4342  
4343              // Page type pattern test.
4344              $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
4345              list($pagetypepatternsql, $pagetypepatternparams) =
4346                  $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
4347              $params = array_merge($params, $pagetypepatternparams);
4348  
4349              // Sub page pattern test.
4350              $subpagepatternsql = 'bi.subpagepattern IS NULL';
4351              if ($data->subpagepattern !== null) {
4352                  $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
4353                  $params['subpagepattern'] = $data->subpagepattern;
4354              }
4355  
4356              $existingblock = $DB->get_records_sql("SELECT bi.id
4357                                                  FROM {block_instances} bi
4358                                                  JOIN {block} b ON b.name = bi.blockname
4359                                                 WHERE bi.blockname = :blockname
4360                                                   AND $contextsql
4361                                                   AND bi.pagetypepattern $pagetypepatternsql
4362                                                   AND $subpagepatternsql", $params);
4363              if (!empty($existingblock)) {
4364                  // Save the context mapping in case something else is linking to this block's context.
4365                  $newcontext = context_block::instance(reset($existingblock)->id);
4366                  $this->set_mapping('context', $oldcontextid, $newcontext->id);
4367                  // There is at least one very similar block visible on the page where we
4368                  // are trying to restore the block. In these circumstances the block API
4369                  // would not allow the user to add another instance of the block, so we
4370                  // apply the same rule here.
4371                  return false;
4372              }
4373          }
4374  
4375          // If there is already one block of that type in the parent context
4376          // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
4377          // stop processing
4378          $params = array(
4379              'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
4380              'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
4381              'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
4382          if ($birecs = $DB->get_records('block_instances', $params)) {
4383              foreach($birecs as $birec) {
4384                  if ($birec->configdata == $data->configdata) {
4385                      // Save the context mapping in case something else is linking to this block's context.
4386                      $newcontext = context_block::instance($birec->id);
4387                      $this->set_mapping('context', $oldcontextid, $newcontext->id);
4388                      return false;
4389                  }
4390              }
4391          }
4392  
4393          // Set task old contextid, blockid and blockname once we know them
4394          $this->task->set_old_contextid($oldcontextid);
4395          $this->task->set_old_blockid($oldid);
4396          $this->task->set_blockname($data->blockname);
4397  
4398          // Let's look for anything within configdata neededing processing
4399          // (nulls and uses of legacy file.php)
4400          if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
4401              $configdata = array_filter(
4402                  (array) unserialize_object(base64_decode($data->configdata)),
4403                  static function($value): bool {
4404                      return !($value instanceof __PHP_Incomplete_Class);
4405                  }
4406              );
4407  
4408              foreach ($configdata as $attribute => $value) {
4409                  if (in_array($attribute, $attrstotransform)) {
4410                      $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
4411                  }
4412              }
4413              $data->configdata = base64_encode(serialize((object)$configdata));
4414          }
4415  
4416          // Set timecreated, timemodified if not included (older backup).
4417          if (empty($data->timecreated)) {
4418              $data->timecreated = time();
4419          }
4420          if (empty($data->timemodified)) {
4421              $data->timemodified = $data->timecreated;
4422          }
4423  
4424          // Create the block instance
4425          $newitemid = $DB->insert_record('block_instances', $data);
4426          // Save the mapping (with restorefiles support)
4427          $this->set_mapping('block_instance', $oldid, $newitemid, true);
4428          // Create the block context
4429          $newcontextid = context_block::instance($newitemid)->id;
4430          // Save the block contexts mapping and sent it to task
4431          $this->set_mapping('context', $oldcontextid, $newcontextid);
4432          $this->task->set_contextid($newcontextid);
4433          $this->task->set_blockid($newitemid);
4434  
4435          // Restore block fileareas if declared
4436          $component = 'block_' . $this->task->get_blockname();
4437          foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
4438              $this->add_related_files($component, $filearea, null);
4439          }
4440  
4441          // Process block positions, creating them or accumulating for final step
4442          foreach($positions as $position) {
4443              $position = (object)$position;
4444              $position->blockinstanceid = $newitemid; // The instance is always the restored one
4445              // If position is for one already mapped (known) contextid
4446              // process it now, creating the position
4447              if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
4448                  $position->contextid = $newpositionctxid;
4449                  // Create the block position
4450                  $DB->insert_record('block_positions', $position);
4451  
4452              // The position belongs to an unknown context, send it to backup_ids
4453              // to process them as part of the final steps of restore. We send the
4454              // whole $position object there, hence use the low level method.
4455              } else {
4456                  restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
4457              }
4458          }
4459      }
4460  }
4461  
4462  /**
4463   * Structure step to restore common course_module information
4464   *
4465   * This step will process the module.xml file for one activity, in order to restore
4466   * the corresponding information to the course_modules table, skipping various bits
4467   * of information based on CFG settings (groupings, completion...) in order to fullfill
4468   * all the reqs to be able to create the context to be used by all the rest of steps
4469   * in the activity restore task
4470   */
4471  class restore_module_structure_step extends restore_structure_step {
4472  
4473      protected function define_structure() {
4474          global $CFG;
4475  
4476          $paths = array();
4477  
4478          $module = new restore_path_element('module', '/module');
4479          $paths[] = $module;
4480          if ($CFG->enableavailability) {
4481              $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4482              $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4483          }
4484  
4485          $paths[] = new restore_path_element('tag', '/module/tags/tag');
4486  
4487          // Apply for 'format' plugins optional paths at module level
4488          $this->add_plugin_structure('format', $module);
4489  
4490          // Apply for 'report' plugins optional paths at module level.
4491          $this->add_plugin_structure('report', $module);
4492  
4493          // Apply for 'plagiarism' plugins optional paths at module level
4494          $this->add_plugin_structure('plagiarism', $module);
4495  
4496          // Apply for 'local' plugins optional paths at module level
4497          $this->add_plugin_structure('local', $module);
4498  
4499          // Apply for 'admin tool' plugins optional paths at module level.
4500          $this->add_plugin_structure('tool', $module);
4501  
4502          return $paths;
4503      }
4504  
4505      protected function process_module($data) {
4506          global $CFG, $DB;
4507  
4508          $data = (object)$data;
4509          $oldid = $data->id;
4510          $this->task->set_old_moduleversion($data->version);
4511  
4512          $data->course = $this->task->get_courseid();
4513          $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
4514          // Map section (first try by course_section mapping match. Useful in course and section restores)
4515          $data->section = $this->get_mappingid('course_section', $data->sectionid);
4516          if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
4517              $params = array(
4518                  'course' => $this->get_courseid(),
4519                  'section' => $data->sectionnumber);
4520              $data->section = $DB->get_field('course_sections', 'id', $params);
4521          }
4522          if (!$data->section) { // sectionnumber failed, try to get first section in course
4523              $params = array(
4524                  'course' => $this->get_courseid());
4525              $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
4526          }
4527          if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
4528              $sectionrec = array(
4529                  'course' => $this->get_courseid(),
4530                  'section' => 0,
4531                  'timemodified' => time());
4532              $DB->insert_record('course_sections', $sectionrec); // section 0
4533              $sectionrec = array(
4534                  'course' => $this->get_courseid(),
4535                  'section' => 1,
4536                  'timemodified' => time());
4537              $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
4538          }
4539          $data->groupingid= $this->get_mappingid('grouping', $data->groupingid);      // grouping
4540          if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) {        // idnumber uniqueness
4541              $data->idnumber = '';
4542          }
4543          if (empty($CFG->enablecompletion)) { // completion
4544              $data->completion = 0;
4545              $data->completiongradeitemnumber = null;
4546              $data->completionview = 0;
4547              $data->completionexpected = 0;
4548          } else {
4549              $data->completionexpected = $this->apply_date_offset($data->completionexpected);
4550          }
4551          if (empty($CFG->enableavailability)) {
4552              $data->availability = null;
4553          }
4554          // Backups that did not include showdescription, set it to default 0
4555          // (this is not totally necessary as it has a db default, but just to
4556          // be explicit).
4557          if (!isset($data->showdescription)) {
4558              $data->showdescription = 0;
4559          }
4560          $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
4561  
4562          if (empty($data->availability)) {
4563              // If there are legacy availablility data fields (and no new format data),
4564              // convert the old fields.
4565              $data->availability = \core_availability\info::convert_legacy_fields(
4566                      $data, false);
4567          } else if (!empty($data->groupmembersonly)) {
4568              // There is current availability data, but it still has groupmembersonly
4569              // as well (2.7 backups), convert just that part.
4570              require_once($CFG->dirroot . '/lib/db/upgradelib.php');
4571              $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
4572          }
4573  
4574          if (!has_capability('moodle/course:setforcedlanguage', context_course::instance($data->course))) {
4575              unset($data->lang);
4576          }
4577  
4578          // course_module record ready, insert it
4579          $newitemid = $DB->insert_record('course_modules', $data);
4580          // save mapping
4581          $this->set_mapping('course_module', $oldid, $newitemid);
4582          // set the new course_module id in the task
4583          $this->task->set_moduleid($newitemid);
4584          // we can now create the context safely
4585          $ctxid = context_module::instance($newitemid)->id;
4586          // set the new context id in the task
4587          $this->task->set_contextid($ctxid);
4588          // update sequence field in course_section
4589          if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
4590              $sequence .= ',' . $newitemid;
4591          } else {
4592              $sequence = $newitemid;
4593          }
4594  
4595          $updatesection = new \stdClass();
4596          $updatesection->id = $data->section;
4597          $updatesection->sequence = $sequence;
4598          $updatesection->timemodified = time();
4599          $DB->update_record('course_sections', $updatesection);
4600  
4601          // If there is the legacy showavailability data, store this for later use.
4602          // (This data is not present when restoring 'new' backups.)
4603          if (isset($data->showavailability)) {
4604              // Cache the showavailability flag using the backup_ids data field.
4605              restore_dbops::set_backup_ids_record($this->get_restoreid(),
4606                      'module_showavailability', $newitemid, 0, null,
4607                      (object)array('showavailability' => $data->showavailability));
4608          }
4609      }
4610  
4611      /**
4612       * Fetch all the existing because tag_set() deletes them
4613       * so everything must be reinserted on each call.
4614       *
4615       * @param stdClass $data Record data
4616       */
4617      protected function process_tag($data) {
4618          global $CFG;
4619  
4620          $data = (object)$data;
4621  
4622          if (core_tag_tag::is_enabled('core', 'course_modules')) {
4623              $modcontext = context::instance_by_id($this->task->get_contextid());
4624              $instanceid = $this->task->get_moduleid();
4625  
4626              core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4627          }
4628      }
4629  
4630      /**
4631       * Process the legacy availability table record. This table does not exist
4632       * in Moodle 2.7+ but we still support restore.
4633       *
4634       * @param stdClass $data Record data
4635       */
4636      protected function process_availability($data) {
4637          $data = (object)$data;
4638          // Simply going to store the whole availability record now, we'll process
4639          // all them later in the final task (once all activities have been restored)
4640          // Let's call the low level one to be able to store the whole object
4641          $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
4642          restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
4643      }
4644  
4645      /**
4646       * Process the legacy availability fields table record. This table does not
4647       * exist in Moodle 2.7+ but we still support restore.
4648       *
4649       * @param stdClass $data Record data
4650       */
4651      protected function process_availability_field($data) {
4652          global $DB, $CFG;
4653          require_once($CFG->dirroot.'/user/profile/lib.php');
4654  
4655          $data = (object)$data;
4656          // Mark it is as passed by default
4657          $passed = true;
4658          $customfieldid = null;
4659  
4660          // If a customfield has been used in order to pass we must be able to match an existing
4661          // customfield by name (data->customfield) and type (data->customfieldtype)
4662          if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
4663              // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4664              // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4665              $passed = false;
4666          } else if (!empty($data->customfield)) {
4667              $field = profile_get_custom_field_data_by_shortname($data->customfield);
4668              $passed = $field && $field->datatype == $data->customfieldtype;
4669          }
4670  
4671          if ($passed) {
4672              // Create the object to insert into the database
4673              $availfield = new stdClass();
4674              $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
4675              $availfield->userfield = $data->userfield;
4676              $availfield->customfieldid = $customfieldid;
4677              $availfield->operator = $data->operator;
4678              $availfield->value = $data->value;
4679  
4680              // Get showavailability option.
4681              $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4682                      'module_showavailability', $availfield->coursemoduleid);
4683              if (!$showrec) {
4684                  // Should not happen.
4685                  throw new coding_exception('No matching showavailability record');
4686              }
4687              $show = $showrec->info->showavailability;
4688  
4689              // The $availfieldobject is now in the format used in the old
4690              // system. Interpret this and convert to new system.
4691              $currentvalue = $DB->get_field('course_modules', 'availability',
4692                      array('id' => $availfield->coursemoduleid), MUST_EXIST);
4693              $newvalue = \core_availability\info::add_legacy_availability_field_condition(
4694                      $currentvalue, $availfield, $show);
4695              $DB->set_field('course_modules', 'availability', $newvalue,
4696                      array('id' => $availfield->coursemoduleid));
4697          }
4698      }
4699      /**
4700       * This method will be executed after the rest of the restore has been processed.
4701       *
4702       * Update old tag instance itemid(s).
4703       */
4704      protected function after_restore() {
4705          global $DB;
4706  
4707          $contextid = $this->task->get_contextid();
4708          $instanceid = $this->task->get_activityid();
4709          $olditemid = $this->task->get_old_activityid();
4710  
4711          $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4712      }
4713  }
4714  
4715  /**
4716   * Structure step that will process the user activity completion
4717   * information if all these conditions are met:
4718   *  - Target site has completion enabled ($CFG->enablecompletion)
4719   *  - Activity includes completion info (file_exists)
4720   */
4721  class restore_userscompletion_structure_step extends restore_structure_step {
4722      /**
4723       * To conditionally decide if this step must be executed
4724       * Note the "settings" conditions are evaluated in the
4725       * corresponding task. Here we check for other conditions
4726       * not being restore settings (files, site settings...)
4727       */
4728       protected function execute_condition() {
4729           global $CFG;
4730  
4731           // Completion disabled in this site, don't execute
4732           if (empty($CFG->enablecompletion)) {
4733               return false;
4734           }
4735  
4736          // No completion on the front page.
4737          if ($this->get_courseid() == SITEID) {
4738              return false;
4739          }
4740  
4741           // No user completion info found, don't execute
4742          $fullpath = $this->task->get_taskbasepath();
4743          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4744           if (!file_exists($fullpath)) {
4745               return false;
4746           }
4747  
4748           // Arrived here, execute the step
4749           return true;
4750       }
4751  
4752       protected function define_structure() {
4753  
4754          $paths = array();
4755  
4756          // Restore completion.
4757          $paths[] = new restore_path_element('completion', '/completions/completion');
4758  
4759          // Restore completion view.
4760          $paths[] = new restore_path_element('completionview', '/completions/completionviews/completionview');
4761  
4762          return $paths;
4763      }
4764  
4765      protected function process_completion($data) {
4766          global $DB;
4767  
4768          $data = (object)$data;
4769  
4770          $data->coursemoduleid = $this->task->get_moduleid();
4771          $data->userid = $this->get_mappingid('user', $data->userid);
4772  
4773          // Find the existing record
4774          $existing = $DB->get_record('course_modules_completion', array(
4775                  'coursemoduleid' => $data->coursemoduleid,
4776                  'userid' => $data->userid), 'id, timemodified');
4777          // Check we didn't already insert one for this cmid and userid
4778          // (there aren't supposed to be duplicates in that field, but
4779          // it was possible until MDL-28021 was fixed).
4780          if ($existing) {
4781              // Update it to these new values, but only if the time is newer
4782              if ($existing->timemodified < $data->timemodified) {
4783                  $data->id = $existing->id;
4784                  $DB->update_record('course_modules_completion', $data);
4785              }
4786          } else {
4787              // Normal entry where it doesn't exist already
4788              $DB->insert_record('course_modules_completion', $data);
4789          }
4790  
4791          // Add viewed to course_modules_viewed.
4792          if (isset($data->viewed) && $data->viewed) {
4793              $dataview = clone($data);
4794              unset($dataview->id);
4795              unset($dataview->viewed);
4796              $dataview->timecreated = $data->timemodified;
4797              $DB->insert_record('course_modules_viewed', $dataview);
4798          }
4799      }
4800  
4801      /**
4802       * Process the completioinview data.
4803       * @param array $data The data from the XML file.
4804       */
4805      protected function process_completionview(array $data) {
4806          global $DB;
4807  
4808          $data = (object)$data;
4809          $data->coursemoduleid = $this->task->get_moduleid();
4810          $data->userid = $this->get_mappingid('user', $data->userid);
4811  
4812          $DB->insert_record('course_modules_viewed', $data);
4813      }
4814  }
4815  
4816  /**
4817   * Abstract structure step, parent of all the activity structure steps. Used to support
4818   * the main <activity ...> tag and process it.
4819   */
4820  abstract class restore_activity_structure_step extends restore_structure_step {
4821  
4822      /**
4823       * Adds support for the 'activity' path that is common to all the activities
4824       * and will be processed globally here
4825       */
4826      protected function prepare_activity_structure($paths) {
4827  
4828          $paths[] = new restore_path_element('activity', '/activity');
4829  
4830          return $paths;
4831      }
4832  
4833      /**
4834       * Process the activity path, informing the task about various ids, needed later
4835       */
4836      protected function process_activity($data) {
4837          $data = (object)$data;
4838          $this->task->set_old_contextid($data->contextid); // Save old contextid in task
4839          $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
4840          $this->task->set_old_activityid($data->id); // Save old activityid in task
4841      }
4842  
4843      /**
4844       * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4845       * and will adjust the new activity id (the instance) in various places
4846       */
4847      protected function apply_activity_instance($newitemid) {
4848          global $DB;
4849  
4850          $this->task->set_activityid($newitemid); // Save activity id in task
4851          // Apply the id to course_sections->instanceid
4852          $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
4853          // Do the mapping for modulename, preparing it for files by oldcontext
4854          $modulename = $this->task->get_modulename();
4855          $oldid = $this->task->get_old_activityid();
4856          $this->set_mapping($modulename, $oldid, $newitemid, true);
4857      }
4858  }
4859  
4860  /**
4861   * Structure step in charge of creating/mapping all the qcats and qs
4862   * by parsing the questions.xml file and checking it against the
4863   * results calculated by {@link restore_process_categories_and_questions}
4864   * and stored in backup_ids_temp.
4865   */
4866  class restore_create_categories_and_questions extends restore_structure_step {
4867  
4868      /** @var array $cachedcategory store a question category */
4869      protected $cachedcategory = null;
4870  
4871      protected function define_structure() {
4872  
4873          // Check if the backup is a pre 4.0 one.
4874          $restoretask = $this->get_task();
4875          $before40 = $restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<');
4876          // Start creating the path, category should be the first one.
4877          $paths = [];
4878          $paths [] = new restore_path_element('question_category', '/question_categories/question_category');
4879          // For the backups done before 4.0.
4880          if ($before40) {
4881              // This path is to recreate the bank entry and version for the legacy question objets.
4882              $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4883  
4884              // Apply for 'qtype' plugins optional paths at question level.
4885              $this->add_plugin_structure('qtype', $question);
4886  
4887              // Apply for 'local' plugins optional paths at question level.
4888              $this->add_plugin_structure('local', $question);
4889  
4890              $paths [] = $question;
4891              $paths [] = new restore_path_element('question_hint',
4892                  '/question_categories/question_category/questions/question/question_hints/question_hint');
4893              $paths [] = new restore_path_element('tag', '/question_categories/question_category/questions/question/tags/tag');
4894          } else {
4895              // For all the new backups.
4896              $paths [] = new restore_path_element('question_bank_entry',
4897                  '/question_categories/question_category/question_bank_entries/question_bank_entry');
4898              $paths [] = new restore_path_element('question_versions', '/question_categories/question_category/'.
4899                  'question_bank_entries/question_bank_entry/question_version/question_versions');
4900              $question = new restore_path_element('question', '/question_categories/question_category/'.
4901                  'question_bank_entries/question_bank_entry/question_version/question_versions/questions/question');
4902  
4903              // Apply for 'qtype' plugins optional paths at question level.
4904              $this->add_plugin_structure('qtype', $question);
4905  
4906              // Apply for 'qbank' plugins optional paths at question level.
4907              $this->add_plugin_structure('qbank', $question);
4908  
4909              // Apply for 'local' plugins optional paths at question level.
4910              $this->add_plugin_structure('local', $question);
4911  
4912              $paths [] = $question;
4913              $paths [] = new restore_path_element('question_hint', '/question_categories/question_category/question_bank_entries/'.
4914                  'question_bank_entry/question_version/question_versions/questions/question/question_hints/question_hint');
4915              $paths [] = new restore_path_element('tag', '/question_categories/question_category/question_bank_entries/'.
4916                  'question_bank_entry/question_version/question_versions/questions/question/tags/tag');
4917          }
4918  
4919          return $paths;
4920      }
4921  
4922      /**
4923       * Process question category restore.
4924       *
4925       * @param array $data the data from the XML file.
4926       */
4927      protected function process_question_category($data) {
4928          global $DB;
4929  
4930          $data = (object)$data;
4931          $oldid = $data->id;
4932  
4933          // Check we have one mapping for this category.
4934          if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4935              return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
4936          }
4937  
4938          // Check we have to create the category (newitemid = 0).
4939          if ($mapping->newitemid) {
4940              // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4941              // children elements of the 'question_category' one.
4942              $this->set_mapping('question_category', $oldid, $mapping->newitemid);
4943              return; // newitemid != 0, this category is going to be mapped. Nothing to do
4944          }
4945  
4946          // Arrived here, newitemid = 0, we need to create the category
4947          // we'll do it at parentitemid context, but for CONTEXT_MODULE
4948          // categories, that will be created at CONTEXT_COURSE and moved
4949          // to module context later when the activity is created.
4950          if ($mapping->info->contextlevel == CONTEXT_MODULE) {
4951              $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
4952          }
4953          $data->contextid = $mapping->parentitemid;
4954  
4955          // Before 3.5, question categories could be created at top level.
4956          // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
4957          $restoretask = $this->get_task();
4958          $before35 = $restoretask->backup_release_compare('3.5', '<') || $restoretask->backup_version_compare(20180205, '<');
4959          if (empty($mapping->info->parent) && $before35) {
4960              $top = question_get_top_category($data->contextid, true);
4961              $data->parent = $top->id;
4962          }
4963  
4964          if (empty($data->parent)) {
4965              if (!$top = question_get_top_category($data->contextid)) {
4966                  $top = question_get_top_category($data->contextid, true);
4967                  $this->set_mapping('question_category_created', $oldid, $top->id, false, null, $data->contextid);
4968              }
4969              $this->set_mapping('question_category', $oldid, $top->id);
4970          } else {
4971  
4972              // Before 3.1, the 'stamp' field could be erroneously duplicated.
4973              // From 3.1 onwards, there's a unique index of (contextid, stamp).
4974              // If we encounter a duplicate in an old restore file, just generate a new stamp.
4975              // This is the same as what happens during an upgrade to 3.1+ anyway.
4976              if ($DB->record_exists('question_categories', ['stamp' => $data->stamp, 'contextid' => $data->contextid])) {
4977                  $data->stamp = make_unique_id_code();
4978              }
4979  
4980              // The idnumber if it exists also needs to be unique within a context or reset it to null.
4981              if (!empty($data->idnumber) && $DB->record_exists('question_categories',
4982                      ['idnumber' => $data->idnumber, 'contextid' => $data->contextid])) {
4983                  unset($data->idnumber);
4984              }
4985  
4986              // Let's create the question_category and save mapping.
4987              $newitemid = $DB->insert_record('question_categories', $data);
4988              $this->set_mapping('question_category', $oldid, $newitemid);
4989              // Also annotate them as question_category_created, we need
4990              // that later when remapping parents.
4991              $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
4992          }
4993      }
4994  
4995      /**
4996       * Process pre 4.0 question data where in creates the record for version and entry table.
4997       *
4998       * @param array $data the data from the XML file.
4999       */
5000      protected function process_question_legacy_data($data) {
5001          global $DB;
5002  
5003          $oldid = $data->id;
5004          // Process question bank entry.
5005          $entrydata = new stdClass();
5006          $entrydata->questioncategoryid = $data->category;
5007          $userid = $this->get_mappingid('user', $data->createdby);
5008          if ($userid) {
5009              $entrydata->ownerid = $userid;
5010          } else {
5011              if (!$this->task->is_samesite()) {
5012                  $entrydata->ownerid = $this->task->get_userid();
5013              }
5014          }
5015          // The idnumber if it exists also needs to be unique within a category or reset it to null.
5016          if (isset($data->idnumber) && !$DB->record_exists('question_bank_entries',
5017                  ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->category])) {
5018              $entrydata->idnumber = $data->idnumber;
5019          }
5020  
5021          $newentryid = $DB->insert_record('question_bank_entries', $entrydata);
5022          // Process question versions.
5023          $versiondata = new stdClass();
5024          $versiondata->questionbankentryid = $newentryid;
5025          $versiondata->version = 1;
5026          // Question id is updated after inserting the question.
5027          $versiondata->questionid = 0;
5028          $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
5029          if ((int)$data->hidden === 1) {
5030              $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_HIDDEN;
5031          }
5032          $versiondata->status = $versionstatus;
5033          $newversionid = $DB->insert_record('question_versions', $versiondata);
5034          $this->set_mapping('question_version_created', $oldid, $newversionid);
5035      }
5036  
5037      /**
5038       * Process question bank entry data.
5039       *
5040       * @param array $data the data from the XML file.
5041       */
5042      protected function process_question_bank_entry($data) {
5043          global $DB;
5044  
5045          $data = (object)$data;
5046          $oldid = $data->id;
5047  
5048          $questioncreated = $this->get_mappingid('question_category_created', $data->questioncategoryid) ? true : false;
5049          $recordexist = $DB->record_exists('question_bank_entries', ['id' => $data->id,
5050              'questioncategoryid' => $data->questioncategoryid]);
5051          // Check we have category created.
5052          if (!$questioncreated && $recordexist) {
5053              return self::SKIP_ALL_CHILDREN;
5054          }
5055  
5056          $data->questioncategoryid = $this->get_new_parentid('question_category');
5057          $userid = $this->get_mappingid('user', $data->ownerid);
5058          if ($userid) {
5059              $data->ownerid = $userid;
5060          } else {
5061              if (!$this->task->is_samesite()) {
5062                  $data->ownerid = $this->task->get_userid();
5063              }
5064          }
5065  
5066          // The idnumber if it exists also needs to be unique within a category or reset it to null.
5067          if (!empty($data->idnumber) && $DB->record_exists('question_bank_entries',
5068                  ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->questioncategoryid])) {
5069              unset($data->idnumber);
5070          }
5071  
5072          $newitemid = $DB->insert_record('question_bank_entries', $data);
5073          $this->set_mapping('question_bank_entry', $oldid, $newitemid);
5074      }
5075  
5076      /**
5077       * Process question versions.
5078       *
5079       * @param array $data the data from the XML file.
5080       */
5081      protected function process_question_versions($data) {
5082          global $DB;
5083  
5084          $data = (object)$data;
5085          $oldid = $data->id;
5086  
5087          $data->questionbankentryid = $this->get_new_parentid('question_bank_entry');
5088          // Question id is updated after inserting the question.
5089          $data->questionid = 0;
5090          $newitemid = $DB->insert_record('question_versions', $data);
5091          $this->set_mapping('question_versions', $oldid, $newitemid);
5092      }
5093  
5094      /**
5095       * Process the actual question.
5096       *
5097       * @param array $data the data from the XML file.
5098       */
5099      protected function process_question($data) {
5100          global $DB;
5101  
5102          $data = (object)$data;
5103          $oldid = $data->id;
5104  
5105          // Check if the backup is a pre 4.0 one.
5106          $restoretask = $this->get_task();
5107          if ($restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<')) {
5108              // Check we have one mapping for this question.
5109              if (!$questionmapping = $this->get_mapping('question', $oldid)) {
5110                  return; // No mapping = this question doesn't need to be created/mapped.
5111              }
5112  
5113              // Get the mapped category (cannot use get_new_parentid() because not
5114              // all the categories have been created, so it is not always available
5115              // Instead we get the mapping for the question->parentitemid because
5116              // we have loaded qcatids there for all parsed questions.
5117              $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
5118              $this->process_question_legacy_data($data);
5119          }
5120  
5121          // In the past, there were some very sloppy values of penalty. Fix them.
5122          if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
5123              $data->penalty = 0.3333333;
5124          }
5125          if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
5126              $data->penalty = 0.6666667;
5127          }
5128          if ($data->penalty >= 1) {
5129              $data->penalty = 1;
5130          }
5131  
5132          $userid = $this->get_mappingid('user', $data->createdby);
5133          if ($userid) {
5134              // The question creator is included in the backup, so we can use their mapping id.
5135              $data->createdby = $userid;
5136          } else {
5137              // Leave the question creator unchanged when we are restoring the same site.
5138              // Otherwise use current user id.
5139              if (!$this->task->is_samesite()) {
5140                  $data->createdby = $this->task->get_userid();
5141              }
5142          }
5143  
5144          $userid = $this->get_mappingid('user', $data->modifiedby);
5145          if ($userid) {
5146              // The question modifier is included in the backup, so we can use their mapping id.
5147              $data->modifiedby = $userid;
5148          } else {
5149              // Leave the question modifier unchanged when we are restoring the same site.
5150              // Otherwise use current user id.
5151              if (!$this->task->is_samesite()) {
5152                  $data->modifiedby = $this->task->get_userid();
5153              }
5154          }
5155  
5156          $newitemid = $DB->insert_record('question', $data);
5157          $this->set_mapping('question', $oldid, $newitemid);
5158          // Also annotate them as question_created, we need
5159          // that later when remapping parents (keeping the old categoryid as parentid).
5160          $parentcatid = $this->get_old_parentid('question_category');
5161          $this->set_mapping('question_created', $oldid, $newitemid, false, null, $parentcatid);
5162          // Now update the question_versions table with the new question id. we dont need to do that for random qtypes.
5163          $legacyquestiondata = $this->get_mappingid('question_version_created', $oldid) ? true : false;
5164          if ($legacyquestiondata) {
5165              $parentitemid = $this->get_mappingid('question_version_created', $oldid);
5166          } else {
5167              $parentitemid = $this->get_new_parentid('question_versions');
5168          }
5169          $version = new stdClass();
5170          $version->id = $parentitemid;
5171          $version->questionid = $newitemid;
5172          $DB->update_record('question_versions', $version);
5173  
5174          // Note, we don't restore any question files yet
5175          // as far as the CONTEXT_MODULE categories still
5176          // haven't their contexts to be restored to
5177          // The {@link restore_create_question_files}, executed in the final step
5178          // step will be in charge of restoring all the question files.
5179      }
5180  
5181      protected function process_question_hint($data) {
5182          global $DB;
5183  
5184          $data = (object)$data;
5185          $oldid = $data->id;
5186  
5187          // Detect if the question is created or mapped
5188          $oldquestionid   = $this->get_old_parentid('question');
5189          $newquestionid   = $this->get_new_parentid('question');
5190          $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
5191  
5192          // If the question has been created by restore, we need to create its question_answers too
5193          if ($questioncreated) {
5194              // Adjust some columns
5195              $data->questionid = $newquestionid;
5196              // Insert record
5197              $newitemid = $DB->insert_record('question_hints', $data);
5198  
5199          // The question existed, we need to map the existing question_hints
5200          } else {
5201              // Look in question_hints by hint text matching
5202              $sql = 'SELECT id
5203                        FROM {question_hints}
5204                       WHERE questionid = ?
5205                         AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
5206              $params = array($newquestionid, $data->hint);
5207              $newitemid = $DB->get_field_sql($sql, $params);
5208  
5209              // Not able to find the hint, let's try cleaning the hint text
5210              // of all the question's hints in DB as slower fallback. MDL-33863.
5211              if (!$newitemid) {
5212                  $potentialhints = $DB->get_records('question_hints',
5213                          array('questionid' => $newquestionid), '', 'id, hint');
5214                  foreach ($potentialhints as $potentialhint) {
5215                      // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
5216                      $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
5217                      $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
5218                      if ($cleanhint === $data->hint) {
5219                          $newitemid = $data->id;
5220                      }
5221                  }
5222              }
5223  
5224              // If we haven't found the newitemid, something has gone really wrong, question in DB
5225              // is missing hints, exception
5226              if (!$newitemid) {
5227                  $info = new stdClass();
5228                  $info->filequestionid = $oldquestionid;
5229                  $info->dbquestionid   = $newquestionid;
5230                  $info->hint           = $data->hint;
5231                  throw new restore_step_exception('error_question_hint_missing_in_db', $info);
5232              }
5233          }
5234          // Create mapping (I'm not sure if this is really needed?)
5235          $this->set_mapping('question_hint', $oldid, $newitemid);
5236      }
5237  
5238      protected function process_tag($data) {
5239          global $DB;
5240  
5241          $data = (object)$data;
5242          $newquestion = $this->get_new_parentid('question');
5243          $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
5244          if (!$questioncreated) {
5245              // This question already exists in the question bank. Nothing for us to do.
5246              return;
5247          }
5248  
5249          if (core_tag_tag::is_enabled('core_question', 'question')) {
5250              $tagname = $data->rawname;
5251              if (!empty($data->contextid) && $newcontextid = $this->get_mappingid('context', $data->contextid)) {
5252                      $tagcontextid = $newcontextid;
5253              } else {
5254                  // Get the category, so we can then later get the context.
5255                  $categoryid = $this->get_new_parentid('question_category');
5256                  if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
5257                      $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
5258                  }
5259                  $tagcontextid = $this->cachedcategory->contextid;
5260              }
5261              // Add the tag to the question.
5262              core_tag_tag::add_item_tag('core_question', 'question', $newquestion,
5263                      context::instance_by_id($tagcontextid),
5264                      $tagname);
5265          }
5266      }
5267  
5268      protected function after_execute() {
5269          global $DB;
5270  
5271          // First of all, recode all the created question_categories->parent fields
5272          $qcats = $DB->get_records('backup_ids_temp', array(
5273                       'backupid' => $this->get_restoreid(),
5274                       'itemname' => 'question_category_created'));
5275          foreach ($qcats as $qcat) {
5276              $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
5277              // Get new parent (mapped or created, so we look in quesiton_category mappings)
5278              if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5279                                   'backupid' => $this->get_restoreid(),
5280                                   'itemname' => 'question_category',
5281                                   'itemid'   => $dbcat->parent))) {
5282                  // contextids must match always, as far as we always include complete qbanks, just check it
5283                  $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
5284                  if ($dbcat->contextid == $newparentctxid) {
5285                      $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
5286                  } else {
5287                      $newparent = 0; // No ctx match for both cats, no parent relationship
5288                  }
5289              }
5290              // Here with $newparent empty, problem with contexts or remapping, set it to top cat
5291              if (!$newparent && $dbcat->parent) {
5292                  $topcat = question_get_top_category($dbcat->contextid, true);
5293                  if ($dbcat->parent != $topcat->id) {
5294                      $DB->set_field('question_categories', 'parent', $topcat->id, array('id' => $dbcat->id));
5295                  }
5296              }
5297          }
5298  
5299          // Now, recode all the created question->parent fields
5300          $qs = $DB->get_records('backup_ids_temp', array(
5301                    'backupid' => $this->get_restoreid(),
5302                    'itemname' => 'question_created'));
5303          foreach ($qs as $q) {
5304              $dbq = $DB->get_record('question', array('id' => $q->newitemid));
5305              // Get new parent (mapped or created, so we look in question mappings)
5306              if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5307                                   'backupid' => $this->get_restoreid(),
5308                                   'itemname' => 'question',
5309                                   'itemid'   => $dbq->parent))) {
5310                  $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
5311              }
5312          }
5313  
5314          // Note, we don't restore any question files yet
5315          // as far as the CONTEXT_MODULE categories still
5316          // haven't their contexts to be restored to
5317          // The {@link restore_create_question_files}, executed in the final step
5318          // step will be in charge of restoring all the question files
5319      }
5320  }
5321  
5322  /**
5323   * Execution step that will move all the CONTEXT_MODULE question categories
5324   * created at early stages of restore in course context (because modules weren't
5325   * created yet) to their target module (matching by old-new-contextid mapping)
5326   */
5327  class restore_move_module_questions_categories extends restore_execution_step {
5328  
5329      protected function define_execution() {
5330          global $DB;
5331  
5332          $after35 = $this->task->backup_release_compare('3.5', '>=') && $this->task->backup_version_compare(20180205, '>');
5333  
5334          $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
5335          foreach ($contexts as $contextid => $contextlevel) {
5336              // Only if context mapping exists (i.e. the module has been restored)
5337              if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
5338                  // Update all the qcats having their parentitemid set to the original contextid
5339                  $modulecats = $DB->get_records_sql("SELECT itemid, newitemid, info
5340                                                        FROM {backup_ids_temp}
5341                                                       WHERE backupid = ?
5342                                                         AND itemname = 'question_category'
5343                                                         AND parentitemid = ?", array($this->get_restoreid(), $contextid));
5344                  $top = question_get_top_category($newcontext->newitemid, true);
5345                  $oldtopid = 0;
5346                  $categoryids = [];
5347                  foreach ($modulecats as $modulecat) {
5348                      // Before 3.5, question categories could be created at top level.
5349                      // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
5350                      $info = backup_controller_dbops::decode_backup_temp_info($modulecat->info);
5351                      if ($after35 && empty($info->parent)) {
5352                          $oldtopid = $modulecat->newitemid;
5353                          $modulecat->newitemid = $top->id;
5354                      } else {
5355                          $cat = new stdClass();
5356                          $cat->id = $modulecat->newitemid;
5357                          $cat->contextid = $newcontext->newitemid;
5358                          if (empty($info->parent)) {
5359                              $cat->parent = $top->id;
5360                          }
5361                          $DB->update_record('question_categories', $cat);
5362                          $categoryids[] = (int)$cat->id;
5363                      }
5364  
5365                      // And set new contextid (and maybe update newitemid) also in question_category mapping (will be
5366                      // used by {@link restore_create_question_files} later.
5367                      restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid,
5368                              $modulecat->newitemid, $newcontext->newitemid);
5369                  }
5370  
5371                  // Update the context id of any tags applied to any questions in these categories.
5372                  if ($categoryids) {
5373                      [$categorysql, $categoryidparams] = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
5374                      $sqlupdate = "UPDATE {tag_instance}
5375                                       SET contextid = :newcontext
5376                                     WHERE component = :component
5377                                           AND itemtype = :itemtype
5378                                           AND itemid IN (SELECT DISTINCT bi.newitemid as questionid
5379                                                            FROM {backup_ids_temp} bi
5380                                                            JOIN {question} q ON q.id = bi.newitemid
5381                                                            JOIN {question_versions} qv ON qv.questionid = q.id
5382                                                            JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
5383                                                           WHERE bi.backupid = :backupid AND bi.itemname = 'question_created'
5384                                                                 AND qbe.questioncategoryid {$categorysql}) ";
5385                      $params = [
5386                          'newcontext' => $newcontext->newitemid,
5387                          'component' => 'core_question',
5388                          'itemtype' => 'question',
5389                          'backupid' => $this->get_restoreid(),
5390                      ];
5391                      $params += $categoryidparams;
5392                      $DB->execute($sqlupdate, $params);
5393                  }
5394  
5395                  // Now set the parent id for the question categories that were in the top category in the course context
5396                  // and have been moved now.
5397                  if ($oldtopid) {
5398                      $DB->set_field('question_categories', 'parent', $top->id,
5399                              array('contextid' => $newcontext->newitemid, 'parent' => $oldtopid));
5400                  }
5401              }
5402          }
5403      }
5404  }
5405  
5406  /**
5407   * Execution step that will create all the question/answers/qtype-specific files for the restored
5408   * questions. It must be executed after {@link restore_move_module_questions_categories}
5409   * because only then each question is in its final category and only then the
5410   * contexts can be determined.
5411   */
5412  class restore_create_question_files extends restore_execution_step {
5413  
5414      /** @var array Question-type specific component items cache. */
5415      private $qtypecomponentscache = array();
5416  
5417      /**
5418       * Preform the restore_create_question_files step.
5419       */
5420      protected function define_execution() {
5421          global $DB;
5422  
5423          // Track progress, as this task can take a long time.
5424          $progress = $this->task->get_progress();
5425          $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
5426  
5427          // Parentitemids of question_createds in backup_ids_temp are the category it is in.
5428          // MUST use a recordset, as there is no unique key in the first (or any) column.
5429          $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
5430                                                     FROM {backup_ids_temp} bi
5431                                                     JOIN {question} q ON q.id = bi.newitemid
5432                                                    WHERE bi.backupid = ?
5433                                                          AND bi.itemname = 'question_created'
5434                                                 ORDER BY categoryid ASC", array($this->get_restoreid()));
5435  
5436          $currentcatid = -1;
5437          foreach ($catqtypes as $categoryid => $row) {
5438              $qtype = $row->qtype;
5439  
5440              // Check if we are in a new category.
5441              if ($currentcatid !== $categoryid) {
5442                  // Report progress for each category.
5443                  $progress->progress();
5444  
5445                  if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
5446                          'question_category', $categoryid)) {
5447                      // Something went really wrong, cannot find the question_category for the question_created records.
5448                      debugging('Error fetching target context for question', DEBUG_DEVELOPER);
5449                      continue;
5450                  }
5451  
5452                  // Calculate source and target contexts.
5453                  $oldctxid = $qcatmapping->info->contextid;
5454                  $newctxid = $qcatmapping->parentitemid;
5455  
5456                  $this->send_common_files($oldctxid, $newctxid, $progress);
5457                  $currentcatid = $categoryid;
5458              }
5459  
5460              $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
5461          }
5462          $catqtypes->close();
5463          $progress->end_progress();
5464      }
5465  
5466      /**
5467       * Send the common question files to a new context.
5468       *
5469       * @param int             $oldctxid Old context id.
5470       * @param int             $newctxid New context id.
5471       * @param \core\progress\base  $progress Progress object to use.
5472       */
5473      private function send_common_files($oldctxid, $newctxid, $progress) {
5474          // Add common question files (question and question_answer ones).
5475          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
5476                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5477          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
5478                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5479          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
5480                  $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5481          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
5482                  $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5483          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
5484                  $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
5485          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
5486                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5487          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
5488                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5489          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
5490                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5491      }
5492  
5493      /**
5494       * Send the question type specific files to a new context.
5495       *
5496       * @param text            $qtype The qtype name to send.
5497       * @param int             $oldctxid Old context id.
5498       * @param int             $newctxid New context id.
5499       * @param \core\progress\base  $progress Progress object to use.
5500       */
5501      private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
5502          if (!isset($this->qtypecomponentscache[$qtype])) {
5503              $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
5504          }
5505          $components = $this->qtypecomponentscache[$qtype];
5506          foreach ($components as $component => $fileareas) {
5507              foreach ($fileareas as $filearea => $mapping) {
5508                  restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
5509                          $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
5510              }
5511          }
5512      }
5513  }
5514  
5515  /**
5516   * Try to restore aliases and references to external files.
5517   *
5518   * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5519   * We expect that all regular (non-alias) files have already been restored. Make sure
5520   * there is no restore step executed after this one that would call send_files_to_pool() again.
5521   *
5522   * You may notice we have hardcoded support for Server files, Legacy course files
5523   * and user Private files here at the moment. This could be eventually replaced with a set of
5524   * callbacks in the future if needed.
5525   *
5526   * @copyright 2012 David Mudrak <david@moodle.com>
5527   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5528   */
5529  class restore_process_file_aliases_queue extends restore_execution_step {
5530  
5531      /** @var array internal cache for {@link choose_repository()} */
5532      private $cachereposbyid = array();
5533  
5534      /** @var array internal cache for {@link choose_repository()} */
5535      private $cachereposbytype = array();
5536  
5537      /**
5538       * What to do when this step is executed.
5539       */
5540      protected function define_execution() {
5541          global $DB;
5542  
5543          $fs = get_file_storage();
5544  
5545          // Load the queue.
5546          $aliascount = $DB->count_records('backup_ids_temp',
5547              ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue']);
5548          $rs = $DB->get_recordset('backup_ids_temp',
5549              ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'],
5550              '', 'info');
5551  
5552          $this->log('processing file aliases queue. ' . $aliascount . ' entries.', backup::LOG_DEBUG);
5553          $progress = $this->task->get_progress();
5554          $progress->start_progress('Processing file aliases queue', $aliascount);
5555  
5556          // Iterate over aliases in the queue.
5557          foreach ($rs as $record) {
5558              $progress->increment_progress();
5559              $info = backup_controller_dbops::decode_backup_temp_info($record->info);
5560  
5561              // Try to pick a repository instance that should serve the alias.
5562              $repository = $this->choose_repository($info);
5563  
5564              if (is_null($repository)) {
5565                  $this->notify_failure($info, 'unable to find a matching repository instance');
5566                  continue;
5567              }
5568  
5569              if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5570                      || $info->oldfile->repositorytype === 'contentbank') {
5571                  // Aliases to Server files and Legacy course files may refer to a file
5572                  // contained in the backup file or to some existing file (if we are on the
5573                  // same site).
5574                  try {
5575                      $reference = file_storage::unpack_reference($info->oldfile->reference);
5576                  } catch (Exception $e) {
5577                      $this->notify_failure($info, 'invalid reference field format');
5578                      continue;
5579                  }
5580  
5581                  // Let's see if the referred source file was also included in the backup.
5582                  $candidates = $DB->get_recordset('backup_files_temp', array(
5583                          'backupid' => $this->get_restoreid(),
5584                          'contextid' => $reference['contextid'],
5585                          'component' => $reference['component'],
5586                          'filearea' => $reference['filearea'],
5587                          'itemid' => $reference['itemid'],
5588                      ), '', 'info, newcontextid, newitemid');
5589  
5590                  $source = null;
5591  
5592                  foreach ($candidates as $candidate) {
5593                      $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
5594                      if ($candidateinfo->filename === $reference['filename']
5595                              and $candidateinfo->filepath === $reference['filepath']
5596                              and !is_null($candidate->newcontextid)
5597                              and !is_null($candidate->newitemid) ) {
5598                          $source = $candidateinfo;
5599                          $source->contextid = $candidate->newcontextid;
5600                          $source->itemid = $candidate->newitemid;
5601                          break;
5602                      }
5603                  }
5604                  $candidates->close();
5605  
5606                  if ($source) {
5607                      // We have an alias that refers to another file also included in
5608                      // the backup. Let us change the reference field so that it refers
5609                      // to the restored copy of the original file.
5610                      $reference = file_storage::pack_reference($source);
5611  
5612                      // Send the new alias to the filepool.
5613                      $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5614                      $this->notify_success($info);
5615                      continue;
5616  
5617                  } else {
5618                      // This is a reference to some moodle file that was not contained in the backup
5619                      // file. If we are restoring to the same site, keep the reference untouched
5620                      // and restore the alias as is if the referenced file exists.
5621                      if ($this->task->is_samesite()) {
5622                          if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5623                                  $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5624                              $reference = file_storage::pack_reference($reference);
5625                              $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5626                              $this->notify_success($info);
5627                              continue;
5628                          } else {
5629                              $this->notify_failure($info, 'referenced file not found');
5630                              continue;
5631                          }
5632  
5633                      // If we are at other site, we can't restore this alias.
5634                      } else {
5635                          $this->notify_failure($info, 'referenced file not included');
5636                          continue;
5637                      }
5638                  }
5639  
5640              } else if ($info->oldfile->repositorytype === 'user') {
5641                  if ($this->task->is_samesite()) {
5642                      // For aliases to user Private files at the same site, we have a chance to check
5643                      // if the referenced file still exists.
5644                      try {
5645                          $reference = file_storage::unpack_reference($info->oldfile->reference);
5646                      } catch (Exception $e) {
5647                          $this->notify_failure($info, 'invalid reference field format');
5648                          continue;
5649                      }
5650                      if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5651                              $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5652                          $reference = file_storage::pack_reference($reference);
5653                          $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5654                          $this->notify_success($info);
5655                          continue;
5656                      } else {
5657                          $this->notify_failure($info, 'referenced file not found');
5658                          continue;
5659                      }
5660  
5661                  // If we are at other site, we can't restore this alias.
5662                  } else {
5663                      $this->notify_failure($info, 'restoring at another site');
5664                      continue;
5665                  }
5666  
5667              } else {
5668                  // This is a reference to some external file such as dropbox.
5669                  // If we are restoring to the same site, keep the reference untouched and
5670                  // restore the alias as is.
5671                  if ($this->task->is_samesite()) {
5672                      $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
5673                      $this->notify_success($info);
5674                      continue;
5675  
5676                  // If we are at other site, we can't restore this alias.
5677                  } else {
5678                      $this->notify_failure($info, 'restoring at another site');
5679                      continue;
5680                  }
5681              }
5682          }
5683          $progress->end_progress();
5684          $rs->close();
5685      }
5686  
5687      /**
5688       * Choose the repository instance that should handle the alias.
5689       *
5690       * At the same site, we can rely on repository instance id and we just
5691       * check it still exists. On other site, try to find matching Server files or
5692       * Legacy course files repository instance. Return null if no matching
5693       * repository instance can be found.
5694       *
5695       * @param stdClass $info
5696       * @return repository|null
5697       */
5698      private function choose_repository(stdClass $info) {
5699          global $DB, $CFG;
5700          require_once($CFG->dirroot.'/repository/lib.php');
5701  
5702          if ($this->task->is_samesite()) {
5703              // We can rely on repository instance id.
5704  
5705              if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
5706                  return $this->cachereposbyid[$info->oldfile->repositoryid];
5707              }
5708  
5709              $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
5710  
5711              try {
5712                  $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
5713                  return $this->cachereposbyid[$info->oldfile->repositoryid];
5714              } catch (Exception $e) {
5715                  $this->cachereposbyid[$info->oldfile->repositoryid] = null;
5716                  return null;
5717              }
5718  
5719          } else {
5720              // We can rely on repository type only.
5721  
5722              if (empty($info->oldfile->repositorytype)) {
5723                  return null;
5724              }
5725  
5726              if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
5727                  return $this->cachereposbytype[$info->oldfile->repositorytype];
5728              }
5729  
5730              $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
5731  
5732              // Both Server files and Legacy course files repositories have a single
5733              // instance at the system context to use. Let us try to find it.
5734              if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5735                      || $info->oldfile->repositorytype === 'contentbank') {
5736                  $sql = "SELECT ri.id
5737                            FROM {repository} r
5738                            JOIN {repository_instances} ri ON ri.typeid = r.id
5739                           WHERE r.type = ? AND ri.contextid = ?";
5740                  $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
5741                  if (empty($ris)) {
5742                      return null;
5743                  }
5744                  $repoids = array_keys($ris);
5745                  $repoid = reset($repoids);
5746                  try {
5747                      $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
5748                      return $this->cachereposbytype[$info->oldfile->repositorytype];
5749                  } catch (Exception $e) {
5750                      $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5751                      return null;
5752                  }
5753              }
5754  
5755              $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5756              return null;
5757          }
5758      }
5759  
5760      /**
5761       * Let the user know that the given alias was successfully restored
5762       *
5763       * @param stdClass $info
5764       */
5765      private function notify_success(stdClass $info) {
5766          $filedesc = $this->describe_alias($info);
5767          $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
5768      }
5769  
5770      /**
5771       * Let the user know that the given alias can't be restored
5772       *
5773       * @param stdClass $info
5774       * @param string $reason detailed reason to be logged
5775       */
5776      private function notify_failure(stdClass $info, $reason = '') {
5777          $filedesc = $this->describe_alias($info);
5778          if ($reason) {
5779              $reason = ' ('.$reason.')';
5780          }
5781          $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5782          $this->add_result_item('file_aliases_restore_failures', $filedesc);
5783      }
5784  
5785      /**
5786       * Return a human readable description of the alias file
5787       *
5788       * @param stdClass $info
5789       * @return string
5790       */
5791      private function describe_alias(stdClass $info) {
5792  
5793          $filedesc = $this->expected_alias_location($info->newfile);
5794  
5795          if (!is_null($info->oldfile->source)) {
5796              $filedesc .= ' ('.$info->oldfile->source.')';
5797          }
5798  
5799          return $filedesc;
5800      }
5801  
5802      /**
5803       * Return the expected location of a file
5804       *
5805       * Please note this may and may not work as a part of URL to pluginfile.php
5806       * (depends on how the given component/filearea deals with the itemid).
5807       *
5808       * @param stdClass $filerecord
5809       * @return string
5810       */
5811      private function expected_alias_location($filerecord) {
5812  
5813          $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5814          if (!is_null($filerecord->itemid)) {
5815              $filedesc .= '/'.$filerecord->itemid;
5816          }
5817          $filedesc .= $filerecord->filepath.$filerecord->filename;
5818  
5819          return $filedesc;
5820      }
5821  
5822      /**
5823       * Append a value to the given resultset
5824       *
5825       * @param string $name name of the result containing a list of values
5826       * @param mixed $value value to add as another item in that result
5827       */
5828      private function add_result_item($name, $value) {
5829  
5830          $results = $this->task->get_results();
5831  
5832          if (isset($results[$name])) {
5833              if (!is_array($results[$name])) {
5834                  throw new coding_exception('Unable to append a result item into a non-array structure.');
5835              }
5836              $current = $results[$name];
5837              $current[] = $value;
5838              $this->task->add_result(array($name => $current));
5839  
5840          } else {
5841              $this->task->add_result(array($name => array($value)));
5842          }
5843      }
5844  }
5845  
5846  
5847  /**
5848   * Helper code for use by any plugin that stores question attempt data that it needs to back up.
5849   */
5850  trait restore_questions_attempt_data_trait {
5851      /** @var array question_attempt->id to qtype. */
5852      protected $qtypes = array();
5853      /** @var array question_attempt->id to questionid. */
5854      protected $newquestionids = array();
5855  
5856      /**
5857       * Attach below $element (usually attempts) the needed restore_path_elements
5858       * to restore question_usages and all they contain.
5859       *
5860       * If you use the $nameprefix parameter, then you will need to implement some
5861       * extra methods in your class, like
5862       *
5863       * protected function process_{nameprefix}question_attempt($data) {
5864       *     $this->restore_question_usage_worker($data, '{nameprefix}');
5865       * }
5866       * protected function process_{nameprefix}question_attempt($data) {
5867       *     $this->restore_question_attempt_worker($data, '{nameprefix}');
5868       * }
5869       * protected function process_{nameprefix}question_attempt_step($data) {
5870       *     $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5871       * }
5872       *
5873       * @param restore_path_element $element the parent element that the usages are stored inside.
5874       * @param array $paths the paths array that is being built.
5875       * @param string $nameprefix should match the prefix passed to the corresponding
5876       *      backup_questions_activity_structure_step::add_question_usages call.
5877       */
5878      protected function add_question_usages($element, &$paths, $nameprefix = '') {
5879          // Check $element is restore_path_element
5880          if (! $element instanceof restore_path_element) {
5881              throw new restore_step_exception('element_must_be_restore_path_element', $element);
5882          }
5883  
5884          // Check $paths is one array
5885          if (!is_array($paths)) {
5886              throw new restore_step_exception('paths_must_be_array', $paths);
5887          }
5888          $paths[] = new restore_path_element($nameprefix . 'question_usage',
5889                  $element->get_path() . "/{$nameprefix}question_usage");
5890          $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5891                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5892          $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5893                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5894                  true);
5895          $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5896                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5897      }
5898  
5899      /**
5900       * Process question_usages
5901       */
5902      public function process_question_usage($data) {
5903          $this->restore_question_usage_worker($data, '');
5904      }
5905  
5906      /**
5907       * Process question_attempts
5908       */
5909      public function process_question_attempt($data) {
5910          $this->restore_question_attempt_worker($data, '');
5911      }
5912  
5913      /**
5914       * Process question_attempt_steps
5915       */
5916      public function process_question_attempt_step($data) {
5917          $this->restore_question_attempt_step_worker($data, '');
5918      }
5919  
5920      /**
5921       * This method does the actual work for process_question_usage or
5922       * process_{nameprefix}_question_usage.
5923       * @param array $data the data from the XML file.
5924       * @param string $nameprefix the element name prefix.
5925       */
5926      protected function restore_question_usage_worker($data, $nameprefix) {
5927          global $DB;
5928  
5929          // Clear our caches.
5930          $this->qtypes = array();
5931          $this->newquestionids = array();
5932  
5933          $data = (object)$data;
5934          $oldid = $data->id;
5935  
5936          $data->contextid  = $this->task->get_contextid();
5937  
5938          // Everything ready, insert (no mapping needed)
5939          $newitemid = $DB->insert_record('question_usages', $data);
5940  
5941          $this->inform_new_usage_id($newitemid);
5942  
5943          $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
5944      }
5945  
5946      /**
5947       * When process_question_usage creates the new usage, it calls this method
5948       * to let the activity link to the new usage. For example, the quiz uses
5949       * this method to set quiz_attempts.uniqueid to the new usage id.
5950       * @param integer $newusageid
5951       */
5952      abstract protected function inform_new_usage_id($newusageid);
5953  
5954      /**
5955       * This method does the actual work for process_question_attempt or
5956       * process_{nameprefix}_question_attempt.
5957       * @param array $data the data from the XML file.
5958       * @param string $nameprefix the element name prefix.
5959       */
5960      protected function restore_question_attempt_worker($data, $nameprefix) {
5961          global $DB;
5962  
5963          $data = (object)$data;
5964          $oldid = $data->id;
5965  
5966          $questioncreated = $this->get_mappingid('question_created', $data->questionid) ? true : false;
5967          $question = $this->get_mapping('question', $data->questionid);
5968          if ($questioncreated) {
5969              $data->questionid = $question->newitemid;
5970          }
5971  
5972          $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
5973  
5974          if (!property_exists($data, 'variant')) {
5975              $data->variant = 1;
5976          }
5977  
5978          if (!property_exists($data, 'maxfraction')) {
5979              $data->maxfraction = 1;
5980          }
5981  
5982          $newitemid = $DB->insert_record('question_attempts', $data);
5983  
5984          $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
5985          if (isset($question->info->qtype)) {
5986              $qtype = $question->info->qtype;
5987          } else {
5988              $qtype = $DB->get_record('question', ['id' => $data->questionid])->qtype;
5989          }
5990          $this->qtypes[$newitemid] = $qtype;
5991          $this->newquestionids[$newitemid] = $data->questionid;
5992      }
5993  
5994      /**
5995       * This method does the actual work for process_question_attempt_step or
5996       * process_{nameprefix}_question_attempt_step.
5997       * @param array $data the data from the XML file.
5998       * @param string $nameprefix the element name prefix.
5999       */
6000      protected function restore_question_attempt_step_worker($data, $nameprefix) {
6001          global $DB;
6002  
6003          $data = (object)$data;
6004          $oldid = $data->id;
6005  
6006          // Pull out the response data.
6007          $response = array();
6008          if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
6009              foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
6010                  $response[$variable['name']] = $variable['value'];
6011              }
6012          }
6013          unset($data->response);
6014  
6015          $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
6016          $data->userid = $this->get_mappingid('user', $data->userid);
6017  
6018          // Everything ready, insert and create mapping (needed by question_sessions)
6019          $newitemid = $DB->insert_record('question_attempt_steps', $data);
6020          $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
6021  
6022          // Now process the response data.
6023          $response = $this->questions_recode_response_data(
6024                  $this->qtypes[$data->questionattemptid],
6025                  $this->newquestionids[$data->questionattemptid],
6026                  $data->sequencenumber, $response);
6027  
6028          foreach ($response as $name => $value) {
6029              $row = new stdClass();
6030              $row->attemptstepid = $newitemid;
6031              $row->name = $name;
6032              $row->value = $value;
6033              $DB->insert_record('question_attempt_step_data', $row, false);
6034          }
6035      }
6036  
6037      /**
6038       * Recode the respones data for a particular step of an attempt at at particular question.
6039       * @param string $qtype the question type.
6040       * @param int $newquestionid the question id.
6041       * @param int $sequencenumber the sequence number.
6042       * @param array $response the response data to recode.
6043       */
6044      public function questions_recode_response_data(
6045              $qtype, $newquestionid, $sequencenumber, array $response) {
6046          $qtyperestorer = $this->get_qtype_restorer($qtype);
6047          if ($qtyperestorer) {
6048              $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
6049          }
6050          return $response;
6051      }
6052  
6053      /**
6054       * Given a list of question->ids, separated by commas, returns the
6055       * recoded list, with all the restore question mappings applied.
6056       * Note: Used by quiz->questions and quiz_attempts->layout
6057       * Note: 0 = page break (unconverted)
6058       */
6059      protected function questions_recode_layout($layout) {
6060          // Extracts question id from sequence
6061          if ($questionids = explode(',', $layout)) {
6062              foreach ($questionids as $id => $questionid) {
6063                  if ($questionid) { // If it is zero then this is a pagebreak, don't translate
6064                      $newquestionid = $this->get_mappingid('question', $questionid);
6065                      $questionids[$id] = $newquestionid;
6066                  }
6067              }
6068          }
6069          return implode(',', $questionids);
6070      }
6071  
6072      /**
6073       * Get the restore_qtype_plugin subclass for a specific question type.
6074       * @param string $qtype e.g. multichoice.
6075       * @return restore_qtype_plugin instance.
6076       */
6077      protected function get_qtype_restorer($qtype) {
6078          // Build one static cache to store {@link restore_qtype_plugin}
6079          // while we are needing them, just to save zillions of instantiations
6080          // or using static stuff that will break our nice API
6081          static $qtypeplugins = array();
6082  
6083          if (!isset($qtypeplugins[$qtype])) {
6084              $classname = 'restore_qtype_' . $qtype . '_plugin';
6085              if (class_exists($classname)) {
6086                  $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
6087              } else {
6088                  $qtypeplugins[$qtype] = null;
6089              }
6090          }
6091          return $qtypeplugins[$qtype];
6092      }
6093  
6094      protected function after_execute() {
6095          parent::after_execute();
6096  
6097          // Restore any files belonging to responses.
6098          foreach (question_engine::get_all_response_file_areas() as $filearea) {
6099              $this->add_related_files('question', $filearea, 'question_attempt_step');
6100          }
6101      }
6102  }
6103  
6104  /**
6105   * Helper trait to restore question reference data.
6106   */
6107  trait restore_question_reference_data_trait {
6108  
6109      /**
6110       * Attach the question reference data to the restore.
6111       *
6112       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6113       * @param array $paths the paths array that is being built to describe the structure.
6114       */
6115      protected function add_question_references($element, &$paths) {
6116          // Check $element is restore_path_element.
6117          if (! $element instanceof restore_path_element) {
6118              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6119          }
6120  
6121          // Check $paths is one array.
6122          if (!is_array($paths)) {
6123              throw new restore_step_exception('paths_must_be_array', $paths);
6124          }
6125  
6126          $paths[] = new restore_path_element('question_reference',
6127              $element->get_path() . '/question_reference');
6128      }
6129  
6130      /**
6131       * Process question references which replaces the direct connection to quiz slots to question.
6132       *
6133       * @param array $data the data from the XML file.
6134       */
6135      public function process_question_reference($data) {
6136          global $DB;
6137          $data = (object) $data;
6138          $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6139          $data->itemid = $this->get_new_parentid('quiz_question_instance');
6140          if ($entry = $this->get_mappingid('question_bank_entry', $data->questionbankentryid)) {
6141              $data->questionbankentryid = $entry;
6142          }
6143          $DB->insert_record('question_references', $data);
6144      }
6145  }
6146  
6147  /**
6148   * Helper trait to restore question set reference data.
6149   */
6150  trait restore_question_set_reference_data_trait {
6151  
6152      /**
6153       * Attach the question reference data to the restore.
6154       *
6155       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6156       * @param array $paths the paths array that is being built to describe the structure.
6157       */
6158      protected function add_question_set_references($element, &$paths) {
6159          // Check $element is restore_path_element.
6160          if (! $element instanceof restore_path_element) {
6161              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6162          }
6163  
6164          // Check $paths is one array.
6165          if (!is_array($paths)) {
6166              throw new restore_step_exception('paths_must_be_array', $paths);
6167          }
6168  
6169          $paths[] = new restore_path_element('question_set_reference',
6170              $element->get_path() . '/question_set_reference');
6171      }
6172  
6173      /**
6174       * Process question set references data which replaces the random qtype.
6175       *
6176       * @param array $data the data from the XML file.
6177       */
6178      public function process_question_set_reference($data) {
6179          global $DB;
6180          $data = (object) $data;
6181          $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6182          $data->itemid = $this->get_new_parentid('quiz_question_instance');
6183          $filtercondition = json_decode($data->filtercondition);
6184          if ($category = $this->get_mappingid('question_category', $filtercondition->questioncategoryid)) {
6185              $filtercondition->questioncategoryid = $category;
6186          }
6187          $data->filtercondition = json_encode($filtercondition);
6188          if ($context = $this->get_mappingid('context', $data->questionscontextid)) {
6189              $data->questionscontextid = $context;
6190          }
6191  
6192          $DB->insert_record('question_set_references', $data);
6193      }
6194  }
6195  
6196  
6197  /**
6198   * Abstract structure step to help activities that store question attempt data.
6199   *
6200   * @copyright 2011 The Open University
6201   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6202   */
6203  abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
6204      use restore_questions_attempt_data_trait;
6205      use restore_question_reference_data_trait;
6206      use restore_question_set_reference_data_trait;
6207  
6208      /** @var \question_engine_attempt_upgrader manages upgrading all the question attempts. */
6209      private $attemptupgrader;
6210  
6211      /**
6212       * Attach below $element (usually attempts) the needed restore_path_elements
6213       * to restore question attempt data from Moodle 2.0.
6214       *
6215       * When using this method, the parent element ($element) must be defined with
6216       * $grouped = true. Then, in that elements process method, you must call
6217       * {@link process_legacy_attempt_data()} with the groupded data. See, for
6218       * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
6219       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6220       * @param array $paths the paths array that is being built to describe the
6221       *      structure.
6222       */
6223      protected function add_legacy_question_attempt_data($element, &$paths) {
6224          global $CFG;
6225          require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
6226  
6227          // Check $element is restore_path_element
6228          if (!($element instanceof restore_path_element)) {
6229              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6230          }
6231          // Check $paths is one array
6232          if (!is_array($paths)) {
6233              throw new restore_step_exception('paths_must_be_array', $paths);
6234          }
6235  
6236          $paths[] = new restore_path_element('question_state',
6237                  $element->get_path() . '/states/state');
6238          $paths[] = new restore_path_element('question_session',
6239                  $element->get_path() . '/sessions/session');
6240      }
6241  
6242      protected function get_attempt_upgrader() {
6243          if (empty($this->attemptupgrader)) {
6244              $this->attemptupgrader = new question_engine_attempt_upgrader();
6245              $this->attemptupgrader->prepare_to_restore();
6246          }
6247          return $this->attemptupgrader;
6248      }
6249  
6250      /**
6251       * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
6252       * @param object $data contains all the grouped attempt data to process.
6253       * @param object $quiz data about the activity the attempts belong to. Required
6254       * fields are (basically this only works for the quiz module):
6255       *      oldquestions => list of question ids in this activity - using old ids.
6256       *      preferredbehaviour => the behaviour to use for questionattempts.
6257       */
6258      protected function process_legacy_quiz_attempt_data($data, $quiz) {
6259          global $DB;
6260          $upgrader = $this->get_attempt_upgrader();
6261  
6262          $data = (object)$data;
6263  
6264          $layout = explode(',', $data->layout);
6265          $newlayout = $layout;
6266  
6267          // Convert each old question_session into a question_attempt.
6268          $qas = array();
6269          foreach (explode(',', $quiz->oldquestions) as $questionid) {
6270              if ($questionid == 0) {
6271                  continue;
6272              }
6273  
6274              $newquestionid = $this->get_mappingid('question', $questionid);
6275              if (!$newquestionid) {
6276                  throw new restore_step_exception('questionattemptreferstomissingquestion',
6277                          $questionid, $questionid);
6278              }
6279  
6280              $question = $upgrader->load_question($newquestionid, $quiz->id);
6281  
6282              foreach ($layout as $key => $qid) {
6283                  if ($qid == $questionid) {
6284                      $newlayout[$key] = $newquestionid;
6285                  }
6286              }
6287  
6288              list($qsession, $qstates) = $this->find_question_session_and_states(
6289                      $data, $questionid);
6290  
6291              if (empty($qsession) || empty($qstates)) {
6292                  throw new restore_step_exception('questionattemptdatamissing',
6293                          $questionid, $questionid);
6294              }
6295  
6296              list($qsession, $qstates) = $this->recode_legacy_response_data(
6297                      $question, $qsession, $qstates);
6298  
6299              $data->layout = implode(',', $newlayout);
6300              $qas[$newquestionid] = $upgrader->convert_question_attempt(
6301                      $quiz, $data, $question, $qsession, $qstates);
6302          }
6303  
6304          // Now create a new question_usage.
6305          $usage = new stdClass();
6306          $usage->component = 'mod_quiz';
6307          $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
6308          $usage->preferredbehaviour = $quiz->preferredbehaviour;
6309          $usage->id = $DB->insert_record('question_usages', $usage);
6310  
6311          $this->inform_new_usage_id($usage->id);
6312  
6313          $data->uniqueid = $usage->id;
6314          $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
6315                  $this->questions_recode_layout($quiz->oldquestions));
6316      }
6317  
6318      protected function find_question_session_and_states($data, $questionid) {
6319          $qsession = null;
6320          foreach ($data->sessions['session'] as $session) {
6321              if ($session['questionid'] == $questionid) {
6322                  $qsession = (object) $session;
6323                  break;
6324              }
6325          }
6326  
6327          $qstates = array();
6328          foreach ($data->states['state'] as $state) {
6329              if ($state['question'] == $questionid) {
6330                  // It would be natural to use $state['seq_number'] as the array-key
6331                  // here, but it seems that buggy behaviour in 2.0 and early can
6332                  // mean that that is not unique, so we use id, which is guaranteed
6333                  // to be unique.
6334                  $qstates[$state['id']] = (object) $state;
6335              }
6336          }
6337          ksort($qstates);
6338          $qstates = array_values($qstates);
6339  
6340          return array($qsession, $qstates);
6341      }
6342  
6343      /**
6344       * Recode any ids in the response data
6345       * @param object $question the question data
6346       * @param object $qsession the question sessions.
6347       * @param array $qstates the question states.
6348       */
6349      protected function recode_legacy_response_data($question, $qsession, $qstates) {
6350          $qsession->questionid = $question->id;
6351  
6352          foreach ($qstates as &$state) {
6353              $state->question = $question->id;
6354              $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
6355          }
6356  
6357          return array($qsession, $qstates);
6358      }
6359  
6360      /**
6361       * Recode the legacy answer field.
6362       * @param object $state the state to recode the answer of.
6363       * @param string $qtype the question type.
6364       */
6365      public function restore_recode_legacy_answer($state, $qtype) {
6366          $restorer = $this->get_qtype_restorer($qtype);
6367          if ($restorer) {
6368              return $restorer->recode_legacy_state_answer($state);
6369          } else {
6370              return $state->answer;
6371          }
6372      }
6373  }
6374  
6375  
6376  /**
6377   * Restore completion defaults for each module type
6378   *
6379   * @package     core_backup
6380   * @copyright   2017 Marina Glancy
6381   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6382   */
6383  class restore_completion_defaults_structure_step extends restore_structure_step {
6384      /**
6385       * To conditionally decide if this step must be executed.
6386       */
6387      protected function execute_condition() {
6388          // No completion on the front page.
6389          if ($this->get_courseid() == SITEID) {
6390              return false;
6391          }
6392  
6393          // No default completion info found, don't execute.
6394          $fullpath = $this->task->get_taskbasepath();
6395          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
6396          if (!file_exists($fullpath)) {
6397              return false;
6398          }
6399  
6400          // Arrived here, execute the step.
6401          return true;
6402      }
6403  
6404      /**
6405       * Function that will return the structure to be processed by this restore_step.
6406       *
6407       * @return restore_path_element[]
6408       */
6409      protected function define_structure() {
6410          return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
6411      }
6412  
6413      /**
6414       * Processor for path element 'completion_defaults'
6415       *
6416       * @param stdClass|array $data
6417       */
6418      protected function process_completion_defaults($data) {
6419          global $DB;
6420  
6421          $data = (array)$data;
6422          $oldid = $data['id'];
6423          unset($data['id']);
6424  
6425          // Find the module by name since id may be different in another site.
6426          if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
6427              return;
6428          }
6429          unset($data['modulename']);
6430  
6431          // Find the existing record.
6432          $newid = $DB->get_field('course_completion_defaults', 'id',
6433              ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
6434          if (!$newid) {
6435              $newid = $DB->insert_record('course_completion_defaults',
6436                  ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
6437          } else {
6438              $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
6439          }
6440  
6441          // Save id mapping for restoring associated events.
6442          $this->set_mapping('course_completion_defaults', $oldid, $newid);
6443      }
6444  }
6445  
6446  /**
6447   * Index course after restore.
6448   *
6449   * @package core_backup
6450   * @copyright 2017 The Open University
6451   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6452   */
6453  class restore_course_search_index extends restore_execution_step {
6454      /**
6455       * When this step is executed, we add the course context to the queue for reindexing.
6456       */
6457      protected function define_execution() {
6458          $context = \context_course::instance($this->task->get_courseid());
6459          \core_search\manager::request_index($context);
6460      }
6461  }
6462  
6463  /**
6464   * Index activity after restore (when not restoring whole course).
6465   *
6466   * @package core_backup
6467   * @copyright 2017 The Open University
6468   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6469   */
6470  class restore_activity_search_index extends restore_execution_step {
6471      /**
6472       * When this step is executed, we add the activity context to the queue for reindexing.
6473       */
6474      protected function define_execution() {
6475          $context = \context::instance_by_id($this->task->get_contextid());
6476          \core_search\manager::request_index($context);
6477      }
6478  }
6479  
6480  /**
6481   * Index block after restore (when not restoring whole course).
6482   *
6483   * @package core_backup
6484   * @copyright 2017 The Open University
6485   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6486   */
6487  class restore_block_search_index extends restore_execution_step {
6488      /**
6489       * When this step is executed, we add the block context to the queue for reindexing.
6490       */
6491      protected function define_execution() {
6492          // A block in the restore list may be skipped because a duplicate is detected.
6493          // In this case, there is no new blockid (or context) to get.
6494          if (!empty($this->task->get_blockid())) {
6495              $context = \context_block::instance($this->task->get_blockid());
6496              \core_search\manager::request_index($context);
6497          }
6498      }
6499  }
6500  
6501  /**
6502   * Restore action events.
6503   *
6504   * @package     core_backup
6505   * @copyright   2017 onwards Ankit Agarwal
6506   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6507   */
6508  class restore_calendar_action_events extends restore_execution_step {
6509      /**
6510       * What to do when this step is executed.
6511       */
6512      protected function define_execution() {
6513          // We just queue the task here rather trying to recreate everything manually.
6514          // The task will automatically populate all data.
6515          $task = new \core\task\refresh_mod_calendar_events_task();
6516          $task->set_custom_data(array('courseid' => $this->get_courseid()));
6517          \core\task\manager::queue_adhoc_task($task, true);
6518      }
6519  }