Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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());
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          $languages = get_string_manager()->get_list_of_translations(); // Get languages for quick search
1935          if (isset($data->lang) && !array_key_exists($data->lang, $languages)) {
1936              $data->lang = '';
1937          }
1938  
1939          $themes = get_list_of_themes(); // Get themes for quick search later
1940          if (!array_key_exists($data->theme, $themes) || empty($CFG->allowcoursethemes)) {
1941              $data->theme = '';
1942          }
1943  
1944          // Check if this is an old SCORM course format.
1945          if ($data->format == 'scorm') {
1946              $data->format = 'singleactivity';
1947              $data->activitytype = 'scorm';
1948          }
1949  
1950          // Course record ready, update it
1951          $DB->update_record('course', $data);
1952  
1953          // Apply any course format options that may be saved against the course
1954          // entity in earlier-version backups.
1955          course_get_format($data)->update_course_format_options($data);
1956  
1957          // Role name aliases
1958          restore_dbops::set_course_role_names($this->get_restoreid(), $this->get_courseid());
1959      }
1960  
1961      public function process_category($data) {
1962          // Nothing to do with the category. UI sets it before restore starts
1963      }
1964  
1965      public function process_tag($data) {
1966          global $CFG, $DB;
1967  
1968          $data = (object)$data;
1969  
1970          core_tag_tag::add_item_tag('core', 'course', $this->get_courseid(),
1971                  context_course::instance($this->get_courseid()), $data->rawname);
1972      }
1973  
1974      /**
1975       * Process custom fields
1976       *
1977       * @param array $data
1978       */
1979      public function process_customfield($data) {
1980          $handler = core_course\customfield\course_handler::create();
1981          $handler->restore_instance_data_from_backup($this->task, $data);
1982      }
1983  
1984      /**
1985       * Processes a course format option.
1986       *
1987       * @param array $data The record being restored.
1988       * @throws base_step_exception
1989       * @throws dml_exception
1990       */
1991      public function process_course_format_option(array $data) : void {
1992          global $DB;
1993  
1994          if ($data['sectionid']) {
1995              // Ignore section-level format options saved course-level in earlier-version backups.
1996              return;
1997          }
1998  
1999          $courseid = $this->get_courseid();
2000          $record = $DB->get_record('course_format_options', [ 'courseid' => $courseid, 'name' => $data['name'],
2001                  'format' => $data['format'], 'sectionid' => 0 ], 'id');
2002          if ($record !== false) {
2003              $DB->update_record('course_format_options', (object) [ 'id' => $record->id, 'value' => $data['value'] ]);
2004          } else {
2005              $data['courseid'] = $courseid;
2006              $DB->insert_record('course_format_options', (object) $data);
2007          }
2008      }
2009  
2010      public function process_allowed_module($data) {
2011          $data = (object)$data;
2012  
2013          // Backwards compatiblity support for the data that used to be in the
2014          // course_allowed_modules table.
2015          if ($this->legacyrestrictmodules) {
2016              $this->legacyallowedmodules[$data->modulename] = 1;
2017          }
2018      }
2019  
2020      protected function after_execute() {
2021          global $DB;
2022  
2023          // Add course related files, without itemid to match
2024          $this->add_related_files('course', 'summary', null);
2025          $this->add_related_files('course', 'overviewfiles', null);
2026  
2027          // Deal with legacy allowed modules.
2028          if ($this->legacyrestrictmodules) {
2029              $context = context_course::instance($this->get_courseid());
2030  
2031              list($roleids) = get_roles_with_cap_in_context($context, 'moodle/course:manageactivities');
2032              list($managerroleids) = get_roles_with_cap_in_context($context, 'moodle/site:config');
2033              foreach ($managerroleids as $roleid) {
2034                  unset($roleids[$roleid]);
2035              }
2036  
2037              foreach (core_component::get_plugin_list('mod') as $modname => $notused) {
2038                  if (isset($this->legacyallowedmodules[$modname])) {
2039                      // Module is allowed, no worries.
2040                      continue;
2041                  }
2042  
2043                  $capability = 'mod/' . $modname . ':addinstance';
2044  
2045                  if (!get_capability_info($capability)) {
2046                      $this->log("Capability '{$capability}' was not found!", backup::LOG_WARNING);
2047                      continue;
2048                  }
2049  
2050                  foreach ($roleids as $roleid) {
2051                      assign_capability($capability, CAP_PREVENT, $roleid, $context);
2052                  }
2053              }
2054          }
2055      }
2056  }
2057  
2058  /**
2059   * Execution step that will migrate legacy files if present.
2060   */
2061  class restore_course_legacy_files_step extends restore_execution_step {
2062      public function define_execution() {
2063          global $DB;
2064  
2065          // Do a check for legacy files and skip if there are none.
2066          $sql = 'SELECT count(*)
2067                    FROM {backup_files_temp}
2068                   WHERE backupid = ?
2069                     AND contextid = ?
2070                     AND component = ?
2071                     AND filearea  = ?';
2072          $params = array($this->get_restoreid(), $this->task->get_old_contextid(), 'course', 'legacy');
2073  
2074          if ($DB->count_records_sql($sql, $params)) {
2075              $DB->set_field('course', 'legacyfiles', 2, array('id' => $this->get_courseid()));
2076              restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'course',
2077                  'legacy', $this->task->get_old_contextid(), $this->task->get_userid());
2078          }
2079      }
2080  }
2081  
2082  /*
2083   * Structure step that will read the roles.xml file (at course/activity/block levels)
2084   * containing all the role_assignments and overrides for that context. If corresponding to
2085   * one mapped role, they will be applied to target context. Will observe the role_assignments
2086   * setting to decide if ras are restored.
2087   *
2088   * Note: this needs to be executed after all users are enrolled.
2089   */
2090  class restore_ras_and_caps_structure_step extends restore_structure_step {
2091      protected $plugins = null;
2092  
2093      protected function define_structure() {
2094  
2095          $paths = array();
2096  
2097          // Observe the role_assignments setting
2098          if ($this->get_setting_value('role_assignments')) {
2099              $paths[] = new restore_path_element('assignment', '/roles/role_assignments/assignment');
2100          }
2101          if ($this->get_setting_value('permissions')) {
2102              $paths[] = new restore_path_element('override', '/roles/role_overrides/override');
2103          }
2104  
2105          return $paths;
2106      }
2107  
2108      /**
2109       * Assign roles
2110       *
2111       * This has to be called after enrolments processing.
2112       *
2113       * @param mixed $data
2114       * @return void
2115       */
2116      public function process_assignment($data) {
2117          global $DB;
2118  
2119          $data = (object)$data;
2120  
2121          // Check roleid, userid are one of the mapped ones
2122          if (!$newroleid = $this->get_mappingid('role', $data->roleid)) {
2123              return;
2124          }
2125          if (!$newuserid = $this->get_mappingid('user', $data->userid)) {
2126              return;
2127          }
2128          if (!$DB->record_exists('user', array('id' => $newuserid, 'deleted' => 0))) {
2129              // Only assign roles to not deleted users
2130              return;
2131          }
2132          if (!$contextid = $this->task->get_contextid()) {
2133              return;
2134          }
2135  
2136          if (empty($data->component)) {
2137              // assign standard manual roles
2138              // TODO: role_assign() needs one userid param to be able to specify our restore userid
2139              role_assign($newroleid, $newuserid, $contextid);
2140  
2141          } else if ((strpos($data->component, 'enrol_') === 0)) {
2142              // Deal with enrolment roles - ignore the component and just find out the instance via new id,
2143              // it is possible that enrolment was restored using different plugin type.
2144              if (!isset($this->plugins)) {
2145                  $this->plugins = enrol_get_plugins(true);
2146              }
2147              if ($enrolid = $this->get_mappingid('enrol', $data->itemid)) {
2148                  if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2149                      if (isset($this->plugins[$instance->enrol])) {
2150                          $this->plugins[$instance->enrol]->restore_role_assignment($instance, $newroleid, $newuserid, $contextid);
2151                      }
2152                  }
2153              }
2154  
2155          } else {
2156              $data->roleid    = $newroleid;
2157              $data->userid    = $newuserid;
2158              $data->contextid = $contextid;
2159              $dir = core_component::get_component_directory($data->component);
2160              if ($dir and is_dir($dir)) {
2161                  if (component_callback($data->component, 'restore_role_assignment', array($this, $data), true)) {
2162                      return;
2163                  }
2164              }
2165              // Bad luck, plugin could not restore the data, let's add normal membership.
2166              role_assign($data->roleid, $data->userid, $data->contextid);
2167              $message = "Restore of '$data->component/$data->itemid' role assignments is not supported, using manual role assignments instead.";
2168              $this->log($message, backup::LOG_WARNING);
2169          }
2170      }
2171  
2172      public function process_override($data) {
2173          $data = (object)$data;
2174          // Check roleid is one of the mapped ones
2175          $newrole = $this->get_mapping('role', $data->roleid);
2176          $newroleid = $newrole->newitemid ?? false;
2177          $userid = $this->task->get_userid();
2178  
2179          // If newroleid and context are valid assign it via API (it handles dupes and so on)
2180          if ($newroleid && $this->task->get_contextid()) {
2181              if (!$capability = get_capability_info($data->capability)) {
2182                  $this->log("Capability '{$data->capability}' was not found!", backup::LOG_WARNING);
2183              } else {
2184                  $context = context::instance_by_id($this->task->get_contextid());
2185                  $overrideableroles = get_overridable_roles($context, ROLENAME_SHORT);
2186                  $safecapability = is_safe_capability($capability);
2187  
2188                  // Check if the new role is an overrideable role AND if the user performing the restore has the
2189                  // capability to assign the capability.
2190                  if (in_array($newrole->info['shortname'], $overrideableroles) &&
2191                      (has_capability('moodle/role:override', $context, $userid) ||
2192                              ($safecapability && has_capability('moodle/role:safeoverride', $context, $userid)))
2193                  ) {
2194                      assign_capability($data->capability, $data->permission, $newroleid, $this->task->get_contextid());
2195                  } else {
2196                      $this->log("Insufficient capability to assign capability '{$data->capability}' to role!", backup::LOG_WARNING);
2197                  }
2198              }
2199          }
2200      }
2201  }
2202  
2203  /**
2204   * If no instances yet add default enrol methods the same way as when creating new course in UI.
2205   */
2206  class restore_default_enrolments_step extends restore_execution_step {
2207  
2208      public function define_execution() {
2209          global $DB;
2210  
2211          // No enrolments in front page.
2212          if ($this->get_courseid() == SITEID) {
2213              return;
2214          }
2215  
2216          $course = $DB->get_record('course', array('id'=>$this->get_courseid()), '*', MUST_EXIST);
2217          // Return any existing course enrolment instances.
2218          $enrolinstances = enrol_get_instances($course->id, false);
2219  
2220          if ($enrolinstances) {
2221              // Something already added instances.
2222              // Get the existing enrolment methods in the course.
2223              $enrolmethods = array_map(function($enrolinstance) {
2224                  return $enrolinstance->enrol;
2225              }, $enrolinstances);
2226  
2227              $plugins = enrol_get_plugins(true);
2228              foreach ($plugins as $pluginname => $plugin) {
2229                  // Make sure all default enrolment methods exist in the course.
2230                  if (!in_array($pluginname, $enrolmethods)) {
2231                      $plugin->course_updated(true, $course, null);
2232                  }
2233                  $plugin->restore_sync_course($course);
2234              }
2235  
2236          } else {
2237              // Looks like a newly created course.
2238              enrol_course_updated(true, $course, null);
2239          }
2240      }
2241  }
2242  
2243  /**
2244   * This structure steps restores the enrol plugins and their underlying
2245   * enrolments, performing all the mappings and/or movements required
2246   */
2247  class restore_enrolments_structure_step extends restore_structure_step {
2248      protected $enrolsynced = false;
2249      protected $plugins = null;
2250      protected $originalstatus = array();
2251  
2252      /**
2253       * Conditionally decide if this step should be executed.
2254       *
2255       * This function checks the following parameter:
2256       *
2257       *   1. the course/enrolments.xml file exists
2258       *
2259       * @return bool true is safe to execute, false otherwise
2260       */
2261      protected function execute_condition() {
2262  
2263          if ($this->get_courseid() == SITEID) {
2264              return false;
2265          }
2266  
2267          // Check it is included in the backup
2268          $fullpath = $this->task->get_taskbasepath();
2269          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2270          if (!file_exists($fullpath)) {
2271              // Not found, can't restore enrolments info
2272              return false;
2273          }
2274  
2275          return true;
2276      }
2277  
2278      protected function define_structure() {
2279  
2280          $userinfo = $this->get_setting_value('users');
2281  
2282          $paths = [];
2283          $paths[] = $enrol = new restore_path_element('enrol', '/enrolments/enrols/enrol');
2284          if ($userinfo) {
2285              $paths[] = new restore_path_element('enrolment', '/enrolments/enrols/enrol/user_enrolments/enrolment');
2286          }
2287          // Attach local plugin stucture to enrol element.
2288          $this->add_plugin_structure('enrol', $enrol);
2289  
2290          return $paths;
2291      }
2292  
2293      /**
2294       * Create enrolment instances.
2295       *
2296       * This has to be called after creation of roles
2297       * and before adding of role assignments.
2298       *
2299       * @param mixed $data
2300       * @return void
2301       */
2302      public function process_enrol($data) {
2303          global $DB;
2304  
2305          $data = (object)$data;
2306          $oldid = $data->id; // We'll need this later.
2307          unset($data->id);
2308  
2309          $this->originalstatus[$oldid] = $data->status;
2310  
2311          if (!$courserec = $DB->get_record('course', array('id' => $this->get_courseid()))) {
2312              $this->set_mapping('enrol', $oldid, 0);
2313              return;
2314          }
2315  
2316          if (!isset($this->plugins)) {
2317              $this->plugins = enrol_get_plugins(true);
2318          }
2319  
2320          if (!$this->enrolsynced) {
2321              // Make sure that all plugin may create instances and enrolments automatically
2322              // before the first instance restore - this is suitable especially for plugins
2323              // that synchronise data automatically using course->idnumber or by course categories.
2324              foreach ($this->plugins as $plugin) {
2325                  $plugin->restore_sync_course($courserec);
2326              }
2327              $this->enrolsynced = true;
2328          }
2329  
2330          // Map standard fields - plugin has to process custom fields manually.
2331          $data->roleid   = $this->get_mappingid('role', $data->roleid);
2332          $data->courseid = $courserec->id;
2333  
2334          if (!$this->get_setting_value('users') && $this->get_setting_value('enrolments') == backup::ENROL_WITHUSERS) {
2335              $converttomanual = true;
2336          } else {
2337              $converttomanual = ($this->get_setting_value('enrolments') == backup::ENROL_NEVER);
2338          }
2339  
2340          if ($converttomanual) {
2341              // Restore enrolments as manual enrolments.
2342              unset($data->sortorder); // Remove useless sortorder from <2.4 backups.
2343              if (!enrol_is_enabled('manual')) {
2344                  $this->set_mapping('enrol', $oldid, 0);
2345                  return;
2346              }
2347              if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
2348                  $instance = reset($instances);
2349                  $this->set_mapping('enrol', $oldid, $instance->id);
2350              } else {
2351                  if ($data->enrol === 'manual') {
2352                      $instanceid = $this->plugins['manual']->add_instance($courserec, (array)$data);
2353                  } else {
2354                      $instanceid = $this->plugins['manual']->add_default_instance($courserec);
2355                  }
2356                  $this->set_mapping('enrol', $oldid, $instanceid);
2357              }
2358  
2359          } else {
2360              if (!enrol_is_enabled($data->enrol) or !isset($this->plugins[$data->enrol])) {
2361                  $this->set_mapping('enrol', $oldid, 0);
2362                  $message = "Enrol plugin '$data->enrol' data can not be restored because it is not enabled, consider restoring without enrolment methods";
2363                  $this->log($message, backup::LOG_WARNING);
2364                  return;
2365              }
2366              if ($task = $this->get_task() and $task->get_target() == backup::TARGET_NEW_COURSE) {
2367                  // Let's keep the sortorder in old backups.
2368              } else {
2369                  // Prevent problems with colliding sortorders in old backups,
2370                  // new 2.4 backups do not need sortorder because xml elements are ordered properly.
2371                  unset($data->sortorder);
2372              }
2373              // Note: plugin is responsible for setting up the mapping, it may also decide to migrate to different type.
2374              $this->plugins[$data->enrol]->restore_instance($this, $data, $courserec, $oldid);
2375          }
2376      }
2377  
2378      /**
2379       * Create user enrolments.
2380       *
2381       * This has to be called after creation of enrolment instances
2382       * and before adding of role assignments.
2383       *
2384       * Roles are assigned in restore_ras_and_caps_structure_step::process_assignment() processing afterwards.
2385       *
2386       * @param mixed $data
2387       * @return void
2388       */
2389      public function process_enrolment($data) {
2390          global $DB;
2391  
2392          if (!isset($this->plugins)) {
2393              $this->plugins = enrol_get_plugins(true);
2394          }
2395  
2396          $data = (object)$data;
2397  
2398          // Process only if parent instance have been mapped.
2399          if ($enrolid = $this->get_new_parentid('enrol')) {
2400              $oldinstancestatus = ENROL_INSTANCE_ENABLED;
2401              $oldenrolid = $this->get_old_parentid('enrol');
2402              if (isset($this->originalstatus[$oldenrolid])) {
2403                  $oldinstancestatus = $this->originalstatus[$oldenrolid];
2404              }
2405              if ($instance = $DB->get_record('enrol', array('id'=>$enrolid))) {
2406                  // And only if user is a mapped one.
2407                  if ($userid = $this->get_mappingid('user', $data->userid)) {
2408                      if (isset($this->plugins[$instance->enrol])) {
2409                          $this->plugins[$instance->enrol]->restore_user_enrolment($this, $data, $instance, $userid, $oldinstancestatus);
2410                      }
2411                  }
2412              }
2413          }
2414      }
2415  }
2416  
2417  
2418  /**
2419   * Make sure the user restoring the course can actually access it.
2420   */
2421  class restore_fix_restorer_access_step extends restore_execution_step {
2422      protected function define_execution() {
2423          global $CFG, $DB;
2424  
2425          if (!$userid = $this->task->get_userid()) {
2426              return;
2427          }
2428  
2429          if (empty($CFG->restorernewroleid)) {
2430              // Bad luck, no fallback role for restorers specified
2431              return;
2432          }
2433  
2434          $courseid = $this->get_courseid();
2435          $context = context_course::instance($courseid);
2436  
2437          if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2438              // Current user may access the course (admin, category manager or restored teacher enrolment usually)
2439              return;
2440          }
2441  
2442          // Try to add role only - we do not need enrolment if user has moodle/course:view or is already enrolled
2443          role_assign($CFG->restorernewroleid, $userid, $context);
2444  
2445          if (is_enrolled($context, $userid, 'moodle/course:update', true) or is_viewing($context, $userid, 'moodle/course:update')) {
2446              // Extra role is enough, yay!
2447              return;
2448          }
2449  
2450          // The last chance is to create manual enrol if it does not exist and and try to enrol the current user,
2451          // hopefully admin selected suitable $CFG->restorernewroleid ...
2452          if (!enrol_is_enabled('manual')) {
2453              return;
2454          }
2455          if (!$enrol = enrol_get_plugin('manual')) {
2456              return;
2457          }
2458          if (!$DB->record_exists('enrol', array('enrol'=>'manual', 'courseid'=>$courseid))) {
2459              $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
2460              $fields = array('status'=>ENROL_INSTANCE_ENABLED, 'enrolperiod'=>$enrol->get_config('enrolperiod', 0), 'roleid'=>$enrol->get_config('roleid', 0));
2461              $enrol->add_instance($course, $fields);
2462          }
2463  
2464          enrol_try_internal_enrol($courseid, $userid);
2465      }
2466  }
2467  
2468  
2469  /**
2470   * This structure steps restores the filters and their configs
2471   */
2472  class restore_filters_structure_step extends restore_structure_step {
2473  
2474      protected function define_structure() {
2475  
2476          $paths = array();
2477  
2478          $paths[] = new restore_path_element('active', '/filters/filter_actives/filter_active');
2479          $paths[] = new restore_path_element('config', '/filters/filter_configs/filter_config');
2480  
2481          return $paths;
2482      }
2483  
2484      public function process_active($data) {
2485  
2486          $data = (object)$data;
2487  
2488          if (strpos($data->filter, 'filter/') === 0) {
2489              $data->filter = substr($data->filter, 7);
2490  
2491          } else if (strpos($data->filter, '/') !== false) {
2492              // Unsupported old filter.
2493              return;
2494          }
2495  
2496          if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2497              return;
2498          }
2499          filter_set_local_state($data->filter, $this->task->get_contextid(), $data->active);
2500      }
2501  
2502      public function process_config($data) {
2503  
2504          $data = (object)$data;
2505  
2506          if (strpos($data->filter, 'filter/') === 0) {
2507              $data->filter = substr($data->filter, 7);
2508  
2509          } else if (strpos($data->filter, '/') !== false) {
2510              // Unsupported old filter.
2511              return;
2512          }
2513  
2514          if (!filter_is_enabled($data->filter)) { // Not installed or not enabled, nothing to do
2515              return;
2516          }
2517          filter_set_local_config($data->filter, $this->task->get_contextid(), $data->name, $data->value);
2518      }
2519  }
2520  
2521  
2522  /**
2523   * This structure steps restores the comments
2524   * Note: Cannot use the comments API because defaults to USER->id.
2525   * That should change allowing to pass $userid
2526   */
2527  class restore_comments_structure_step extends restore_structure_step {
2528  
2529      protected function define_structure() {
2530  
2531          $paths = array();
2532  
2533          $paths[] = new restore_path_element('comment', '/comments/comment');
2534  
2535          return $paths;
2536      }
2537  
2538      public function process_comment($data) {
2539          global $DB;
2540  
2541          $data = (object)$data;
2542  
2543          // First of all, if the comment has some itemid, ask to the task what to map
2544          $mapping = false;
2545          if ($data->itemid) {
2546              $mapping = $this->task->get_comment_mapping_itemname($data->commentarea);
2547              $data->itemid = $this->get_mappingid($mapping, $data->itemid);
2548          }
2549          // Only restore the comment if has no mapping OR we have found the matching mapping
2550          if (!$mapping || $data->itemid) {
2551              // Only if user mapping and context
2552              $data->userid = $this->get_mappingid('user', $data->userid);
2553              if ($data->userid && $this->task->get_contextid()) {
2554                  $data->contextid = $this->task->get_contextid();
2555                  // Only if there is another comment with same context/user/timecreated
2556                  $params = array('contextid' => $data->contextid, 'userid' => $data->userid, 'timecreated' => $data->timecreated);
2557                  if (!$DB->record_exists('comments', $params)) {
2558                      $DB->insert_record('comments', $data);
2559                  }
2560              }
2561          }
2562      }
2563  }
2564  
2565  /**
2566   * This structure steps restores the badges and their configs
2567   */
2568  class restore_badges_structure_step extends restore_structure_step {
2569  
2570      /**
2571       * Conditionally decide if this step should be executed.
2572       *
2573       * This function checks the following parameters:
2574       *
2575       *   1. Badges and course badges are enabled on the site.
2576       *   2. The course/badges.xml file exists.
2577       *   3. All modules are restorable.
2578       *   4. All modules are marked for restore.
2579       *
2580       * @return bool True is safe to execute, false otherwise
2581       */
2582      protected function execute_condition() {
2583          global $CFG;
2584  
2585          // First check is badges and course level badges are enabled on this site.
2586          if (empty($CFG->enablebadges) || empty($CFG->badges_allowcoursebadges)) {
2587              // Disabled, don't restore course badges.
2588              return false;
2589          }
2590  
2591          // Check if badges.xml is included in the backup.
2592          $fullpath = $this->task->get_taskbasepath();
2593          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
2594          if (!file_exists($fullpath)) {
2595              // Not found, can't restore course badges.
2596              return false;
2597          }
2598  
2599          // Check we are able to restore all backed up modules.
2600          if ($this->task->is_missing_modules()) {
2601              return false;
2602          }
2603  
2604          // Finally check all modules within the backup are being restored.
2605          if ($this->task->is_excluding_activities()) {
2606              return false;
2607          }
2608  
2609          return true;
2610      }
2611  
2612      protected function define_structure() {
2613          $paths = array();
2614          $paths[] = new restore_path_element('badge', '/badges/badge');
2615          $paths[] = new restore_path_element('criterion', '/badges/badge/criteria/criterion');
2616          $paths[] = new restore_path_element('parameter', '/badges/badge/criteria/criterion/parameters/parameter');
2617          $paths[] = new restore_path_element('endorsement', '/badges/badge/endorsement');
2618          $paths[] = new restore_path_element('alignment', '/badges/badge/alignments/alignment');
2619          $paths[] = new restore_path_element('relatedbadge', '/badges/badge/relatedbadges/relatedbadge');
2620          $paths[] = new restore_path_element('manual_award', '/badges/badge/manual_awards/manual_award');
2621  
2622          return $paths;
2623      }
2624  
2625      public function process_badge($data) {
2626          global $DB, $CFG;
2627  
2628          require_once($CFG->libdir . '/badgeslib.php');
2629  
2630          $data = (object)$data;
2631          $data->usercreated = $this->get_mappingid('user', $data->usercreated);
2632          if (empty($data->usercreated)) {
2633              $data->usercreated = $this->task->get_userid();
2634          }
2635          $data->usermodified = $this->get_mappingid('user', $data->usermodified);
2636          if (empty($data->usermodified)) {
2637              $data->usermodified = $this->task->get_userid();
2638          }
2639  
2640          // We'll restore the badge image.
2641          $restorefiles = true;
2642  
2643          $courseid = $this->get_courseid();
2644  
2645          $params = array(
2646                  'name'           => $data->name,
2647                  'description'    => $data->description,
2648                  'timecreated'    => $data->timecreated,
2649                  'timemodified'   => $data->timemodified,
2650                  'usercreated'    => $data->usercreated,
2651                  'usermodified'   => $data->usermodified,
2652                  'issuername'     => $data->issuername,
2653                  'issuerurl'      => $data->issuerurl,
2654                  'issuercontact'  => $data->issuercontact,
2655                  'expiredate'     => $this->apply_date_offset($data->expiredate),
2656                  'expireperiod'   => $data->expireperiod,
2657                  'type'           => BADGE_TYPE_COURSE,
2658                  'courseid'       => $courseid,
2659                  'message'        => $data->message,
2660                  'messagesubject' => $data->messagesubject,
2661                  'attachment'     => $data->attachment,
2662                  'notification'   => $data->notification,
2663                  'status'         => BADGE_STATUS_INACTIVE,
2664                  'nextcron'       => $data->nextcron,
2665                  'version'        => $data->version,
2666                  'language'       => $data->language,
2667                  'imageauthorname' => $data->imageauthorname,
2668                  'imageauthoremail' => $data->imageauthoremail,
2669                  'imageauthorurl' => $data->imageauthorurl,
2670                  'imagecaption'   => $data->imagecaption
2671          );
2672  
2673          $newid = $DB->insert_record('badge', $params);
2674          $this->set_mapping('badge', $data->id, $newid, $restorefiles);
2675      }
2676  
2677      /**
2678       * Create an endorsement for a badge.
2679       *
2680       * @param mixed $data
2681       * @return void
2682       */
2683      public function process_endorsement($data) {
2684          global $DB;
2685  
2686          $data = (object)$data;
2687  
2688          $params = [
2689              'badgeid' => $this->get_new_parentid('badge'),
2690              'issuername' => $data->issuername,
2691              'issuerurl' => $data->issuerurl,
2692              'issueremail' => $data->issueremail,
2693              'claimid' => $data->claimid,
2694              'claimcomment' => $data->claimcomment,
2695              'dateissued' => $this->apply_date_offset($data->dateissued)
2696          ];
2697          $newid = $DB->insert_record('badge_endorsement', $params);
2698          $this->set_mapping('endorsement', $data->id, $newid);
2699      }
2700  
2701      /**
2702       * Link to related badges for a badge. This relies on post processing in after_execute().
2703       *
2704       * @param mixed $data
2705       * @return void
2706       */
2707      public function process_relatedbadge($data) {
2708          global $DB;
2709  
2710          $data = (object)$data;
2711          $relatedbadgeid = $data->relatedbadgeid;
2712  
2713          if ($relatedbadgeid) {
2714              // Only backup and restore related badges if they are contained in the backup file.
2715              $params = array(
2716                      'badgeid'           => $this->get_new_parentid('badge'),
2717                      'relatedbadgeid'    => $relatedbadgeid
2718              );
2719              $newid = $DB->insert_record('badge_related', $params);
2720          }
2721      }
2722  
2723      /**
2724       * Link to an alignment for a badge.
2725       *
2726       * @param mixed $data
2727       * @return void
2728       */
2729      public function process_alignment($data) {
2730          global $DB;
2731  
2732          $data = (object)$data;
2733          $params = array(
2734                  'badgeid'           => $this->get_new_parentid('badge'),
2735                  'targetname'        => $data->targetname,
2736                  'targeturl'         => $data->targeturl,
2737                  'targetdescription' => $data->targetdescription,
2738                  'targetframework'   => $data->targetframework,
2739                  'targetcode'        => $data->targetcode
2740          );
2741          $newid = $DB->insert_record('badge_alignment', $params);
2742          $this->set_mapping('alignment', $data->id, $newid);
2743      }
2744  
2745      public function process_criterion($data) {
2746          global $DB;
2747  
2748          $data = (object)$data;
2749  
2750          $params = array(
2751                  'badgeid'           => $this->get_new_parentid('badge'),
2752                  'criteriatype'      => $data->criteriatype,
2753                  'method'            => $data->method,
2754                  'description'       => isset($data->description) ? $data->description : '',
2755                  'descriptionformat' => isset($data->descriptionformat) ? $data->descriptionformat : 0,
2756          );
2757  
2758          $newid = $DB->insert_record('badge_criteria', $params);
2759          $this->set_mapping('criterion', $data->id, $newid);
2760      }
2761  
2762      public function process_parameter($data) {
2763          global $DB, $CFG;
2764  
2765          require_once($CFG->libdir . '/badgeslib.php');
2766  
2767          $data = (object)$data;
2768          $criteriaid = $this->get_new_parentid('criterion');
2769  
2770          // Parameter array that will go to database.
2771          $params = array();
2772          $params['critid'] = $criteriaid;
2773  
2774          $oldparam = explode('_', $data->name);
2775  
2776          if ($data->criteriatype == BADGE_CRITERIA_TYPE_ACTIVITY) {
2777              $module = $this->get_mappingid('course_module', $oldparam[1]);
2778              $params['name'] = $oldparam[0] . '_' . $module;
2779              $params['value'] = $oldparam[0] == 'module' ? $module : $data->value;
2780          } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COURSE) {
2781              $params['name'] = $oldparam[0] . '_' . $this->get_courseid();
2782              $params['value'] = $oldparam[0] == 'course' ? $this->get_courseid() : $data->value;
2783          } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_MANUAL) {
2784              $role = $this->get_mappingid('role', $data->value);
2785              if (!empty($role)) {
2786                  $params['name'] = 'role_' . $role;
2787                  $params['value'] = $role;
2788              } else {
2789                  return;
2790              }
2791          } else if ($data->criteriatype == BADGE_CRITERIA_TYPE_COMPETENCY) {
2792              $competencyid = $this->get_mappingid('competency', $data->value);
2793              if (!empty($competencyid)) {
2794                  $params['name'] = 'competency_' . $competencyid;
2795                  $params['value'] = $competencyid;
2796              } else {
2797                  return;
2798              }
2799          }
2800  
2801          if (!$DB->record_exists('badge_criteria_param', $params)) {
2802              $DB->insert_record('badge_criteria_param', $params);
2803          }
2804      }
2805  
2806      public function process_manual_award($data) {
2807          global $DB;
2808  
2809          $data = (object)$data;
2810          $role = $this->get_mappingid('role', $data->issuerrole);
2811  
2812          if (!empty($role)) {
2813              $award = array(
2814                  'badgeid'     => $this->get_new_parentid('badge'),
2815                  'recipientid' => $this->get_mappingid('user', $data->recipientid),
2816                  'issuerid'    => $this->get_mappingid('user', $data->issuerid),
2817                  'issuerrole'  => $role,
2818                  'datemet'     => $this->apply_date_offset($data->datemet)
2819              );
2820  
2821              // Skip the manual award if recipient or issuer can not be mapped to.
2822              if (empty($award['recipientid']) || empty($award['issuerid'])) {
2823                  return;
2824              }
2825  
2826              $DB->insert_record('badge_manual_award', $award);
2827          }
2828      }
2829  
2830      protected function after_execute() {
2831          global $DB;
2832          // Add related files.
2833          $this->add_related_files('badges', 'badgeimage', 'badge');
2834  
2835          $badgeid = $this->get_new_parentid('badge');
2836          // Remap any related badges.
2837          // We do this in the DB directly because this is backup/restore it is not valid to call into
2838          // the component API.
2839          $params = array('badgeid' => $badgeid);
2840          $query = "SELECT DISTINCT br.id, br.badgeid, br.relatedbadgeid
2841                      FROM {badge_related} br
2842                     WHERE (br.badgeid = :badgeid)";
2843          $relatedbadges = $DB->get_records_sql($query, $params);
2844          $newrelatedids = [];
2845          foreach ($relatedbadges as $relatedbadge) {
2846              $relatedid = $this->get_mappingid('badge', $relatedbadge->relatedbadgeid);
2847              $params['relatedbadgeid'] = $relatedbadge->relatedbadgeid;
2848              $DB->delete_records_select('badge_related', '(badgeid = :badgeid AND relatedbadgeid = :relatedbadgeid)', $params);
2849              if ($relatedid) {
2850                  $newrelatedids[] = $relatedid;
2851              }
2852          }
2853          if (!empty($newrelatedids)) {
2854              $relatedbadges = [];
2855              foreach ($newrelatedids as $relatedid) {
2856                  $relatedbadge = new stdClass();
2857                  $relatedbadge->badgeid = $badgeid;
2858                  $relatedbadge->relatedbadgeid = $relatedid;
2859                  $relatedbadges[] = $relatedbadge;
2860              }
2861              $DB->insert_records('badge_related', $relatedbadges);
2862          }
2863      }
2864  }
2865  
2866  /**
2867   * This structure steps restores the calendar events
2868   */
2869  class restore_calendarevents_structure_step extends restore_structure_step {
2870  
2871      protected function define_structure() {
2872  
2873          $paths = array();
2874  
2875          $paths[] = new restore_path_element('calendarevents', '/events/event');
2876  
2877          return $paths;
2878      }
2879  
2880      public function process_calendarevents($data) {
2881          global $DB, $SITE, $USER;
2882  
2883          $data = (object)$data;
2884          $oldid = $data->id;
2885          $restorefiles = true; // We'll restore the files
2886  
2887          // If this is a new action event, it will automatically be populated by the adhoc task.
2888          // Nothing to do here.
2889          if (isset($data->type) && $data->type == CALENDAR_EVENT_TYPE_ACTION) {
2890              return;
2891          }
2892  
2893          // User overrides for activities are identified by having a courseid of zero with
2894          // both a modulename and instance value set.
2895          $isuseroverride = !$data->courseid && $data->modulename && $data->instance;
2896  
2897          // If we don't want to include user data and this record is a user override event
2898          // for an activity then we should not create it. (Only activity events can be user override events - which must have this
2899          // setting).
2900          if ($isuseroverride && $this->task->setting_exists('userinfo') && !$this->task->get_setting_value('userinfo')) {
2901              return;
2902          }
2903  
2904          // Find the userid and the groupid associated with the event.
2905          $data->userid = $this->get_mappingid('user', $data->userid);
2906          if ($data->userid === false) {
2907              // Blank user ID means that we are dealing with module generated events such as quiz starting times.
2908              // Use the current user ID for these events.
2909              $data->userid = $USER->id;
2910          }
2911          if (!empty($data->groupid)) {
2912              $data->groupid = $this->get_mappingid('group', $data->groupid);
2913              if ($data->groupid === false) {
2914                  return;
2915              }
2916          }
2917          // Handle events with empty eventtype //MDL-32827
2918          if(empty($data->eventtype)) {
2919              if ($data->courseid == $SITE->id) {                                // Site event
2920                  $data->eventtype = "site";
2921              } else if ($data->courseid != 0 && $data->groupid == 0 && ($data->modulename == 'assignment' || $data->modulename == 'assign')) {
2922                  // Course assingment event
2923                  $data->eventtype = "due";
2924              } else if ($data->courseid != 0 && $data->groupid == 0) {      // Course event
2925                  $data->eventtype = "course";
2926              } else if ($data->groupid) {                                      // Group event
2927                  $data->eventtype = "group";
2928              } else if ($data->userid) {                                       // User event
2929                  $data->eventtype = "user";
2930              } else {
2931                  return;
2932              }
2933          }
2934  
2935          $params = array(
2936                  'name'           => $data->name,
2937                  'description'    => $data->description,
2938                  'format'         => $data->format,
2939                  // User overrides in activities use a course id of zero. All other event types
2940                  // must use the mapped course id.
2941                  'courseid'       => $data->courseid ? $this->get_courseid() : 0,
2942                  'groupid'        => $data->groupid,
2943                  'userid'         => $data->userid,
2944                  'repeatid'       => $this->get_mappingid('event', $data->repeatid),
2945                  'modulename'     => $data->modulename,
2946                  'type'           => isset($data->type) ? $data->type : 0,
2947                  'eventtype'      => $data->eventtype,
2948                  'timestart'      => $this->apply_date_offset($data->timestart),
2949                  'timeduration'   => $data->timeduration,
2950                  'timesort'       => isset($data->timesort) ? $this->apply_date_offset($data->timesort) : null,
2951                  'visible'        => $data->visible,
2952                  'uuid'           => $data->uuid,
2953                  'sequence'       => $data->sequence,
2954                  'timemodified'   => $data->timemodified,
2955                  'priority'       => isset($data->priority) ? $data->priority : null,
2956                  'location'       => isset($data->location) ? $data->location : null);
2957          if ($this->name == 'activity_calendar') {
2958              $params['instance'] = $this->task->get_activityid();
2959          } else {
2960              $params['instance'] = 0;
2961          }
2962          $sql = "SELECT id
2963                    FROM {event}
2964                   WHERE " . $DB->sql_compare_text('name', 255) . " = " . $DB->sql_compare_text('?', 255) . "
2965                     AND courseid = ?
2966                     AND modulename = ?
2967                     AND instance = ?
2968                     AND timestart = ?
2969                     AND timeduration = ?
2970                     AND " . $DB->sql_compare_text('description', 255) . " = " . $DB->sql_compare_text('?', 255);
2971          $arg = array ($params['name'], $params['courseid'], $params['modulename'], $params['instance'], $params['timestart'], $params['timeduration'], $params['description']);
2972          $result = $DB->record_exists_sql($sql, $arg);
2973          if (empty($result)) {
2974              $newitemid = $DB->insert_record('event', $params);
2975              $this->set_mapping('event', $oldid, $newitemid);
2976              $this->set_mapping('event_description', $oldid, $newitemid, $restorefiles);
2977          }
2978          // With repeating events, each event has the repeatid pointed at the first occurrence.
2979          // Since the repeatid will be empty when the first occurrence is restored,
2980          // Get the repeatid from the second occurrence of the repeating event and use that to update the first occurrence.
2981          // Then keep a list of repeatids so we only perform this update once.
2982          static $repeatids = array();
2983          if (!empty($params['repeatid']) && !in_array($params['repeatid'], $repeatids)) {
2984              // This entry is repeated so the repeatid field must be set.
2985              $DB->set_field('event', 'repeatid', $params['repeatid'], array('id' => $params['repeatid']));
2986              $repeatids[] = $params['repeatid'];
2987          }
2988  
2989      }
2990      protected function after_execute() {
2991          // Add related files
2992          $this->add_related_files('calendar', 'event_description', 'event_description');
2993      }
2994  }
2995  
2996  class restore_course_completion_structure_step extends restore_structure_step {
2997  
2998      /**
2999       * Conditionally decide if this step should be executed.
3000       *
3001       * This function checks parameters that are not immediate settings to ensure
3002       * that the enviroment is suitable for the restore of course completion info.
3003       *
3004       * This function checks the following four parameters:
3005       *
3006       *   1. Course completion is enabled on the site
3007       *   2. The backup includes course completion information
3008       *   3. All modules are restorable
3009       *   4. All modules are marked for restore.
3010       *   5. No completion criteria already exist for the course.
3011       *
3012       * @return bool True is safe to execute, false otherwise
3013       */
3014      protected function execute_condition() {
3015          global $CFG, $DB;
3016  
3017          // First check course completion is enabled on this site
3018          if (empty($CFG->enablecompletion)) {
3019              // Disabled, don't restore course completion
3020              return false;
3021          }
3022  
3023          // No course completion on the front page.
3024          if ($this->get_courseid() == SITEID) {
3025              return false;
3026          }
3027  
3028          // Check it is included in the backup
3029          $fullpath = $this->task->get_taskbasepath();
3030          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3031          if (!file_exists($fullpath)) {
3032              // Not found, can't restore course completion
3033              return false;
3034          }
3035  
3036          // Check we are able to restore all backed up modules
3037          if ($this->task->is_missing_modules()) {
3038              return false;
3039          }
3040  
3041          // Check all modules within the backup are being restored.
3042          if ($this->task->is_excluding_activities()) {
3043              return false;
3044          }
3045  
3046          // Check that no completion criteria is already set for the course.
3047          if ($DB->record_exists('course_completion_criteria', array('course' => $this->get_courseid()))) {
3048              return false;
3049          }
3050  
3051          return true;
3052      }
3053  
3054      /**
3055       * Define the course completion structure
3056       *
3057       * @return array Array of restore_path_element
3058       */
3059      protected function define_structure() {
3060  
3061          // To know if we are including user completion info
3062          $userinfo = $this->get_setting_value('userscompletion');
3063  
3064          $paths = array();
3065          $paths[] = new restore_path_element('course_completion_criteria', '/course_completion/course_completion_criteria');
3066          $paths[] = new restore_path_element('course_completion_aggr_methd', '/course_completion/course_completion_aggr_methd');
3067  
3068          if ($userinfo) {
3069              $paths[] = new restore_path_element('course_completion_crit_compl', '/course_completion/course_completion_criteria/course_completion_crit_completions/course_completion_crit_compl');
3070              $paths[] = new restore_path_element('course_completions', '/course_completion/course_completions');
3071          }
3072  
3073          return $paths;
3074  
3075      }
3076  
3077      /**
3078       * Process course completion criteria
3079       *
3080       * @global moodle_database $DB
3081       * @param stdClass $data
3082       */
3083      public function process_course_completion_criteria($data) {
3084          global $DB;
3085  
3086          $data = (object)$data;
3087          $data->course = $this->get_courseid();
3088  
3089          // Apply the date offset to the time end field
3090          $data->timeend = $this->apply_date_offset($data->timeend);
3091  
3092          // Map the role from the criteria
3093          if (isset($data->role) && $data->role != '') {
3094              // Newer backups should include roleshortname, which makes this much easier.
3095              if (!empty($data->roleshortname)) {
3096                  $roleinstanceid = $DB->get_field('role', 'id', array('shortname' => $data->roleshortname));
3097                  if (!$roleinstanceid) {
3098                      $this->log(
3099                          'Could not match the role shortname in course_completion_criteria, so skipping',
3100                          backup::LOG_DEBUG
3101                      );
3102                      return;
3103                  }
3104                  $data->role = $roleinstanceid;
3105              } else {
3106                  $data->role = $this->get_mappingid('role', $data->role);
3107              }
3108  
3109              // Check we have an id, otherwise it causes all sorts of bugs.
3110              if (!$data->role) {
3111                  $this->log(
3112                      'Could not match role in course_completion_criteria, so skipping',
3113                      backup::LOG_DEBUG
3114                  );
3115                  return;
3116              }
3117          }
3118  
3119          // If the completion criteria is for a module we need to map the module instance
3120          // to the new module id.
3121          if (!empty($data->moduleinstance) && !empty($data->module)) {
3122              $data->moduleinstance = $this->get_mappingid('course_module', $data->moduleinstance);
3123              if (empty($data->moduleinstance)) {
3124                  $this->log(
3125                      'Could not match the module instance in course_completion_criteria, so skipping',
3126                      backup::LOG_DEBUG
3127                  );
3128                  return;
3129              }
3130          } else {
3131              $data->module = null;
3132              $data->moduleinstance = null;
3133          }
3134  
3135          // We backup the course shortname rather than the ID so that we can match back to the course
3136          if (!empty($data->courseinstanceshortname)) {
3137              $courseinstanceid = $DB->get_field('course', 'id', array('shortname'=>$data->courseinstanceshortname));
3138              if (!$courseinstanceid) {
3139                  $this->log(
3140                      'Could not match the course instance in course_completion_criteria, so skipping',
3141                      backup::LOG_DEBUG
3142                  );
3143                  return;
3144              }
3145          } else {
3146              $courseinstanceid = null;
3147          }
3148          $data->courseinstance = $courseinstanceid;
3149  
3150          $params = array(
3151              'course'         => $data->course,
3152              'criteriatype'   => $data->criteriatype,
3153              'enrolperiod'    => $data->enrolperiod,
3154              'courseinstance' => $data->courseinstance,
3155              'module'         => $data->module,
3156              'moduleinstance' => $data->moduleinstance,
3157              'timeend'        => $data->timeend,
3158              'gradepass'      => $data->gradepass,
3159              'role'           => $data->role
3160          );
3161          $newid = $DB->insert_record('course_completion_criteria', $params);
3162          $this->set_mapping('course_completion_criteria', $data->id, $newid);
3163      }
3164  
3165      /**
3166       * Processes course compltion criteria complete records
3167       *
3168       * @global moodle_database $DB
3169       * @param stdClass $data
3170       */
3171      public function process_course_completion_crit_compl($data) {
3172          global $DB;
3173  
3174          $data = (object)$data;
3175  
3176          // This may be empty if criteria could not be restored
3177          $data->criteriaid = $this->get_mappingid('course_completion_criteria', $data->criteriaid);
3178  
3179          $data->course = $this->get_courseid();
3180          $data->userid = $this->get_mappingid('user', $data->userid);
3181  
3182          if (!empty($data->criteriaid) && !empty($data->userid)) {
3183              $params = array(
3184                  'userid' => $data->userid,
3185                  'course' => $data->course,
3186                  'criteriaid' => $data->criteriaid,
3187                  'timecompleted' => $data->timecompleted
3188              );
3189              if (isset($data->gradefinal)) {
3190                  $params['gradefinal'] = $data->gradefinal;
3191              }
3192              if (isset($data->unenroled)) {
3193                  $params['unenroled'] = $data->unenroled;
3194              }
3195              $DB->insert_record('course_completion_crit_compl', $params);
3196          }
3197      }
3198  
3199      /**
3200       * Process course completions
3201       *
3202       * @global moodle_database $DB
3203       * @param stdClass $data
3204       */
3205      public function process_course_completions($data) {
3206          global $DB;
3207  
3208          $data = (object)$data;
3209  
3210          $data->course = $this->get_courseid();
3211          $data->userid = $this->get_mappingid('user', $data->userid);
3212  
3213          if (!empty($data->userid)) {
3214              $params = array(
3215                  'userid' => $data->userid,
3216                  'course' => $data->course,
3217                  'timeenrolled' => $data->timeenrolled,
3218                  'timestarted' => $data->timestarted,
3219                  'timecompleted' => $data->timecompleted,
3220                  'reaggregate' => $data->reaggregate
3221              );
3222  
3223              $existing = $DB->get_record('course_completions', array(
3224                  'userid' => $data->userid,
3225                  'course' => $data->course
3226              ));
3227  
3228              // MDL-46651 - If cron writes out a new record before we get to it
3229              // then we should replace it with the Truth data from the backup.
3230              // This may be obsolete after MDL-48518 is resolved
3231              if ($existing) {
3232                  $params['id'] = $existing->id;
3233                  $DB->update_record('course_completions', $params);
3234              } else {
3235                  $DB->insert_record('course_completions', $params);
3236              }
3237          }
3238      }
3239  
3240      /**
3241       * Process course completion aggregate methods
3242       *
3243       * @global moodle_database $DB
3244       * @param stdClass $data
3245       */
3246      public function process_course_completion_aggr_methd($data) {
3247          global $DB;
3248  
3249          $data = (object)$data;
3250  
3251          $data->course = $this->get_courseid();
3252  
3253          // Only create the course_completion_aggr_methd records if
3254          // the target course has not them defined. MDL-28180
3255          if (!$DB->record_exists('course_completion_aggr_methd', array(
3256                      'course' => $data->course,
3257                      'criteriatype' => $data->criteriatype))) {
3258              $params = array(
3259                  'course' => $data->course,
3260                  'criteriatype' => $data->criteriatype,
3261                  'method' => $data->method,
3262                  'value' => $data->value,
3263              );
3264              $DB->insert_record('course_completion_aggr_methd', $params);
3265          }
3266      }
3267  }
3268  
3269  
3270  /**
3271   * This structure step restores course logs (cmid = 0), delegating
3272   * the hard work to the corresponding {@link restore_logs_processor} passing the
3273   * collection of {@link restore_log_rule} rules to be observed as they are defined
3274   * by the task. Note this is only executed based in the 'logs' setting.
3275   *
3276   * NOTE: This is executed by final task, to have all the activities already restored
3277   *
3278   * NOTE: Not all course logs are being restored. For now only 'course' and 'user'
3279   * records are. There are others like 'calendar' and 'upload' that will be handled
3280   * later.
3281   *
3282   * NOTE: All the missing actions (not able to be restored) are sent to logs for
3283   * debugging purposes
3284   */
3285  class restore_course_logs_structure_step extends restore_structure_step {
3286  
3287      /**
3288       * Conditionally decide if this step should be executed.
3289       *
3290       * This function checks the following parameter:
3291       *
3292       *   1. the course/logs.xml file exists
3293       *
3294       * @return bool true is safe to execute, false otherwise
3295       */
3296      protected function execute_condition() {
3297  
3298          // Check it is included in the backup
3299          $fullpath = $this->task->get_taskbasepath();
3300          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3301          if (!file_exists($fullpath)) {
3302              // Not found, can't restore course logs
3303              return false;
3304          }
3305  
3306          return true;
3307      }
3308  
3309      protected function define_structure() {
3310  
3311          $paths = array();
3312  
3313          // Simple, one plain level of information contains them
3314          $paths[] = new restore_path_element('log', '/logs/log');
3315  
3316          return $paths;
3317      }
3318  
3319      protected function process_log($data) {
3320          global $DB;
3321  
3322          $data = (object)($data);
3323  
3324          // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3325  
3326          $data->userid = $this->get_mappingid('user', $data->userid);
3327          $data->course = $this->get_courseid();
3328          $data->cmid = 0;
3329  
3330          // For any reason user wasn't remapped ok, stop processing this
3331          if (empty($data->userid)) {
3332              return;
3333          }
3334  
3335          // Everything ready, let's delegate to the restore_logs_processor
3336  
3337          // Set some fixed values that will save tons of DB requests
3338          $values = array(
3339              'course' => $this->get_courseid());
3340          // Get instance and process log record
3341          $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3342  
3343          // If we have data, insert it, else something went wrong in the restore_logs_processor
3344          if ($data) {
3345              if (empty($data->url)) {
3346                  $data->url = '';
3347              }
3348              if (empty($data->info)) {
3349                  $data->info = '';
3350              }
3351              // Store the data in the legacy log table if we are still using it.
3352              $manager = get_log_manager();
3353              if (method_exists($manager, 'legacy_add_to_log')) {
3354                  $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3355                      $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3356              }
3357          }
3358      }
3359  }
3360  
3361  /**
3362   * This structure step restores activity logs, extending {@link restore_course_logs_structure_step}
3363   * sharing its same structure but modifying the way records are handled
3364   */
3365  class restore_activity_logs_structure_step extends restore_course_logs_structure_step {
3366  
3367      protected function process_log($data) {
3368          global $DB;
3369  
3370          $data = (object)($data);
3371  
3372          // There is no need to roll dates. Logs are supposed to be immutable. See MDL-44961.
3373  
3374          $data->userid = $this->get_mappingid('user', $data->userid);
3375          $data->course = $this->get_courseid();
3376          $data->cmid = $this->task->get_moduleid();
3377  
3378          // For any reason user wasn't remapped ok, stop processing this
3379          if (empty($data->userid)) {
3380              return;
3381          }
3382  
3383          // Everything ready, let's delegate to the restore_logs_processor
3384  
3385          // Set some fixed values that will save tons of DB requests
3386          $values = array(
3387              'course' => $this->get_courseid(),
3388              'course_module' => $this->task->get_moduleid(),
3389              $this->task->get_modulename() => $this->task->get_activityid());
3390          // Get instance and process log record
3391          $data = restore_logs_processor::get_instance($this->task, $values)->process_log_record($data);
3392  
3393          // If we have data, insert it, else something went wrong in the restore_logs_processor
3394          if ($data) {
3395              if (empty($data->url)) {
3396                  $data->url = '';
3397              }
3398              if (empty($data->info)) {
3399                  $data->info = '';
3400              }
3401              // Store the data in the legacy log table if we are still using it.
3402              $manager = get_log_manager();
3403              if (method_exists($manager, 'legacy_add_to_log')) {
3404                  $manager->legacy_add_to_log($data->course, $data->module, $data->action, $data->url,
3405                      $data->info, $data->cmid, $data->userid, $data->ip, $data->time);
3406              }
3407          }
3408      }
3409  }
3410  
3411  /**
3412   * Structure step in charge of restoring the logstores.xml file for the course logs.
3413   *
3414   * This restore step will rebuild the logs for all the enabled logstore subplugins supporting
3415   * it, for logs belonging to the course level.
3416   */
3417  class restore_course_logstores_structure_step extends restore_structure_step {
3418  
3419      /**
3420       * Conditionally decide if this step should be executed.
3421       *
3422       * This function checks the following parameter:
3423       *
3424       *   1. the logstores.xml file exists
3425       *
3426       * @return bool true is safe to execute, false otherwise
3427       */
3428      protected function execute_condition() {
3429  
3430          // Check it is included in the backup.
3431          $fullpath = $this->task->get_taskbasepath();
3432          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3433          if (!file_exists($fullpath)) {
3434              // Not found, can't restore logstores.xml information.
3435              return false;
3436          }
3437  
3438          return true;
3439      }
3440  
3441      /**
3442       * Return the elements to be processed on restore of logstores.
3443       *
3444       * @return restore_path_element[] array of elements to be processed on restore.
3445       */
3446      protected function define_structure() {
3447  
3448          $paths = array();
3449  
3450          $logstore = new restore_path_element('logstore', '/logstores/logstore');
3451          $paths[] = $logstore;
3452  
3453          // Add logstore subplugin support to the 'logstore' element.
3454          $this->add_subplugin_structure('logstore', $logstore, 'tool', 'log');
3455  
3456          return array($logstore);
3457      }
3458  
3459      /**
3460       * Process the 'logstore' element,
3461       *
3462       * Note: This is empty by definition in backup, because stores do not share any
3463       * data between them, so there is nothing to process here.
3464       *
3465       * @param array $data element data
3466       */
3467      protected function process_logstore($data) {
3468          return;
3469      }
3470  }
3471  
3472  /**
3473   * Structure step in charge of restoring the loglastaccess.xml file for the course logs.
3474   *
3475   * This restore step will rebuild the table for user_lastaccess table.
3476   */
3477  class restore_course_loglastaccess_structure_step extends restore_structure_step {
3478  
3479      /**
3480       * Conditionally decide if this step should be executed.
3481       *
3482       * This function checks the following parameter:
3483       *
3484       *   1. the loglastaccess.xml file exists
3485       *
3486       * @return bool true is safe to execute, false otherwise
3487       */
3488      protected function execute_condition() {
3489          // Check it is included in the backup.
3490          $fullpath = $this->task->get_taskbasepath();
3491          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3492          if (!file_exists($fullpath)) {
3493              // Not found, can't restore loglastaccess.xml information.
3494              return false;
3495          }
3496  
3497          return true;
3498      }
3499  
3500      /**
3501       * Return the elements to be processed on restore of loglastaccess.
3502       *
3503       * @return restore_path_element[] array of elements to be processed on restore.
3504       */
3505      protected function define_structure() {
3506  
3507          $paths = array();
3508          // To know if we are including userinfo.
3509          $userinfo = $this->get_setting_value('users');
3510  
3511          if ($userinfo) {
3512              $paths[] = new restore_path_element('lastaccess', '/lastaccesses/lastaccess');
3513          }
3514          // Return the paths wrapped.
3515          return $paths;
3516      }
3517  
3518      /**
3519       * Process the 'lastaccess' elements.
3520       *
3521       * @param array $data element data
3522       */
3523      protected function process_lastaccess($data) {
3524          global $DB;
3525  
3526          $data = (object)$data;
3527  
3528          $data->courseid = $this->get_courseid();
3529          if (!$data->userid = $this->get_mappingid('user', $data->userid)) {
3530              return; // Nothing to do, not able to find the user to set the lastaccess time.
3531          }
3532  
3533          // Check if record does exist.
3534          $exists = $DB->get_record('user_lastaccess', array('courseid' => $data->courseid, 'userid' => $data->userid));
3535          if ($exists) {
3536              // If the time of last access of the restore is newer, then replace and update.
3537              if ($exists->timeaccess < $data->timeaccess) {
3538                  $exists->timeaccess = $data->timeaccess;
3539                  $DB->update_record('user_lastaccess', $exists);
3540              }
3541          } else {
3542              $DB->insert_record('user_lastaccess', $data);
3543          }
3544      }
3545  }
3546  
3547  /**
3548   * Structure step in charge of restoring the logstores.xml file for the activity logs.
3549   *
3550   * Note: Activity structure is completely equivalent to the course one, so just extend it.
3551   */
3552  class restore_activity_logstores_structure_step extends restore_course_logstores_structure_step {
3553  }
3554  
3555  /**
3556   * Restore course competencies structure step.
3557   */
3558  class restore_course_competencies_structure_step extends restore_structure_step {
3559  
3560      /**
3561       * Returns the structure.
3562       *
3563       * @return array
3564       */
3565      protected function define_structure() {
3566          $userinfo = $this->get_setting_value('users');
3567          $paths = array(
3568              new restore_path_element('course_competency', '/course_competencies/competencies/competency'),
3569              new restore_path_element('course_competency_settings', '/course_competencies/settings'),
3570          );
3571          if ($userinfo) {
3572              $paths[] = new restore_path_element('user_competency_course',
3573                  '/course_competencies/user_competencies/user_competency');
3574          }
3575          return $paths;
3576      }
3577  
3578      /**
3579       * Process a course competency settings.
3580       *
3581       * @param array $data The data.
3582       */
3583      public function process_course_competency_settings($data) {
3584          global $DB;
3585          $data = (object) $data;
3586  
3587          // We do not restore the course settings during merge.
3588          $target = $this->get_task()->get_target();
3589          if ($target == backup::TARGET_CURRENT_ADDING || $target == backup::TARGET_EXISTING_ADDING) {
3590              return;
3591          }
3592  
3593          $courseid = $this->task->get_courseid();
3594          $exists = \core_competency\course_competency_settings::record_exists_select('courseid = :courseid',
3595              array('courseid' => $courseid));
3596  
3597          // Strangely the course settings already exist, let's just leave them as is then.
3598          if ($exists) {
3599              $this->log('Course competency settings not restored, existing settings have been found.', backup::LOG_WARNING);
3600              return;
3601          }
3602  
3603          $data = (object) array('courseid' => $courseid, 'pushratingstouserplans' => $data->pushratingstouserplans);
3604          $settings = new \core_competency\course_competency_settings(0, $data);
3605          $settings->create();
3606      }
3607  
3608      /**
3609       * Process a course competency.
3610       *
3611       * @param array $data The data.
3612       */
3613      public function process_course_competency($data) {
3614          $data = (object) $data;
3615  
3616          // Mapping the competency by ID numbers.
3617          $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3618          if (!$framework) {
3619              return;
3620          }
3621          $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3622              'competencyframeworkid' => $framework->get('id')));
3623          if (!$competency) {
3624              return;
3625          }
3626          $this->set_mapping(\core_competency\competency::TABLE, $data->id, $competency->get('id'));
3627  
3628          $params = array(
3629              'competencyid' => $competency->get('id'),
3630              'courseid' => $this->task->get_courseid()
3631          );
3632          $query = 'competencyid = :competencyid AND courseid = :courseid';
3633          $existing = \core_competency\course_competency::record_exists_select($query, $params);
3634  
3635          if (!$existing) {
3636              // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3637              $record = (object) $params;
3638              $record->ruleoutcome = $data->ruleoutcome;
3639              $coursecompetency = new \core_competency\course_competency(0, $record);
3640              $coursecompetency->create();
3641          }
3642      }
3643  
3644      /**
3645       * Process the user competency course.
3646       *
3647       * @param array $data The data.
3648       */
3649      public function process_user_competency_course($data) {
3650          global $USER, $DB;
3651          $data = (object) $data;
3652  
3653          $data->competencyid = $this->get_mappingid(\core_competency\competency::TABLE, $data->competencyid);
3654          if (!$data->competencyid) {
3655              // This is strange, the competency does not belong to the course.
3656              return;
3657          } else if ($data->grade === null) {
3658              // We do not need to do anything when there is no grade.
3659              return;
3660          }
3661  
3662          $data->userid = $this->get_mappingid('user', $data->userid);
3663          $shortname = $DB->get_field('course', 'shortname', array('id' => $this->task->get_courseid()), MUST_EXIST);
3664  
3665          // The method add_evidence also sets the course rating.
3666          \core_competency\api::add_evidence($data->userid,
3667                                             $data->competencyid,
3668                                             $this->task->get_contextid(),
3669                                             \core_competency\evidence::ACTION_OVERRIDE,
3670                                             'evidence_courserestored',
3671                                             'core_competency',
3672                                             $shortname,
3673                                             false,
3674                                             null,
3675                                             $data->grade,
3676                                             $USER->id);
3677      }
3678  
3679      /**
3680       * Execute conditions.
3681       *
3682       * @return bool
3683       */
3684      protected function execute_condition() {
3685  
3686          // Do not execute if competencies are not included.
3687          if (!$this->get_setting_value('competencies')) {
3688              return false;
3689          }
3690  
3691          // Do not execute if the competencies XML file is not found.
3692          $fullpath = $this->task->get_taskbasepath();
3693          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3694          if (!file_exists($fullpath)) {
3695              return false;
3696          }
3697  
3698          return true;
3699      }
3700  }
3701  
3702  /**
3703   * Restore activity competencies structure step.
3704   */
3705  class restore_activity_competencies_structure_step extends restore_structure_step {
3706  
3707      /**
3708       * Defines the structure.
3709       *
3710       * @return array
3711       */
3712      protected function define_structure() {
3713          $paths = array(
3714              new restore_path_element('course_module_competency', '/course_module_competencies/competencies/competency')
3715          );
3716          return $paths;
3717      }
3718  
3719      /**
3720       * Process a course module competency.
3721       *
3722       * @param array $data The data.
3723       */
3724      public function process_course_module_competency($data) {
3725          $data = (object) $data;
3726  
3727          // Mapping the competency by ID numbers.
3728          $framework = \core_competency\competency_framework::get_record(array('idnumber' => $data->frameworkidnumber));
3729          if (!$framework) {
3730              return;
3731          }
3732          $competency = \core_competency\competency::get_record(array('idnumber' => $data->idnumber,
3733              'competencyframeworkid' => $framework->get('id')));
3734          if (!$competency) {
3735              return;
3736          }
3737  
3738          $params = array(
3739              'competencyid' => $competency->get('id'),
3740              'cmid' => $this->task->get_moduleid()
3741          );
3742          $query = 'competencyid = :competencyid AND cmid = :cmid';
3743          $existing = \core_competency\course_module_competency::record_exists_select($query, $params);
3744  
3745          if (!$existing) {
3746              // Sortorder is ignored by precaution, anyway we should walk through the records in the right order.
3747              $record = (object) $params;
3748              $record->ruleoutcome = $data->ruleoutcome;
3749              $coursemodulecompetency = new \core_competency\course_module_competency(0, $record);
3750              $coursemodulecompetency->create();
3751          }
3752      }
3753  
3754      /**
3755       * Execute conditions.
3756       *
3757       * @return bool
3758       */
3759      protected function execute_condition() {
3760  
3761          // Do not execute if competencies are not included.
3762          if (!$this->get_setting_value('competencies')) {
3763              return false;
3764          }
3765  
3766          // Do not execute if the competencies XML file is not found.
3767          $fullpath = $this->task->get_taskbasepath();
3768          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3769          if (!file_exists($fullpath)) {
3770              return false;
3771          }
3772  
3773          return true;
3774      }
3775  }
3776  
3777  /**
3778   * Defines the restore step for advanced grading methods attached to the activity module
3779   */
3780  class restore_activity_grading_structure_step extends restore_structure_step {
3781  
3782      /**
3783       * This step is executed only if the grading file is present
3784       */
3785       protected function execute_condition() {
3786  
3787          if ($this->get_courseid() == SITEID) {
3788              return false;
3789          }
3790  
3791          $fullpath = $this->task->get_taskbasepath();
3792          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3793          if (!file_exists($fullpath)) {
3794              return false;
3795          }
3796  
3797          return true;
3798      }
3799  
3800  
3801      /**
3802       * Declares paths in the grading.xml file we are interested in
3803       */
3804      protected function define_structure() {
3805  
3806          $paths = array();
3807          $userinfo = $this->get_setting_value('userinfo');
3808  
3809          $area = new restore_path_element('grading_area', '/areas/area');
3810          $paths[] = $area;
3811          // attach local plugin stucture to $area element
3812          $this->add_plugin_structure('local', $area);
3813  
3814          $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3815          $paths[] = $definition;
3816          $this->add_plugin_structure('gradingform', $definition);
3817          // attach local plugin stucture to $definition element
3818          $this->add_plugin_structure('local', $definition);
3819  
3820  
3821          if ($userinfo) {
3822              $instance = new restore_path_element('grading_instance',
3823                  '/areas/area/definitions/definition/instances/instance');
3824              $paths[] = $instance;
3825              $this->add_plugin_structure('gradingform', $instance);
3826              // attach local plugin stucture to $intance element
3827              $this->add_plugin_structure('local', $instance);
3828          }
3829  
3830          return $paths;
3831      }
3832  
3833      /**
3834       * Processes one grading area element
3835       *
3836       * @param array $data element data
3837       */
3838      protected function process_grading_area($data) {
3839          global $DB;
3840  
3841          $task = $this->get_task();
3842          $data = (object)$data;
3843          $oldid = $data->id;
3844          $data->component = 'mod_'.$task->get_modulename();
3845          $data->contextid = $task->get_contextid();
3846  
3847          $newid = $DB->insert_record('grading_areas', $data);
3848          $this->set_mapping('grading_area', $oldid, $newid);
3849      }
3850  
3851      /**
3852       * Processes one grading definition element
3853       *
3854       * @param array $data element data
3855       */
3856      protected function process_grading_definition($data) {
3857          global $DB;
3858  
3859          $task = $this->get_task();
3860          $data = (object)$data;
3861          $oldid = $data->id;
3862          $data->areaid = $this->get_new_parentid('grading_area');
3863          $data->copiedfromid = null;
3864          $data->timecreated = time();
3865          $data->usercreated = $task->get_userid();
3866          $data->timemodified = $data->timecreated;
3867          $data->usermodified = $data->usercreated;
3868  
3869          $newid = $DB->insert_record('grading_definitions', $data);
3870          $this->set_mapping('grading_definition', $oldid, $newid, true);
3871      }
3872  
3873      /**
3874       * Processes one grading form instance element
3875       *
3876       * @param array $data element data
3877       */
3878      protected function process_grading_instance($data) {
3879          global $DB;
3880  
3881          $data = (object)$data;
3882  
3883          // new form definition id
3884          $newformid = $this->get_new_parentid('grading_definition');
3885  
3886          // get the name of the area we are restoring to
3887          $sql = "SELECT ga.areaname
3888                    FROM {grading_definitions} gd
3889                    JOIN {grading_areas} ga ON gd.areaid = ga.id
3890                   WHERE gd.id = ?";
3891          $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3892  
3893          // get the mapped itemid - the activity module is expected to define the mappings
3894          // for each gradable area
3895          $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3896  
3897          $oldid = $data->id;
3898          $data->definitionid = $newformid;
3899          $data->raterid = $this->get_mappingid('user', $data->raterid);
3900          $data->itemid = $newitemid;
3901  
3902          $newid = $DB->insert_record('grading_instances', $data);
3903          $this->set_mapping('grading_instance', $oldid, $newid);
3904      }
3905  
3906      /**
3907       * Final operations when the database records are inserted
3908       */
3909      protected function after_execute() {
3910          // Add files embedded into the definition description
3911          $this->add_related_files('grading', 'description', 'grading_definition');
3912      }
3913  }
3914  
3915  
3916  /**
3917   * This structure step restores the grade items associated with one activity
3918   * All the grade items are made child of the "course" grade item but the original
3919   * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3920   * the complete gradebook (categories and calculations), that information is
3921   * available there
3922   */
3923  class restore_activity_grades_structure_step extends restore_structure_step {
3924  
3925      /**
3926       * No grades in front page.
3927       * @return bool
3928       */
3929      protected function execute_condition() {
3930          return ($this->get_courseid() != SITEID);
3931      }
3932  
3933      protected function define_structure() {
3934  
3935          $paths = array();
3936          $userinfo = $this->get_setting_value('userinfo');
3937  
3938          $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3939          $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3940          if ($userinfo) {
3941              $paths[] = new restore_path_element('grade_grade',
3942                             '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3943          }
3944          return $paths;
3945      }
3946  
3947      protected function process_grade_item($data) {
3948          global $DB;
3949  
3950          $data = (object)($data);
3951          $oldid       = $data->id;        // We'll need these later
3952          $oldparentid = $data->categoryid;
3953          $courseid = $this->get_courseid();
3954  
3955          $idnumber = null;
3956          if (!empty($data->idnumber)) {
3957              // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
3958              // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
3959              // so the best is to keep the ones already in the gradebook
3960              // Potential problem: duplicates if same items are restored more than once. :-(
3961              // This needs to be fixed in some way (outcomes & activities with multiple items)
3962              // $data->idnumber     = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
3963              // In any case, verify always for uniqueness
3964              $sql = "SELECT cm.id
3965                        FROM {course_modules} cm
3966                       WHERE cm.course = :courseid AND
3967                             cm.idnumber = :idnumber AND
3968                             cm.id <> :cmid";
3969              $params = array(
3970                  'courseid' => $courseid,
3971                  'idnumber' => $data->idnumber,
3972                  'cmid' => $this->task->get_moduleid()
3973              );
3974              if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
3975                  $idnumber = $data->idnumber;
3976              }
3977          }
3978  
3979          if (!empty($data->categoryid)) {
3980              // If the grade category id of the grade item being restored belongs to this course
3981              // then it is a fair assumption that this is the correct grade category for the activity
3982              // and we should leave it in place, if not then unset it.
3983              // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
3984              $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
3985              if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
3986                  unset($data->categoryid);
3987              }
3988          }
3989  
3990          unset($data->id);
3991          $data->courseid     = $this->get_courseid();
3992          $data->iteminstance = $this->task->get_activityid();
3993          $data->idnumber     = $idnumber;
3994          $data->scaleid      = $this->get_mappingid('scale', $data->scaleid);
3995          $data->outcomeid    = $this->get_mappingid('outcome', $data->outcomeid);
3996  
3997          $gradeitem = new grade_item($data, false);
3998          $gradeitem->insert('restore');
3999  
4000          //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
4001          $gradeitem->sortorder = $data->sortorder;
4002          $gradeitem->update('restore');
4003  
4004          // Set mapping, saving the original category id into parentitemid
4005          // gradebook restore (final task) will need it to reorganise items
4006          $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
4007      }
4008  
4009      protected function process_grade_grade($data) {
4010          global $CFG;
4011  
4012          require_once($CFG->libdir . '/grade/constants.php');
4013  
4014          $data = (object)($data);
4015          $olduserid = $data->userid;
4016          $oldid = $data->id;
4017          unset($data->id);
4018  
4019          $data->itemid = $this->get_new_parentid('grade_item');
4020  
4021          $data->userid = $this->get_mappingid('user', $data->userid, null);
4022          if (!empty($data->userid)) {
4023              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4024              $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4025  
4026              $grade = new grade_grade($data, false);
4027              $grade->insert('restore');
4028  
4029              $this->set_mapping('grade_grades', $oldid, $grade->id, true);
4030  
4031              $this->add_related_files(
4032                  GRADE_FILE_COMPONENT,
4033                  GRADE_FEEDBACK_FILEAREA,
4034                  'grade_grades',
4035                  null,
4036                  $oldid
4037              );
4038          } else {
4039              debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
4040          }
4041      }
4042  
4043      /**
4044       * process activity grade_letters. Note that, while these are possible,
4045       * because grade_letters are contextid based, in practice, only course
4046       * context letters can be defined. So we keep here this method knowing
4047       * it won't be executed ever. gradebook restore will restore course letters.
4048       */
4049      protected function process_grade_letter($data) {
4050          global $DB;
4051  
4052          $data['contextid'] = $this->task->get_contextid();
4053          $gradeletter = (object)$data;
4054  
4055          // Check if it exists before adding it
4056          unset($data['id']);
4057          if (!$DB->record_exists('grade_letters', $data)) {
4058              $newitemid = $DB->insert_record('grade_letters', $gradeletter);
4059          }
4060          // no need to save any grade_letter mapping
4061      }
4062  
4063      public function after_restore() {
4064          // Fix grade item's sortorder after restore, as it might have duplicates.
4065          $courseid = $this->get_task()->get_courseid();
4066          grade_item::fix_duplicate_sortorder($courseid);
4067      }
4068  }
4069  
4070  /**
4071   * Step in charge of restoring the grade history of an activity.
4072   *
4073   * This step is added to the task regardless of the setting 'grade_histories'.
4074   * The reason is to allow for a more flexible step in case the logic needs to be
4075   * split accross different settings to control the history of items and/or grades.
4076   */
4077  class restore_activity_grade_history_structure_step extends restore_structure_step {
4078  
4079      /**
4080       * This step is executed only if the grade history file is present.
4081       */
4082       protected function execute_condition() {
4083  
4084          if ($this->get_courseid() == SITEID) {
4085              return false;
4086          }
4087  
4088          $fullpath = $this->task->get_taskbasepath();
4089          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4090          if (!file_exists($fullpath)) {
4091              return false;
4092          }
4093          return true;
4094      }
4095  
4096      protected function define_structure() {
4097          $paths = array();
4098  
4099          // Settings to use.
4100          $userinfo = $this->get_setting_value('userinfo');
4101          $history = $this->get_setting_value('grade_histories');
4102  
4103          if ($userinfo && $history) {
4104              $paths[] = new restore_path_element('grade_grade',
4105                 '/grade_history/grade_grades/grade_grade');
4106          }
4107  
4108          return $paths;
4109      }
4110  
4111      protected function process_grade_grade($data) {
4112          global $CFG, $DB;
4113  
4114          require_once($CFG->libdir . '/grade/constants.php');
4115  
4116          $data = (object) $data;
4117          $oldhistoryid = $data->id;
4118          $olduserid = $data->userid;
4119          unset($data->id);
4120  
4121          $data->userid = $this->get_mappingid('user', $data->userid, null);
4122          if (!empty($data->userid)) {
4123              // Do not apply the date offsets as this is history.
4124              $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
4125              $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
4126              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4127              $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4128  
4129              $newhistoryid = $DB->insert_record('grade_grades_history', $data);
4130  
4131              $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
4132  
4133              $this->add_related_files(
4134                  GRADE_FILE_COMPONENT,
4135                  GRADE_HISTORY_FEEDBACK_FILEAREA,
4136                  'grade_grades_history',
4137                  null,
4138                  $oldhistoryid
4139              );
4140          } else {
4141              $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
4142              $this->log($message, backup::LOG_DEBUG);
4143          }
4144      }
4145  }
4146  
4147  /**
4148   * This structure steps restores the content bank content
4149   */
4150  class restore_contentbankcontent_structure_step extends restore_structure_step {
4151  
4152      /**
4153       * Define structure for content bank step
4154       */
4155      protected function define_structure() {
4156  
4157          $paths = [];
4158          $paths[] = new restore_path_element('contentbankcontent', '/contents/content');
4159  
4160          return $paths;
4161      }
4162  
4163      /**
4164       * Define data processed for content bank
4165       *
4166       * @param mixed  $data
4167       */
4168      public function process_contentbankcontent($data) {
4169          global $DB;
4170  
4171          $data = (object)$data;
4172          $oldid = $data->id;
4173  
4174          $params = [
4175              'name'           => $data->name,
4176              'contextid'      => $this->task->get_contextid(),
4177              'contenttype'    => $data->contenttype,
4178              'instanceid'     => $data->instanceid,
4179              'timecreated'    => $data->timecreated,
4180          ];
4181          $exists = $DB->record_exists('contentbank_content', $params);
4182          if (!$exists) {
4183              $params['configdata'] = $data->configdata;
4184              $params['timemodified'] = time();
4185  
4186              // Trying to map users. Users cannot always be mapped, e.g. when copying.
4187              $params['usercreated'] = $this->get_mappingid('user', $data->usercreated);
4188              if (!$params['usercreated']) {
4189                  // Leave the content creator unchanged when we are restoring the same site.
4190                  // Otherwise use current user id.
4191                  if ($this->task->is_samesite()) {
4192                      $params['usercreated'] = $data->usercreated;
4193                  } else {
4194                      $params['usercreated'] = $this->task->get_userid();
4195                  }
4196              }
4197              $params['usermodified'] = $this->get_mappingid('user', $data->usermodified);
4198              if (!$params['usermodified']) {
4199                  // Leave the content modifier unchanged when we are restoring the same site.
4200                  // Otherwise use current user id.
4201                  if ($this->task->is_samesite()) {
4202                      $params['usermodified'] = $data->usermodified;
4203                  } else {
4204                      $params['usermodified'] = $this->task->get_userid();
4205                  }
4206              }
4207  
4208              $newitemid = $DB->insert_record('contentbank_content', $params);
4209              $this->set_mapping('contentbank_content', $oldid, $newitemid, true);
4210          }
4211      }
4212  
4213      /**
4214       * Define data processed after execute for content bank
4215       */
4216      protected function after_execute() {
4217          // Add related files.
4218          $this->add_related_files('contentbank', 'public', 'contentbank_content');
4219      }
4220  }
4221  
4222  /**
4223   * This structure steps restores one instance + positions of one block
4224   * Note: Positions corresponding to one existing context are restored
4225   * here, but all the ones having unknown contexts are sent to backup_ids
4226   * for a later chance to be restored at the end (final task)
4227   */
4228  class restore_block_instance_structure_step extends restore_structure_step {
4229  
4230      protected function define_structure() {
4231  
4232          $paths = array();
4233  
4234          $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
4235          $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
4236  
4237          return $paths;
4238      }
4239  
4240      public function process_block($data) {
4241          global $DB, $CFG;
4242  
4243          $data = (object)$data; // Handy
4244          $oldcontextid = $data->contextid;
4245          $oldid        = $data->id;
4246          $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
4247  
4248          // Look for the parent contextid
4249          if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
4250              // Parent contextid does not exist, ignore this block.
4251              return false;
4252          }
4253  
4254          // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
4255          // If there is already one block of that type in the parent context
4256          // and the block is not multiple, stop processing
4257          // Use blockslib loader / method executor
4258          if (!$bi = block_instance($data->blockname)) {
4259              return false;
4260          }
4261  
4262          if (!$bi->instance_allow_multiple()) {
4263              // The block cannot be added twice, so we will check if the same block is already being
4264              // displayed on the same page. For this, rather than mocking a page and using the block_manager
4265              // we use a similar query to the one in block_manager::load_blocks(), this will give us
4266              // a very good idea of the blocks already displayed in the context.
4267              $params =  array(
4268                  'blockname' => $data->blockname
4269              );
4270  
4271              // Context matching test.
4272              $context = context::instance_by_id($data->parentcontextid);
4273              $contextsql = 'bi.parentcontextid = :contextid';
4274              $params['contextid'] = $context->id;
4275  
4276              $parentcontextids = $context->get_parent_context_ids();
4277              if ($parentcontextids) {
4278                  list($parentcontextsql, $parentcontextparams) =
4279                          $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
4280                  $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
4281                  $params = array_merge($params, $parentcontextparams);
4282              }
4283  
4284              // Page type pattern test.
4285              $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
4286              list($pagetypepatternsql, $pagetypepatternparams) =
4287                  $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
4288              $params = array_merge($params, $pagetypepatternparams);
4289  
4290              // Sub page pattern test.
4291              $subpagepatternsql = 'bi.subpagepattern IS NULL';
4292              if ($data->subpagepattern !== null) {
4293                  $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
4294                  $params['subpagepattern'] = $data->subpagepattern;
4295              }
4296  
4297              $existingblock = $DB->get_records_sql("SELECT bi.id
4298                                                  FROM {block_instances} bi
4299                                                  JOIN {block} b ON b.name = bi.blockname
4300                                                 WHERE bi.blockname = :blockname
4301                                                   AND $contextsql
4302                                                   AND bi.pagetypepattern $pagetypepatternsql
4303                                                   AND $subpagepatternsql", $params);
4304              if (!empty($existingblock)) {
4305                  // Save the context mapping in case something else is linking to this block's context.
4306                  $newcontext = context_block::instance(reset($existingblock)->id);
4307                  $this->set_mapping('context', $oldcontextid, $newcontext->id);
4308                  // There is at least one very similar block visible on the page where we
4309                  // are trying to restore the block. In these circumstances the block API
4310                  // would not allow the user to add another instance of the block, so we
4311                  // apply the same rule here.
4312                  return false;
4313              }
4314          }
4315  
4316          // If there is already one block of that type in the parent context
4317          // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
4318          // stop processing
4319          $params = array(
4320              'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
4321              'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
4322              'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
4323          if ($birecs = $DB->get_records('block_instances', $params)) {
4324              foreach($birecs as $birec) {
4325                  if ($birec->configdata == $data->configdata) {
4326                      // Save the context mapping in case something else is linking to this block's context.
4327                      $newcontext = context_block::instance($birec->id);
4328                      $this->set_mapping('context', $oldcontextid, $newcontext->id);
4329                      return false;
4330                  }
4331              }
4332          }
4333  
4334          // Set task old contextid, blockid and blockname once we know them
4335          $this->task->set_old_contextid($oldcontextid);
4336          $this->task->set_old_blockid($oldid);
4337          $this->task->set_blockname($data->blockname);
4338  
4339          // Let's look for anything within configdata neededing processing
4340          // (nulls and uses of legacy file.php)
4341          if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
4342              $configdata = array_filter(
4343                  (array) unserialize_object(base64_decode($data->configdata)),
4344                  static function($value): bool {
4345                      return !($value instanceof __PHP_Incomplete_Class);
4346                  }
4347              );
4348  
4349              foreach ($configdata as $attribute => $value) {
4350                  if (in_array($attribute, $attrstotransform)) {
4351                      $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
4352                  }
4353              }
4354              $data->configdata = base64_encode(serialize((object)$configdata));
4355          }
4356  
4357          // Set timecreated, timemodified if not included (older backup).
4358          if (empty($data->timecreated)) {
4359              $data->timecreated = time();
4360          }
4361          if (empty($data->timemodified)) {
4362              $data->timemodified = $data->timecreated;
4363          }
4364  
4365          // Create the block instance
4366          $newitemid = $DB->insert_record('block_instances', $data);
4367          // Save the mapping (with restorefiles support)
4368          $this->set_mapping('block_instance', $oldid, $newitemid, true);
4369          // Create the block context
4370          $newcontextid = context_block::instance($newitemid)->id;
4371          // Save the block contexts mapping and sent it to task
4372          $this->set_mapping('context', $oldcontextid, $newcontextid);
4373          $this->task->set_contextid($newcontextid);
4374          $this->task->set_blockid($newitemid);
4375  
4376          // Restore block fileareas if declared
4377          $component = 'block_' . $this->task->get_blockname();
4378          foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
4379              $this->add_related_files($component, $filearea, null);
4380          }
4381  
4382          // Process block positions, creating them or accumulating for final step
4383          foreach($positions as $position) {
4384              $position = (object)$position;
4385              $position->blockinstanceid = $newitemid; // The instance is always the restored one
4386              // If position is for one already mapped (known) contextid
4387              // process it now, creating the position
4388              if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
4389                  $position->contextid = $newpositionctxid;
4390                  // Create the block position
4391                  $DB->insert_record('block_positions', $position);
4392  
4393              // The position belongs to an unknown context, send it to backup_ids
4394              // to process them as part of the final steps of restore. We send the
4395              // whole $position object there, hence use the low level method.
4396              } else {
4397                  restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
4398              }
4399          }
4400      }
4401  }
4402  
4403  /**
4404   * Structure step to restore common course_module information
4405   *
4406   * This step will process the module.xml file for one activity, in order to restore
4407   * the corresponding information to the course_modules table, skipping various bits
4408   * of information based on CFG settings (groupings, completion...) in order to fullfill
4409   * all the reqs to be able to create the context to be used by all the rest of steps
4410   * in the activity restore task
4411   */
4412  class restore_module_structure_step extends restore_structure_step {
4413  
4414      protected function define_structure() {
4415          global $CFG;
4416  
4417          $paths = array();
4418  
4419          $module = new restore_path_element('module', '/module');
4420          $paths[] = $module;
4421          if ($CFG->enableavailability) {
4422              $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4423              $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4424          }
4425  
4426          $paths[] = new restore_path_element('tag', '/module/tags/tag');
4427  
4428          // Apply for 'format' plugins optional paths at module level
4429          $this->add_plugin_structure('format', $module);
4430  
4431          // Apply for 'report' plugins optional paths at module level.
4432          $this->add_plugin_structure('report', $module);
4433  
4434          // Apply for 'plagiarism' plugins optional paths at module level
4435          $this->add_plugin_structure('plagiarism', $module);
4436  
4437          // Apply for 'local' plugins optional paths at module level
4438          $this->add_plugin_structure('local', $module);
4439  
4440          // Apply for 'admin tool' plugins optional paths at module level.
4441          $this->add_plugin_structure('tool', $module);
4442  
4443          return $paths;
4444      }
4445  
4446      protected function process_module($data) {
4447          global $CFG, $DB;
4448  
4449          $data = (object)$data;
4450          $oldid = $data->id;
4451          $this->task->set_old_moduleversion($data->version);
4452  
4453          $data->course = $this->task->get_courseid();
4454          $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
4455          // Map section (first try by course_section mapping match. Useful in course and section restores)
4456          $data->section = $this->get_mappingid('course_section', $data->sectionid);
4457          if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
4458              $params = array(
4459                  'course' => $this->get_courseid(),
4460                  'section' => $data->sectionnumber);
4461              $data->section = $DB->get_field('course_sections', 'id', $params);
4462          }
4463          if (!$data->section) { // sectionnumber failed, try to get first section in course
4464              $params = array(
4465                  'course' => $this->get_courseid());
4466              $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
4467          }
4468          if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
4469              $sectionrec = array(
4470                  'course' => $this->get_courseid(),
4471                  'section' => 0,
4472                  'timemodified' => time());
4473              $DB->insert_record('course_sections', $sectionrec); // section 0
4474              $sectionrec = array(
4475                  'course' => $this->get_courseid(),
4476                  'section' => 1,
4477                  'timemodified' => time());
4478              $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
4479          }
4480          $data->groupingid= $this->get_mappingid('grouping', $data->groupingid);      // grouping
4481          if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) {        // idnumber uniqueness
4482              $data->idnumber = '';
4483          }
4484          if (empty($CFG->enablecompletion)) { // completion
4485              $data->completion = 0;
4486              $data->completiongradeitemnumber = null;
4487              $data->completionview = 0;
4488              $data->completionexpected = 0;
4489          } else {
4490              $data->completionexpected = $this->apply_date_offset($data->completionexpected);
4491          }
4492          if (empty($CFG->enableavailability)) {
4493              $data->availability = null;
4494          }
4495          // Backups that did not include showdescription, set it to default 0
4496          // (this is not totally necessary as it has a db default, but just to
4497          // be explicit).
4498          if (!isset($data->showdescription)) {
4499              $data->showdescription = 0;
4500          }
4501          $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
4502  
4503          if (empty($data->availability)) {
4504              // If there are legacy availablility data fields (and no new format data),
4505              // convert the old fields.
4506              $data->availability = \core_availability\info::convert_legacy_fields(
4507                      $data, false);
4508          } else if (!empty($data->groupmembersonly)) {
4509              // There is current availability data, but it still has groupmembersonly
4510              // as well (2.7 backups), convert just that part.
4511              require_once($CFG->dirroot . '/lib/db/upgradelib.php');
4512              $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
4513          }
4514  
4515          // course_module record ready, insert it
4516          $newitemid = $DB->insert_record('course_modules', $data);
4517          // save mapping
4518          $this->set_mapping('course_module', $oldid, $newitemid);
4519          // set the new course_module id in the task
4520          $this->task->set_moduleid($newitemid);
4521          // we can now create the context safely
4522          $ctxid = context_module::instance($newitemid)->id;
4523          // set the new context id in the task
4524          $this->task->set_contextid($ctxid);
4525          // update sequence field in course_section
4526          if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
4527              $sequence .= ',' . $newitemid;
4528          } else {
4529              $sequence = $newitemid;
4530          }
4531  
4532          $updatesection = new \stdClass();
4533          $updatesection->id = $data->section;
4534          $updatesection->sequence = $sequence;
4535          $updatesection->timemodified = time();
4536          $DB->update_record('course_sections', $updatesection);
4537  
4538          // If there is the legacy showavailability data, store this for later use.
4539          // (This data is not present when restoring 'new' backups.)
4540          if (isset($data->showavailability)) {
4541              // Cache the showavailability flag using the backup_ids data field.
4542              restore_dbops::set_backup_ids_record($this->get_restoreid(),
4543                      'module_showavailability', $newitemid, 0, null,
4544                      (object)array('showavailability' => $data->showavailability));
4545          }
4546      }
4547  
4548      /**
4549       * Fetch all the existing because tag_set() deletes them
4550       * so everything must be reinserted on each call.
4551       *
4552       * @param stdClass $data Record data
4553       */
4554      protected function process_tag($data) {
4555          global $CFG;
4556  
4557          $data = (object)$data;
4558  
4559          if (core_tag_tag::is_enabled('core', 'course_modules')) {
4560              $modcontext = context::instance_by_id($this->task->get_contextid());
4561              $instanceid = $this->task->get_moduleid();
4562  
4563              core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4564          }
4565      }
4566  
4567      /**
4568       * Process the legacy availability table record. This table does not exist
4569       * in Moodle 2.7+ but we still support restore.
4570       *
4571       * @param stdClass $data Record data
4572       */
4573      protected function process_availability($data) {
4574          $data = (object)$data;
4575          // Simply going to store the whole availability record now, we'll process
4576          // all them later in the final task (once all activities have been restored)
4577          // Let's call the low level one to be able to store the whole object
4578          $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
4579          restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
4580      }
4581  
4582      /**
4583       * Process the legacy availability fields table record. This table does not
4584       * exist in Moodle 2.7+ but we still support restore.
4585       *
4586       * @param stdClass $data Record data
4587       */
4588      protected function process_availability_field($data) {
4589          global $DB, $CFG;
4590          require_once($CFG->dirroot.'/user/profile/lib.php');
4591  
4592          $data = (object)$data;
4593          // Mark it is as passed by default
4594          $passed = true;
4595          $customfieldid = null;
4596  
4597          // If a customfield has been used in order to pass we must be able to match an existing
4598          // customfield by name (data->customfield) and type (data->customfieldtype)
4599          if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
4600              // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4601              // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4602              $passed = false;
4603          } else if (!empty($data->customfield)) {
4604              $field = profile_get_custom_field_data_by_shortname($data->customfield);
4605              $passed = $field && $field->datatype == $data->customfieldtype;
4606          }
4607  
4608          if ($passed) {
4609              // Create the object to insert into the database
4610              $availfield = new stdClass();
4611              $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
4612              $availfield->userfield = $data->userfield;
4613              $availfield->customfieldid = $customfieldid;
4614              $availfield->operator = $data->operator;
4615              $availfield->value = $data->value;
4616  
4617              // Get showavailability option.
4618              $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4619                      'module_showavailability', $availfield->coursemoduleid);
4620              if (!$showrec) {
4621                  // Should not happen.
4622                  throw new coding_exception('No matching showavailability record');
4623              }
4624              $show = $showrec->info->showavailability;
4625  
4626              // The $availfieldobject is now in the format used in the old
4627              // system. Interpret this and convert to new system.
4628              $currentvalue = $DB->get_field('course_modules', 'availability',
4629                      array('id' => $availfield->coursemoduleid), MUST_EXIST);
4630              $newvalue = \core_availability\info::add_legacy_availability_field_condition(
4631                      $currentvalue, $availfield, $show);
4632              $DB->set_field('course_modules', 'availability', $newvalue,
4633                      array('id' => $availfield->coursemoduleid));
4634          }
4635      }
4636      /**
4637       * This method will be executed after the rest of the restore has been processed.
4638       *
4639       * Update old tag instance itemid(s).
4640       */
4641      protected function after_restore() {
4642          global $DB;
4643  
4644          $contextid = $this->task->get_contextid();
4645          $instanceid = $this->task->get_activityid();
4646          $olditemid = $this->task->get_old_activityid();
4647  
4648          $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4649      }
4650  }
4651  
4652  /**
4653   * Structure step that will process the user activity completion
4654   * information if all these conditions are met:
4655   *  - Target site has completion enabled ($CFG->enablecompletion)
4656   *  - Activity includes completion info (file_exists)
4657   */
4658  class restore_userscompletion_structure_step extends restore_structure_step {
4659      /**
4660       * To conditionally decide if this step must be executed
4661       * Note the "settings" conditions are evaluated in the
4662       * corresponding task. Here we check for other conditions
4663       * not being restore settings (files, site settings...)
4664       */
4665       protected function execute_condition() {
4666           global $CFG;
4667  
4668           // Completion disabled in this site, don't execute
4669           if (empty($CFG->enablecompletion)) {
4670               return false;
4671           }
4672  
4673          // No completion on the front page.
4674          if ($this->get_courseid() == SITEID) {
4675              return false;
4676          }
4677  
4678           // No user completion info found, don't execute
4679          $fullpath = $this->task->get_taskbasepath();
4680          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4681           if (!file_exists($fullpath)) {
4682               return false;
4683           }
4684  
4685           // Arrived here, execute the step
4686           return true;
4687       }
4688  
4689       protected function define_structure() {
4690  
4691          $paths = array();
4692  
4693          $paths[] = new restore_path_element('completion', '/completions/completion');
4694  
4695          return $paths;
4696      }
4697  
4698      protected function process_completion($data) {
4699          global $DB;
4700  
4701          $data = (object)$data;
4702  
4703          $data->coursemoduleid = $this->task->get_moduleid();
4704          $data->userid = $this->get_mappingid('user', $data->userid);
4705  
4706          // Find the existing record
4707          $existing = $DB->get_record('course_modules_completion', array(
4708                  'coursemoduleid' => $data->coursemoduleid,
4709                  'userid' => $data->userid), 'id, timemodified');
4710          // Check we didn't already insert one for this cmid and userid
4711          // (there aren't supposed to be duplicates in that field, but
4712          // it was possible until MDL-28021 was fixed).
4713          if ($existing) {
4714              // Update it to these new values, but only if the time is newer
4715              if ($existing->timemodified < $data->timemodified) {
4716                  $data->id = $existing->id;
4717                  $DB->update_record('course_modules_completion', $data);
4718              }
4719          } else {
4720              // Normal entry where it doesn't exist already
4721              $DB->insert_record('course_modules_completion', $data);
4722          }
4723      }
4724  }
4725  
4726  /**
4727   * Abstract structure step, parent of all the activity structure steps. Used to support
4728   * the main <activity ...> tag and process it.
4729   */
4730  abstract class restore_activity_structure_step extends restore_structure_step {
4731  
4732      /**
4733       * Adds support for the 'activity' path that is common to all the activities
4734       * and will be processed globally here
4735       */
4736      protected function prepare_activity_structure($paths) {
4737  
4738          $paths[] = new restore_path_element('activity', '/activity');
4739  
4740          return $paths;
4741      }
4742  
4743      /**
4744       * Process the activity path, informing the task about various ids, needed later
4745       */
4746      protected function process_activity($data) {
4747          $data = (object)$data;
4748          $this->task->set_old_contextid($data->contextid); // Save old contextid in task
4749          $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
4750          $this->task->set_old_activityid($data->id); // Save old activityid in task
4751      }
4752  
4753      /**
4754       * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4755       * and will adjust the new activity id (the instance) in various places
4756       */
4757      protected function apply_activity_instance($newitemid) {
4758          global $DB;
4759  
4760          $this->task->set_activityid($newitemid); // Save activity id in task
4761          // Apply the id to course_sections->instanceid
4762          $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
4763          // Do the mapping for modulename, preparing it for files by oldcontext
4764          $modulename = $this->task->get_modulename();
4765          $oldid = $this->task->get_old_activityid();
4766          $this->set_mapping($modulename, $oldid, $newitemid, true);
4767      }
4768  }
4769  
4770  /**
4771   * Structure step in charge of creating/mapping all the qcats and qs
4772   * by parsing the questions.xml file and checking it against the
4773   * results calculated by {@link restore_process_categories_and_questions}
4774   * and stored in backup_ids_temp.
4775   */
4776  class restore_create_categories_and_questions extends restore_structure_step {
4777  
4778      /** @var array $cachedcategory store a question category */
4779      protected $cachedcategory = null;
4780  
4781      protected function define_structure() {
4782  
4783          // Check if the backup is a pre 4.0 one.
4784          $restoretask = $this->get_task();
4785          $before40 = $restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<');
4786          // Start creating the path, category should be the first one.
4787          $paths = [];
4788          $paths [] = new restore_path_element('question_category', '/question_categories/question_category');
4789          // For the backups done before 4.0.
4790          if ($before40) {
4791              // This path is to recreate the bank entry and version for the legacy question objets.
4792              $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4793  
4794              // Apply for 'qtype' plugins optional paths at question level.
4795              $this->add_plugin_structure('qtype', $question);
4796  
4797              // Apply for 'local' plugins optional paths at question level.
4798              $this->add_plugin_structure('local', $question);
4799  
4800              $paths [] = $question;
4801              $paths [] = new restore_path_element('question_hint',
4802                  '/question_categories/question_category/questions/question/question_hints/question_hint');
4803              $paths [] = new restore_path_element('tag', '/question_categories/question_category/questions/question/tags/tag');
4804          } else {
4805              // For all the new backups.
4806              $paths [] = new restore_path_element('question_bank_entry',
4807                  '/question_categories/question_category/question_bank_entries/question_bank_entry');
4808              $paths [] = new restore_path_element('question_versions', '/question_categories/question_category/'.
4809                  'question_bank_entries/question_bank_entry/question_version/question_versions');
4810              $question = new restore_path_element('question', '/question_categories/question_category/'.
4811                  'question_bank_entries/question_bank_entry/question_version/question_versions/questions/question');
4812  
4813              // Apply for 'qtype' plugins optional paths at question level.
4814              $this->add_plugin_structure('qtype', $question);
4815  
4816              // Apply for 'qbank' plugins optional paths at question level.
4817              $this->add_plugin_structure('qbank', $question);
4818  
4819              // Apply for 'local' plugins optional paths at question level.
4820              $this->add_plugin_structure('local', $question);
4821  
4822              $paths [] = $question;
4823              $paths [] = new restore_path_element('question_hint', '/question_categories/question_category/question_bank_entries/'.
4824                  'question_bank_entry/question_version/question_versions/questions/question/question_hints/question_hint');
4825              $paths [] = new restore_path_element('tag', '/question_categories/question_category/question_bank_entries/'.
4826                  'question_bank_entry/question_version/question_versions/questions/question/tags/tag');
4827          }
4828  
4829          return $paths;
4830      }
4831  
4832      /**
4833       * Process question category restore.
4834       *
4835       * @param array $data the data from the XML file.
4836       */
4837      protected function process_question_category($data) {
4838          global $DB;
4839  
4840          $data = (object)$data;
4841          $oldid = $data->id;
4842  
4843          // Check we have one mapping for this category.
4844          if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4845              return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
4846          }
4847  
4848          // Check we have to create the category (newitemid = 0).
4849          if ($mapping->newitemid) {
4850              // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4851              // children elements of the 'question_category' one.
4852              $this->set_mapping('question_category', $oldid, $mapping->newitemid);
4853              return; // newitemid != 0, this category is going to be mapped. Nothing to do
4854          }
4855  
4856          // Arrived here, newitemid = 0, we need to create the category
4857          // we'll do it at parentitemid context, but for CONTEXT_MODULE
4858          // categories, that will be created at CONTEXT_COURSE and moved
4859          // to module context later when the activity is created.
4860          if ($mapping->info->contextlevel == CONTEXT_MODULE) {
4861              $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
4862          }
4863          $data->contextid = $mapping->parentitemid;
4864  
4865          // Before 3.5, question categories could be created at top level.
4866          // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
4867          $restoretask = $this->get_task();
4868          $before35 = $restoretask->backup_release_compare('3.5', '<') || $restoretask->backup_version_compare(20180205, '<');
4869          if (empty($mapping->info->parent) && $before35) {
4870              $top = question_get_top_category($data->contextid, true);
4871              $data->parent = $top->id;
4872          }
4873  
4874          if (empty($data->parent)) {
4875              if (!$top = question_get_top_category($data->contextid)) {
4876                  $top = question_get_top_category($data->contextid, true);
4877                  $this->set_mapping('question_category_created', $oldid, $top->id, false, null, $data->contextid);
4878              }
4879              $this->set_mapping('question_category', $oldid, $top->id);
4880          } else {
4881  
4882              // Before 3.1, the 'stamp' field could be erroneously duplicated.
4883              // From 3.1 onwards, there's a unique index of (contextid, stamp).
4884              // If we encounter a duplicate in an old restore file, just generate a new stamp.
4885              // This is the same as what happens during an upgrade to 3.1+ anyway.
4886              if ($DB->record_exists('question_categories', ['stamp' => $data->stamp, 'contextid' => $data->contextid])) {
4887                  $data->stamp = make_unique_id_code();
4888              }
4889  
4890              // The idnumber if it exists also needs to be unique within a context or reset it to null.
4891              if (!empty($data->idnumber) && $DB->record_exists('question_categories',
4892                      ['idnumber' => $data->idnumber, 'contextid' => $data->contextid])) {
4893                  unset($data->idnumber);
4894              }
4895  
4896              // Let's create the question_category and save mapping.
4897              $newitemid = $DB->insert_record('question_categories', $data);
4898              $this->set_mapping('question_category', $oldid, $newitemid);
4899              // Also annotate them as question_category_created, we need
4900              // that later when remapping parents.
4901              $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
4902          }
4903      }
4904  
4905      /**
4906       * Process pre 4.0 question data where in creates the record for version and entry table.
4907       *
4908       * @param array $data the data from the XML file.
4909       */
4910      protected function process_question_legacy_data($data) {
4911          global $DB;
4912  
4913          $oldid = $data->id;
4914          // Process question bank entry.
4915          $entrydata = new stdClass();
4916          $entrydata->questioncategoryid = $data->category;
4917          $userid = $this->get_mappingid('user', $data->createdby);
4918          if ($userid) {
4919              $entrydata->ownerid = $userid;
4920          } else {
4921              if (!$this->task->is_samesite()) {
4922                  $entrydata->ownerid = $this->task->get_userid();
4923              }
4924          }
4925          // The idnumber if it exists also needs to be unique within a category or reset it to null.
4926          if (isset($data->idnumber) && !$DB->record_exists('question_bank_entries',
4927                  ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->category])) {
4928              $entrydata->idnumber = $data->idnumber;
4929          }
4930  
4931          $newentryid = $DB->insert_record('question_bank_entries', $entrydata);
4932          // Process question versions.
4933          $versiondata = new stdClass();
4934          $versiondata->questionbankentryid = $newentryid;
4935          $versiondata->version = 1;
4936          // Question id is updated after inserting the question.
4937          $versiondata->questionid = 0;
4938          $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
4939          if ((int)$data->hidden === 1) {
4940              $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_HIDDEN;
4941          }
4942          $versiondata->status = $versionstatus;
4943          $newversionid = $DB->insert_record('question_versions', $versiondata);
4944          $this->set_mapping('question_version_created', $oldid, $newversionid);
4945      }
4946  
4947      /**
4948       * Process question bank entry data.
4949       *
4950       * @param array $data the data from the XML file.
4951       */
4952      protected function process_question_bank_entry($data) {
4953          global $DB;
4954  
4955          $data = (object)$data;
4956          $oldid = $data->id;
4957  
4958          $questioncreated = $this->get_mappingid('question_category_created', $data->questioncategoryid) ? true : false;
4959          $recordexist = $DB->record_exists('question_bank_entries', ['id' => $data->id,
4960              'questioncategoryid' => $data->questioncategoryid]);
4961          // Check we have category created.
4962          if (!$questioncreated && $recordexist) {
4963              return self::SKIP_ALL_CHILDREN;
4964          }
4965  
4966          $data->questioncategoryid = $this->get_new_parentid('question_category');
4967          $userid = $this->get_mappingid('user', $data->ownerid);
4968          if ($userid) {
4969              $data->ownerid = $userid;
4970          } else {
4971              if (!$this->task->is_samesite()) {
4972                  $data->ownerid = $this->task->get_userid();
4973              }
4974          }
4975  
4976          // The idnumber if it exists also needs to be unique within a category or reset it to null.
4977          if (!empty($data->idnumber) && $DB->record_exists('question_bank_entries',
4978                  ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->questioncategoryid])) {
4979              unset($data->idnumber);
4980          }
4981  
4982          $newitemid = $DB->insert_record('question_bank_entries', $data);
4983          $this->set_mapping('question_bank_entry', $oldid, $newitemid);
4984      }
4985  
4986      /**
4987       * Process question versions.
4988       *
4989       * @param array $data the data from the XML file.
4990       */
4991      protected function process_question_versions($data) {
4992          global $DB;
4993  
4994          $data = (object)$data;
4995          $oldid = $data->id;
4996  
4997          $data->questionbankentryid = $this->get_new_parentid('question_bank_entry');
4998          // Question id is updated after inserting the question.
4999          $data->questionid = 0;
5000          $newitemid = $DB->insert_record('question_versions', $data);
5001          $this->set_mapping('question_versions', $oldid, $newitemid);
5002      }
5003  
5004      /**
5005       * Process the actual question.
5006       *
5007       * @param array $data the data from the XML file.
5008       */
5009      protected function process_question($data) {
5010          global $DB;
5011  
5012          $data = (object)$data;
5013          $oldid = $data->id;
5014  
5015          // Check if the backup is a pre 4.0 one.
5016          $restoretask = $this->get_task();
5017          if ($restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<')) {
5018              // Check we have one mapping for this question.
5019              if (!$questionmapping = $this->get_mapping('question', $oldid)) {
5020                  return; // No mapping = this question doesn't need to be created/mapped.
5021              }
5022  
5023              // Get the mapped category (cannot use get_new_parentid() because not
5024              // all the categories have been created, so it is not always available
5025              // Instead we get the mapping for the question->parentitemid because
5026              // we have loaded qcatids there for all parsed questions.
5027              $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
5028              $this->process_question_legacy_data($data);
5029          }
5030  
5031          // In the past, there were some very sloppy values of penalty. Fix them.
5032          if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
5033              $data->penalty = 0.3333333;
5034          }
5035          if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
5036              $data->penalty = 0.6666667;
5037          }
5038          if ($data->penalty >= 1) {
5039              $data->penalty = 1;
5040          }
5041  
5042          $userid = $this->get_mappingid('user', $data->createdby);
5043          if ($userid) {
5044              // The question creator is included in the backup, so we can use their mapping id.
5045              $data->createdby = $userid;
5046          } else {
5047              // Leave the question creator unchanged when we are restoring the same site.
5048              // Otherwise use current user id.
5049              if (!$this->task->is_samesite()) {
5050                  $data->createdby = $this->task->get_userid();
5051              }
5052          }
5053  
5054          $userid = $this->get_mappingid('user', $data->modifiedby);
5055          if ($userid) {
5056              // The question modifier is included in the backup, so we can use their mapping id.
5057              $data->modifiedby = $userid;
5058          } else {
5059              // Leave the question modifier unchanged when we are restoring the same site.
5060              // Otherwise use current user id.
5061              if (!$this->task->is_samesite()) {
5062                  $data->modifiedby = $this->task->get_userid();
5063              }
5064          }
5065  
5066          $newitemid = $DB->insert_record('question', $data);
5067          $this->set_mapping('question', $oldid, $newitemid);
5068          // Also annotate them as question_created, we need
5069          // that later when remapping parents (keeping the old categoryid as parentid).
5070          $parentcatid = $this->get_old_parentid('question_category');
5071          $this->set_mapping('question_created', $oldid, $newitemid, false, null, $parentcatid);
5072          // Now update the question_versions table with the new question id. we dont need to do that for random qtypes.
5073          $legacyquestiondata = $this->get_mappingid('question_version_created', $oldid) ? true : false;
5074          if ($legacyquestiondata) {
5075              $parentitemid = $this->get_mappingid('question_version_created', $oldid);
5076          } else {
5077              $parentitemid = $this->get_new_parentid('question_versions');
5078          }
5079          $version = new stdClass();
5080          $version->id = $parentitemid;
5081          $version->questionid = $newitemid;
5082          $DB->update_record('question_versions', $version);
5083  
5084          // Note, we don't restore any question files yet
5085          // as far as the CONTEXT_MODULE categories still
5086          // haven't their contexts to be restored to
5087          // The {@link restore_create_question_files}, executed in the final step
5088          // step will be in charge of restoring all the question files.
5089      }
5090  
5091      protected function process_question_hint($data) {
5092          global $DB;
5093  
5094          $data = (object)$data;
5095          $oldid = $data->id;
5096  
5097          // Detect if the question is created or mapped
5098          $oldquestionid   = $this->get_old_parentid('question');
5099          $newquestionid   = $this->get_new_parentid('question');
5100          $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
5101  
5102          // If the question has been created by restore, we need to create its question_answers too
5103          if ($questioncreated) {
5104              // Adjust some columns
5105              $data->questionid = $newquestionid;
5106              // Insert record
5107              $newitemid = $DB->insert_record('question_hints', $data);
5108  
5109          // The question existed, we need to map the existing question_hints
5110          } else {
5111              // Look in question_hints by hint text matching
5112              $sql = 'SELECT id
5113                        FROM {question_hints}
5114                       WHERE questionid = ?
5115                         AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
5116              $params = array($newquestionid, $data->hint);
5117              $newitemid = $DB->get_field_sql($sql, $params);
5118  
5119              // Not able to find the hint, let's try cleaning the hint text
5120              // of all the question's hints in DB as slower fallback. MDL-33863.
5121              if (!$newitemid) {
5122                  $potentialhints = $DB->get_records('question_hints',
5123                          array('questionid' => $newquestionid), '', 'id, hint');
5124                  foreach ($potentialhints as $potentialhint) {
5125                      // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
5126                      $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
5127                      $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
5128                      if ($cleanhint === $data->hint) {
5129                          $newitemid = $data->id;
5130                      }
5131                  }
5132              }
5133  
5134              // If we haven't found the newitemid, something has gone really wrong, question in DB
5135              // is missing hints, exception
5136              if (!$newitemid) {
5137                  $info = new stdClass();
5138                  $info->filequestionid = $oldquestionid;
5139                  $info->dbquestionid   = $newquestionid;
5140                  $info->hint           = $data->hint;
5141                  throw new restore_step_exception('error_question_hint_missing_in_db', $info);
5142              }
5143          }
5144          // Create mapping (I'm not sure if this is really needed?)
5145          $this->set_mapping('question_hint', $oldid, $newitemid);
5146      }
5147  
5148      protected function process_tag($data) {
5149          global $DB;
5150  
5151          $data = (object)$data;
5152          $newquestion = $this->get_new_parentid('question');
5153          $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
5154          if (!$questioncreated) {
5155              // This question already exists in the question bank. Nothing for us to do.
5156              return;
5157          }
5158  
5159          if (core_tag_tag::is_enabled('core_question', 'question')) {
5160              $tagname = $data->rawname;
5161              if (!empty($data->contextid) && $newcontextid = $this->get_mappingid('context', $data->contextid)) {
5162                      $tagcontextid = $newcontextid;
5163              } else {
5164                  // Get the category, so we can then later get the context.
5165                  $categoryid = $this->get_new_parentid('question_category');
5166                  if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
5167                      $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
5168                  }
5169                  $tagcontextid = $this->cachedcategory->contextid;
5170              }
5171              // Add the tag to the question.
5172              core_tag_tag::add_item_tag('core_question', 'question', $newquestion,
5173                      context::instance_by_id($tagcontextid),
5174                      $tagname);
5175          }
5176      }
5177  
5178      protected function after_execute() {
5179          global $DB;
5180  
5181          // First of all, recode all the created question_categories->parent fields
5182          $qcats = $DB->get_records('backup_ids_temp', array(
5183                       'backupid' => $this->get_restoreid(),
5184                       'itemname' => 'question_category_created'));
5185          foreach ($qcats as $qcat) {
5186              $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
5187              // Get new parent (mapped or created, so we look in quesiton_category mappings)
5188              if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5189                                   'backupid' => $this->get_restoreid(),
5190                                   'itemname' => 'question_category',
5191                                   'itemid'   => $dbcat->parent))) {
5192                  // contextids must match always, as far as we always include complete qbanks, just check it
5193                  $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
5194                  if ($dbcat->contextid == $newparentctxid) {
5195                      $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
5196                  } else {
5197                      $newparent = 0; // No ctx match for both cats, no parent relationship
5198                  }
5199              }
5200              // Here with $newparent empty, problem with contexts or remapping, set it to top cat
5201              if (!$newparent && $dbcat->parent) {
5202                  $topcat = question_get_top_category($dbcat->contextid, true);
5203                  if ($dbcat->parent != $topcat->id) {
5204                      $DB->set_field('question_categories', 'parent', $topcat->id, array('id' => $dbcat->id));
5205                  }
5206              }
5207          }
5208  
5209          // Now, recode all the created question->parent fields
5210          $qs = $DB->get_records('backup_ids_temp', array(
5211                    'backupid' => $this->get_restoreid(),
5212                    'itemname' => 'question_created'));
5213          foreach ($qs as $q) {
5214              $dbq = $DB->get_record('question', array('id' => $q->newitemid));
5215              // Get new parent (mapped or created, so we look in question mappings)
5216              if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5217                                   'backupid' => $this->get_restoreid(),
5218                                   'itemname' => 'question',
5219                                   'itemid'   => $dbq->parent))) {
5220                  $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
5221              }
5222          }
5223  
5224          // Note, we don't restore any question files yet
5225          // as far as the CONTEXT_MODULE categories still
5226          // haven't their contexts to be restored to
5227          // The {@link restore_create_question_files}, executed in the final step
5228          // step will be in charge of restoring all the question files
5229      }
5230  }
5231  
5232  /**
5233   * Execution step that will move all the CONTEXT_MODULE question categories
5234   * created at early stages of restore in course context (because modules weren't
5235   * created yet) to their target module (matching by old-new-contextid mapping)
5236   */
5237  class restore_move_module_questions_categories extends restore_execution_step {
5238  
5239      protected function define_execution() {
5240          global $DB;
5241  
5242          $after35 = $this->task->backup_release_compare('3.5', '>=') && $this->task->backup_version_compare(20180205, '>');
5243  
5244          $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
5245          foreach ($contexts as $contextid => $contextlevel) {
5246              // Only if context mapping exists (i.e. the module has been restored)
5247              if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
5248                  // Update all the qcats having their parentitemid set to the original contextid
5249                  $modulecats = $DB->get_records_sql("SELECT itemid, newitemid, info
5250                                                        FROM {backup_ids_temp}
5251                                                       WHERE backupid = ?
5252                                                         AND itemname = 'question_category'
5253                                                         AND parentitemid = ?", array($this->get_restoreid(), $contextid));
5254                  $top = question_get_top_category($newcontext->newitemid, true);
5255                  $oldtopid = 0;
5256                  $categoryids = [];
5257                  foreach ($modulecats as $modulecat) {
5258                      // Before 3.5, question categories could be created at top level.
5259                      // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
5260                      $info = backup_controller_dbops::decode_backup_temp_info($modulecat->info);
5261                      if ($after35 && empty($info->parent)) {
5262                          $oldtopid = $modulecat->newitemid;
5263                          $modulecat->newitemid = $top->id;
5264                      } else {
5265                          $cat = new stdClass();
5266                          $cat->id = $modulecat->newitemid;
5267                          $cat->contextid = $newcontext->newitemid;
5268                          if (empty($info->parent)) {
5269                              $cat->parent = $top->id;
5270                          }
5271                          $DB->update_record('question_categories', $cat);
5272                          $categoryids[] = (int)$cat->id;
5273                      }
5274  
5275                      // And set new contextid (and maybe update newitemid) also in question_category mapping (will be
5276                      // used by {@link restore_create_question_files} later.
5277                      restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid,
5278                              $modulecat->newitemid, $newcontext->newitemid);
5279                  }
5280  
5281                  // Update the context id of any tags applied to any questions in these categories.
5282                  if ($categoryids) {
5283                      [$categorysql, $categoryidparams] = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
5284                      $sqlupdate = "UPDATE {tag_instance}
5285                                       SET contextid = :newcontext
5286                                     WHERE component = :component
5287                                           AND itemtype = :itemtype
5288                                           AND itemid IN (SELECT DISTINCT bi.newitemid as questionid
5289                                                            FROM {backup_ids_temp} bi
5290                                                            JOIN {question} q ON q.id = bi.newitemid
5291                                                            JOIN {question_versions} qv ON qv.questionid = q.id
5292                                                            JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
5293                                                           WHERE bi.backupid = :backupid AND bi.itemname = 'question_created'
5294                                                                 AND qbe.questioncategoryid {$categorysql}) ";
5295                      $params = [
5296                          'newcontext' => $newcontext->newitemid,
5297                          'component' => 'core_question',
5298                          'itemtype' => 'question',
5299                          'backupid' => $this->get_restoreid(),
5300                      ];
5301                      $params += $categoryidparams;
5302                      $DB->execute($sqlupdate, $params);
5303                  }
5304  
5305                  // Now set the parent id for the question categories that were in the top category in the course context
5306                  // and have been moved now.
5307                  if ($oldtopid) {
5308                      $DB->set_field('question_categories', 'parent', $top->id,
5309                              array('contextid' => $newcontext->newitemid, 'parent' => $oldtopid));
5310                  }
5311              }
5312          }
5313      }
5314  }
5315  
5316  /**
5317   * Execution step that will create all the question/answers/qtype-specific files for the restored
5318   * questions. It must be executed after {@link restore_move_module_questions_categories}
5319   * because only then each question is in its final category and only then the
5320   * contexts can be determined.
5321   */
5322  class restore_create_question_files extends restore_execution_step {
5323  
5324      /** @var array Question-type specific component items cache. */
5325      private $qtypecomponentscache = array();
5326  
5327      /**
5328       * Preform the restore_create_question_files step.
5329       */
5330      protected function define_execution() {
5331          global $DB;
5332  
5333          // Track progress, as this task can take a long time.
5334          $progress = $this->task->get_progress();
5335          $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
5336  
5337          // Parentitemids of question_createds in backup_ids_temp are the category it is in.
5338          // MUST use a recordset, as there is no unique key in the first (or any) column.
5339          $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
5340                                                     FROM {backup_ids_temp} bi
5341                                                     JOIN {question} q ON q.id = bi.newitemid
5342                                                    WHERE bi.backupid = ?
5343                                                          AND bi.itemname = 'question_created'
5344                                                 ORDER BY categoryid ASC", array($this->get_restoreid()));
5345  
5346          $currentcatid = -1;
5347          foreach ($catqtypes as $categoryid => $row) {
5348              $qtype = $row->qtype;
5349  
5350              // Check if we are in a new category.
5351              if ($currentcatid !== $categoryid) {
5352                  // Report progress for each category.
5353                  $progress->progress();
5354  
5355                  if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
5356                          'question_category', $categoryid)) {
5357                      // Something went really wrong, cannot find the question_category for the question_created records.
5358                      debugging('Error fetching target context for question', DEBUG_DEVELOPER);
5359                      continue;
5360                  }
5361  
5362                  // Calculate source and target contexts.
5363                  $oldctxid = $qcatmapping->info->contextid;
5364                  $newctxid = $qcatmapping->parentitemid;
5365  
5366                  $this->send_common_files($oldctxid, $newctxid, $progress);
5367                  $currentcatid = $categoryid;
5368              }
5369  
5370              $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
5371          }
5372          $catqtypes->close();
5373          $progress->end_progress();
5374      }
5375  
5376      /**
5377       * Send the common question files to a new context.
5378       *
5379       * @param int             $oldctxid Old context id.
5380       * @param int             $newctxid New context id.
5381       * @param \core\progress  $progress Progress object to use.
5382       */
5383      private function send_common_files($oldctxid, $newctxid, $progress) {
5384          // Add common question files (question and question_answer ones).
5385          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
5386                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5387          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
5388                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5389          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
5390                  $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5391          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
5392                  $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5393          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
5394                  $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
5395          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
5396                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5397          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
5398                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5399          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
5400                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5401      }
5402  
5403      /**
5404       * Send the question type specific files to a new context.
5405       *
5406       * @param text            $qtype The qtype name to send.
5407       * @param int             $oldctxid Old context id.
5408       * @param int             $newctxid New context id.
5409       * @param \core\progress  $progress Progress object to use.
5410       */
5411      private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
5412          if (!isset($this->qtypecomponentscache[$qtype])) {
5413              $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
5414          }
5415          $components = $this->qtypecomponentscache[$qtype];
5416          foreach ($components as $component => $fileareas) {
5417              foreach ($fileareas as $filearea => $mapping) {
5418                  restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
5419                          $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
5420              }
5421          }
5422      }
5423  }
5424  
5425  /**
5426   * Try to restore aliases and references to external files.
5427   *
5428   * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5429   * We expect that all regular (non-alias) files have already been restored. Make sure
5430   * there is no restore step executed after this one that would call send_files_to_pool() again.
5431   *
5432   * You may notice we have hardcoded support for Server files, Legacy course files
5433   * and user Private files here at the moment. This could be eventually replaced with a set of
5434   * callbacks in the future if needed.
5435   *
5436   * @copyright 2012 David Mudrak <david@moodle.com>
5437   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5438   */
5439  class restore_process_file_aliases_queue extends restore_execution_step {
5440  
5441      /** @var array internal cache for {@link choose_repository()} */
5442      private $cachereposbyid = array();
5443  
5444      /** @var array internal cache for {@link choose_repository()} */
5445      private $cachereposbytype = array();
5446  
5447      /**
5448       * What to do when this step is executed.
5449       */
5450      protected function define_execution() {
5451          global $DB;
5452  
5453          $fs = get_file_storage();
5454  
5455          // Load the queue.
5456          $aliascount = $DB->count_records('backup_ids_temp',
5457              ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue']);
5458          $rs = $DB->get_recordset('backup_ids_temp',
5459              ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'],
5460              '', 'info');
5461  
5462          $this->log('processing file aliases queue. ' . $aliascount . ' entries.', backup::LOG_DEBUG);
5463          $progress = $this->task->get_progress();
5464          $progress->start_progress('Processing file aliases queue', $aliascount);
5465  
5466          // Iterate over aliases in the queue.
5467          foreach ($rs as $record) {
5468              $progress->increment_progress();
5469              $info = backup_controller_dbops::decode_backup_temp_info($record->info);
5470  
5471              // Try to pick a repository instance that should serve the alias.
5472              $repository = $this->choose_repository($info);
5473  
5474              if (is_null($repository)) {
5475                  $this->notify_failure($info, 'unable to find a matching repository instance');
5476                  continue;
5477              }
5478  
5479              if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5480                      || $info->oldfile->repositorytype === 'contentbank') {
5481                  // Aliases to Server files and Legacy course files may refer to a file
5482                  // contained in the backup file or to some existing file (if we are on the
5483                  // same site).
5484                  try {
5485                      $reference = file_storage::unpack_reference($info->oldfile->reference);
5486                  } catch (Exception $e) {
5487                      $this->notify_failure($info, 'invalid reference field format');
5488                      continue;
5489                  }
5490  
5491                  // Let's see if the referred source file was also included in the backup.
5492                  $candidates = $DB->get_recordset('backup_files_temp', array(
5493                          'backupid' => $this->get_restoreid(),
5494                          'contextid' => $reference['contextid'],
5495                          'component' => $reference['component'],
5496                          'filearea' => $reference['filearea'],
5497                          'itemid' => $reference['itemid'],
5498                      ), '', 'info, newcontextid, newitemid');
5499  
5500                  $source = null;
5501  
5502                  foreach ($candidates as $candidate) {
5503                      $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
5504                      if ($candidateinfo->filename === $reference['filename']
5505                              and $candidateinfo->filepath === $reference['filepath']
5506                              and !is_null($candidate->newcontextid)
5507                              and !is_null($candidate->newitemid) ) {
5508                          $source = $candidateinfo;
5509                          $source->contextid = $candidate->newcontextid;
5510                          $source->itemid = $candidate->newitemid;
5511                          break;
5512                      }
5513                  }
5514                  $candidates->close();
5515  
5516                  if ($source) {
5517                      // We have an alias that refers to another file also included in
5518                      // the backup. Let us change the reference field so that it refers
5519                      // to the restored copy of the original file.
5520                      $reference = file_storage::pack_reference($source);
5521  
5522                      // Send the new alias to the filepool.
5523                      $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5524                      $this->notify_success($info);
5525                      continue;
5526  
5527                  } else {
5528                      // This is a reference to some moodle file that was not contained in the backup
5529                      // file. If we are restoring to the same site, keep the reference untouched
5530                      // and restore the alias as is if the referenced file exists.
5531                      if ($this->task->is_samesite()) {
5532                          if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5533                                  $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5534                              $reference = file_storage::pack_reference($reference);
5535                              $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5536                              $this->notify_success($info);
5537                              continue;
5538                          } else {
5539                              $this->notify_failure($info, 'referenced file not found');
5540                              continue;
5541                          }
5542  
5543                      // If we are at other site, we can't restore this alias.
5544                      } else {
5545                          $this->notify_failure($info, 'referenced file not included');
5546                          continue;
5547                      }
5548                  }
5549  
5550              } else if ($info->oldfile->repositorytype === 'user') {
5551                  if ($this->task->is_samesite()) {
5552                      // For aliases to user Private files at the same site, we have a chance to check
5553                      // if the referenced file still exists.
5554                      try {
5555                          $reference = file_storage::unpack_reference($info->oldfile->reference);
5556                      } catch (Exception $e) {
5557                          $this->notify_failure($info, 'invalid reference field format');
5558                          continue;
5559                      }
5560                      if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5561                              $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5562                          $reference = file_storage::pack_reference($reference);
5563                          $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5564                          $this->notify_success($info);
5565                          continue;
5566                      } else {
5567                          $this->notify_failure($info, 'referenced file not found');
5568                          continue;
5569                      }
5570  
5571                  // If we are at other site, we can't restore this alias.
5572                  } else {
5573                      $this->notify_failure($info, 'restoring at another site');
5574                      continue;
5575                  }
5576  
5577              } else {
5578                  // This is a reference to some external file such as dropbox.
5579                  // If we are restoring to the same site, keep the reference untouched and
5580                  // restore the alias as is.
5581                  if ($this->task->is_samesite()) {
5582                      $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
5583                      $this->notify_success($info);
5584                      continue;
5585  
5586                  // If we are at other site, we can't restore this alias.
5587                  } else {
5588                      $this->notify_failure($info, 'restoring at another site');
5589                      continue;
5590                  }
5591              }
5592          }
5593          $progress->end_progress();
5594          $rs->close();
5595      }
5596  
5597      /**
5598       * Choose the repository instance that should handle the alias.
5599       *
5600       * At the same site, we can rely on repository instance id and we just
5601       * check it still exists. On other site, try to find matching Server files or
5602       * Legacy course files repository instance. Return null if no matching
5603       * repository instance can be found.
5604       *
5605       * @param stdClass $info
5606       * @return repository|null
5607       */
5608      private function choose_repository(stdClass $info) {
5609          global $DB, $CFG;
5610          require_once($CFG->dirroot.'/repository/lib.php');
5611  
5612          if ($this->task->is_samesite()) {
5613              // We can rely on repository instance id.
5614  
5615              if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
5616                  return $this->cachereposbyid[$info->oldfile->repositoryid];
5617              }
5618  
5619              $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
5620  
5621              try {
5622                  $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
5623                  return $this->cachereposbyid[$info->oldfile->repositoryid];
5624              } catch (Exception $e) {
5625                  $this->cachereposbyid[$info->oldfile->repositoryid] = null;
5626                  return null;
5627              }
5628  
5629          } else {
5630              // We can rely on repository type only.
5631  
5632              if (empty($info->oldfile->repositorytype)) {
5633                  return null;
5634              }
5635  
5636              if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
5637                  return $this->cachereposbytype[$info->oldfile->repositorytype];
5638              }
5639  
5640              $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
5641  
5642              // Both Server files and Legacy course files repositories have a single
5643              // instance at the system context to use. Let us try to find it.
5644              if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5645                      || $info->oldfile->repositorytype === 'contentbank') {
5646                  $sql = "SELECT ri.id
5647                            FROM {repository} r
5648                            JOIN {repository_instances} ri ON ri.typeid = r.id
5649                           WHERE r.type = ? AND ri.contextid = ?";
5650                  $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
5651                  if (empty($ris)) {
5652                      return null;
5653                  }
5654                  $repoids = array_keys($ris);
5655                  $repoid = reset($repoids);
5656                  try {
5657                      $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
5658                      return $this->cachereposbytype[$info->oldfile->repositorytype];
5659                  } catch (Exception $e) {
5660                      $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5661                      return null;
5662                  }
5663              }
5664  
5665              $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5666              return null;
5667          }
5668      }
5669  
5670      /**
5671       * Let the user know that the given alias was successfully restored
5672       *
5673       * @param stdClass $info
5674       */
5675      private function notify_success(stdClass $info) {
5676          $filedesc = $this->describe_alias($info);
5677          $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
5678      }
5679  
5680      /**
5681       * Let the user know that the given alias can't be restored
5682       *
5683       * @param stdClass $info
5684       * @param string $reason detailed reason to be logged
5685       */
5686      private function notify_failure(stdClass $info, $reason = '') {
5687          $filedesc = $this->describe_alias($info);
5688          if ($reason) {
5689              $reason = ' ('.$reason.')';
5690          }
5691          $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5692          $this->add_result_item('file_aliases_restore_failures', $filedesc);
5693      }
5694  
5695      /**
5696       * Return a human readable description of the alias file
5697       *
5698       * @param stdClass $info
5699       * @return string
5700       */
5701      private function describe_alias(stdClass $info) {
5702  
5703          $filedesc = $this->expected_alias_location($info->newfile);
5704  
5705          if (!is_null($info->oldfile->source)) {
5706              $filedesc .= ' ('.$info->oldfile->source.')';
5707          }
5708  
5709          return $filedesc;
5710      }
5711  
5712      /**
5713       * Return the expected location of a file
5714       *
5715       * Please note this may and may not work as a part of URL to pluginfile.php
5716       * (depends on how the given component/filearea deals with the itemid).
5717       *
5718       * @param stdClass $filerecord
5719       * @return string
5720       */
5721      private function expected_alias_location($filerecord) {
5722  
5723          $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5724          if (!is_null($filerecord->itemid)) {
5725              $filedesc .= '/'.$filerecord->itemid;
5726          }
5727          $filedesc .= $filerecord->filepath.$filerecord->filename;
5728  
5729          return $filedesc;
5730      }
5731  
5732      /**
5733       * Append a value to the given resultset
5734       *
5735       * @param string $name name of the result containing a list of values
5736       * @param mixed $value value to add as another item in that result
5737       */
5738      private function add_result_item($name, $value) {
5739  
5740          $results = $this->task->get_results();
5741  
5742          if (isset($results[$name])) {
5743              if (!is_array($results[$name])) {
5744                  throw new coding_exception('Unable to append a result item into a non-array structure.');
5745              }
5746              $current = $results[$name];
5747              $current[] = $value;
5748              $this->task->add_result(array($name => $current));
5749  
5750          } else {
5751              $this->task->add_result(array($name => array($value)));
5752          }
5753      }
5754  }
5755  
5756  
5757  /**
5758   * Helper code for use by any plugin that stores question attempt data that it needs to back up.
5759   */
5760  trait restore_questions_attempt_data_trait {
5761      /** @var array question_attempt->id to qtype. */
5762      protected $qtypes = array();
5763      /** @var array question_attempt->id to questionid. */
5764      protected $newquestionids = array();
5765  
5766      /**
5767       * Attach below $element (usually attempts) the needed restore_path_elements
5768       * to restore question_usages and all they contain.
5769       *
5770       * If you use the $nameprefix parameter, then you will need to implement some
5771       * extra methods in your class, like
5772       *
5773       * protected function process_{nameprefix}question_attempt($data) {
5774       *     $this->restore_question_usage_worker($data, '{nameprefix}');
5775       * }
5776       * protected function process_{nameprefix}question_attempt($data) {
5777       *     $this->restore_question_attempt_worker($data, '{nameprefix}');
5778       * }
5779       * protected function process_{nameprefix}question_attempt_step($data) {
5780       *     $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5781       * }
5782       *
5783       * @param restore_path_element $element the parent element that the usages are stored inside.
5784       * @param array $paths the paths array that is being built.
5785       * @param string $nameprefix should match the prefix passed to the corresponding
5786       *      backup_questions_activity_structure_step::add_question_usages call.
5787       */
5788      protected function add_question_usages($element, &$paths, $nameprefix = '') {
5789          // Check $element is restore_path_element
5790          if (! $element instanceof restore_path_element) {
5791              throw new restore_step_exception('element_must_be_restore_path_element', $element);
5792          }
5793  
5794          // Check $paths is one array
5795          if (!is_array($paths)) {
5796              throw new restore_step_exception('paths_must_be_array', $paths);
5797          }
5798          $paths[] = new restore_path_element($nameprefix . 'question_usage',
5799                  $element->get_path() . "/{$nameprefix}question_usage");
5800          $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5801                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5802          $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5803                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5804                  true);
5805          $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5806                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5807      }
5808  
5809      /**
5810       * Process question_usages
5811       */
5812      public function process_question_usage($data) {
5813          $this->restore_question_usage_worker($data, '');
5814      }
5815  
5816      /**
5817       * Process question_attempts
5818       */
5819      public function process_question_attempt($data) {
5820          $this->restore_question_attempt_worker($data, '');
5821      }
5822  
5823      /**
5824       * Process question_attempt_steps
5825       */
5826      public function process_question_attempt_step($data) {
5827          $this->restore_question_attempt_step_worker($data, '');
5828      }
5829  
5830      /**
5831       * This method does the actual work for process_question_usage or
5832       * process_{nameprefix}_question_usage.
5833       * @param array $data the data from the XML file.
5834       * @param string $nameprefix the element name prefix.
5835       */
5836      protected function restore_question_usage_worker($data, $nameprefix) {
5837          global $DB;
5838  
5839          // Clear our caches.
5840          $this->qtypes = array();
5841          $this->newquestionids = array();
5842  
5843          $data = (object)$data;
5844          $oldid = $data->id;
5845  
5846          $data->contextid  = $this->task->get_contextid();
5847  
5848          // Everything ready, insert (no mapping needed)
5849          $newitemid = $DB->insert_record('question_usages', $data);
5850  
5851          $this->inform_new_usage_id($newitemid);
5852  
5853          $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
5854      }
5855  
5856      /**
5857       * When process_question_usage creates the new usage, it calls this method
5858       * to let the activity link to the new usage. For example, the quiz uses
5859       * this method to set quiz_attempts.uniqueid to the new usage id.
5860       * @param integer $newusageid
5861       */
5862      abstract protected function inform_new_usage_id($newusageid);
5863  
5864      /**
5865       * This method does the actual work for process_question_attempt or
5866       * process_{nameprefix}_question_attempt.
5867       * @param array $data the data from the XML file.
5868       * @param string $nameprefix the element name prefix.
5869       */
5870      protected function restore_question_attempt_worker($data, $nameprefix) {
5871          global $DB;
5872  
5873          $data = (object)$data;
5874          $oldid = $data->id;
5875  
5876          $questioncreated = $this->get_mappingid('question_created', $data->questionid) ? true : false;
5877          $question = $this->get_mapping('question', $data->questionid);
5878          if ($questioncreated) {
5879              $data->questionid = $question->newitemid;
5880          }
5881  
5882          $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
5883  
5884          if (!property_exists($data, 'variant')) {
5885              $data->variant = 1;
5886          }
5887  
5888          if (!property_exists($data, 'maxfraction')) {
5889              $data->maxfraction = 1;
5890          }
5891  
5892          $newitemid = $DB->insert_record('question_attempts', $data);
5893  
5894          $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
5895          if (isset($question->info->qtype)) {
5896              $qtype = $question->info->qtype;
5897          } else {
5898              $qtype = $DB->get_record('question', ['id' => $data->questionid])->qtype;
5899          }
5900          $this->qtypes[$newitemid] = $qtype;
5901          $this->newquestionids[$newitemid] = $data->questionid;
5902      }
5903  
5904      /**
5905       * This method does the actual work for process_question_attempt_step or
5906       * process_{nameprefix}_question_attempt_step.
5907       * @param array $data the data from the XML file.
5908       * @param string $nameprefix the element name prefix.
5909       */
5910      protected function restore_question_attempt_step_worker($data, $nameprefix) {
5911          global $DB;
5912  
5913          $data = (object)$data;
5914          $oldid = $data->id;
5915  
5916          // Pull out the response data.
5917          $response = array();
5918          if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
5919              foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
5920                  $response[$variable['name']] = $variable['value'];
5921              }
5922          }
5923          unset($data->response);
5924  
5925          $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
5926          $data->userid = $this->get_mappingid('user', $data->userid);
5927  
5928          // Everything ready, insert and create mapping (needed by question_sessions)
5929          $newitemid = $DB->insert_record('question_attempt_steps', $data);
5930          $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
5931  
5932          // Now process the response data.
5933          $response = $this->questions_recode_response_data(
5934                  $this->qtypes[$data->questionattemptid],
5935                  $this->newquestionids[$data->questionattemptid],
5936                  $data->sequencenumber, $response);
5937  
5938          foreach ($response as $name => $value) {
5939              $row = new stdClass();
5940              $row->attemptstepid = $newitemid;
5941              $row->name = $name;
5942              $row->value = $value;
5943              $DB->insert_record('question_attempt_step_data', $row, false);
5944          }
5945      }
5946  
5947      /**
5948       * Recode the respones data for a particular step of an attempt at at particular question.
5949       * @param string $qtype the question type.
5950       * @param int $newquestionid the question id.
5951       * @param int $sequencenumber the sequence number.
5952       * @param array $response the response data to recode.
5953       */
5954      public function questions_recode_response_data(
5955              $qtype, $newquestionid, $sequencenumber, array $response) {
5956          $qtyperestorer = $this->get_qtype_restorer($qtype);
5957          if ($qtyperestorer) {
5958              $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
5959          }
5960          return $response;
5961      }
5962  
5963      /**
5964       * Given a list of question->ids, separated by commas, returns the
5965       * recoded list, with all the restore question mappings applied.
5966       * Note: Used by quiz->questions and quiz_attempts->layout
5967       * Note: 0 = page break (unconverted)
5968       */
5969      protected function questions_recode_layout($layout) {
5970          // Extracts question id from sequence
5971          if ($questionids = explode(',', $layout)) {
5972              foreach ($questionids as $id => $questionid) {
5973                  if ($questionid) { // If it is zero then this is a pagebreak, don't translate
5974                      $newquestionid = $this->get_mappingid('question', $questionid);
5975                      $questionids[$id] = $newquestionid;
5976                  }
5977              }
5978          }
5979          return implode(',', $questionids);
5980      }
5981  
5982      /**
5983       * Get the restore_qtype_plugin subclass for a specific question type.
5984       * @param string $qtype e.g. multichoice.
5985       * @return restore_qtype_plugin instance.
5986       */
5987      protected function get_qtype_restorer($qtype) {
5988          // Build one static cache to store {@link restore_qtype_plugin}
5989          // while we are needing them, just to save zillions of instantiations
5990          // or using static stuff that will break our nice API
5991          static $qtypeplugins = array();
5992  
5993          if (!isset($qtypeplugins[$qtype])) {
5994              $classname = 'restore_qtype_' . $qtype . '_plugin';
5995              if (class_exists($classname)) {
5996                  $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
5997              } else {
5998                  $qtypeplugins[$qtype] = null;
5999              }
6000          }
6001          return $qtypeplugins[$qtype];
6002      }
6003  
6004      protected function after_execute() {
6005          parent::after_execute();
6006  
6007          // Restore any files belonging to responses.
6008          foreach (question_engine::get_all_response_file_areas() as $filearea) {
6009              $this->add_related_files('question', $filearea, 'question_attempt_step');
6010          }
6011      }
6012  }
6013  
6014  /**
6015   * Helper trait to restore question reference data.
6016   */
6017  trait restore_question_reference_data_trait {
6018  
6019      /**
6020       * Attach the question reference data to the restore.
6021       *
6022       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6023       * @param array $paths the paths array that is being built to describe the structure.
6024       */
6025      protected function add_question_references($element, &$paths) {
6026          // Check $element is restore_path_element.
6027          if (! $element instanceof restore_path_element) {
6028              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6029          }
6030  
6031          // Check $paths is one array.
6032          if (!is_array($paths)) {
6033              throw new restore_step_exception('paths_must_be_array', $paths);
6034          }
6035  
6036          $paths[] = new restore_path_element('question_reference',
6037              $element->get_path() . '/question_reference');
6038      }
6039  
6040      /**
6041       * Process question references which replaces the direct connection to quiz slots to question.
6042       *
6043       * @param array $data the data from the XML file.
6044       */
6045      public function process_question_reference($data) {
6046          global $DB;
6047          $data = (object) $data;
6048          $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6049          $data->itemid = $this->get_new_parentid('quiz_question_instance');
6050          if ($entry = $this->get_mappingid('question_bank_entry', $data->questionbankentryid)) {
6051              $data->questionbankentryid = $entry;
6052          }
6053          $DB->insert_record('question_references', $data);
6054      }
6055  }
6056  
6057  /**
6058   * Helper trait to restore question set reference data.
6059   */
6060  trait restore_question_set_reference_data_trait {
6061  
6062      /**
6063       * Attach the question reference data to the restore.
6064       *
6065       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6066       * @param array $paths the paths array that is being built to describe the structure.
6067       */
6068      protected function add_question_set_references($element, &$paths) {
6069          // Check $element is restore_path_element.
6070          if (! $element instanceof restore_path_element) {
6071              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6072          }
6073  
6074          // Check $paths is one array.
6075          if (!is_array($paths)) {
6076              throw new restore_step_exception('paths_must_be_array', $paths);
6077          }
6078  
6079          $paths[] = new restore_path_element('question_set_reference',
6080              $element->get_path() . '/question_set_reference');
6081      }
6082  
6083      /**
6084       * Process question set references data which replaces the random qtype.
6085       *
6086       * @param array $data the data from the XML file.
6087       */
6088      public function process_question_set_reference($data) {
6089          global $DB;
6090          $data = (object) $data;
6091          $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6092          $data->itemid = $this->get_new_parentid('quiz_question_instance');
6093          $filtercondition = json_decode($data->filtercondition);
6094          if ($category = $this->get_mappingid('question_category', $filtercondition->questioncategoryid)) {
6095              $filtercondition->questioncategoryid = $category;
6096          }
6097          $data->filtercondition = json_encode($filtercondition);
6098          if ($context = $this->get_mappingid('context', $data->questionscontextid)) {
6099              $data->questionscontextid = $context;
6100          }
6101  
6102          $DB->insert_record('question_set_references', $data);
6103      }
6104  }
6105  
6106  
6107  /**
6108   * Abstract structure step to help activities that store question attempt data.
6109   *
6110   * @copyright 2011 The Open University
6111   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6112   */
6113  abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
6114      use restore_questions_attempt_data_trait;
6115      use restore_question_reference_data_trait;
6116      use restore_question_set_reference_data_trait;
6117  
6118      /**
6119       * Attach below $element (usually attempts) the needed restore_path_elements
6120       * to restore question attempt data from Moodle 2.0.
6121       *
6122       * When using this method, the parent element ($element) must be defined with
6123       * $grouped = true. Then, in that elements process method, you must call
6124       * {@link process_legacy_attempt_data()} with the groupded data. See, for
6125       * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
6126       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6127       * @param array $paths the paths array that is being built to describe the
6128       *      structure.
6129       */
6130      protected function add_legacy_question_attempt_data($element, &$paths) {
6131          global $CFG;
6132          require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
6133  
6134          // Check $element is restore_path_element
6135          if (!($element instanceof restore_path_element)) {
6136              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6137          }
6138          // Check $paths is one array
6139          if (!is_array($paths)) {
6140              throw new restore_step_exception('paths_must_be_array', $paths);
6141          }
6142  
6143          $paths[] = new restore_path_element('question_state',
6144                  $element->get_path() . '/states/state');
6145          $paths[] = new restore_path_element('question_session',
6146                  $element->get_path() . '/sessions/session');
6147      }
6148  
6149      protected function get_attempt_upgrader() {
6150          if (empty($this->attemptupgrader)) {
6151              $this->attemptupgrader = new question_engine_attempt_upgrader();
6152              $this->attemptupgrader->prepare_to_restore();
6153          }
6154          return $this->attemptupgrader;
6155      }
6156  
6157      /**
6158       * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
6159       * @param object $data contains all the grouped attempt data to process.
6160       * @param object $quiz data about the activity the attempts belong to. Required
6161       * fields are (basically this only works for the quiz module):
6162       *      oldquestions => list of question ids in this activity - using old ids.
6163       *      preferredbehaviour => the behaviour to use for questionattempts.
6164       */
6165      protected function process_legacy_quiz_attempt_data($data, $quiz) {
6166          global $DB;
6167          $upgrader = $this->get_attempt_upgrader();
6168  
6169          $data = (object)$data;
6170  
6171          $layout = explode(',', $data->layout);
6172          $newlayout = $layout;
6173  
6174          // Convert each old question_session into a question_attempt.
6175          $qas = array();
6176          foreach (explode(',', $quiz->oldquestions) as $questionid) {
6177              if ($questionid == 0) {
6178                  continue;
6179              }
6180  
6181              $newquestionid = $this->get_mappingid('question', $questionid);
6182              if (!$newquestionid) {
6183                  throw new restore_step_exception('questionattemptreferstomissingquestion',
6184                          $questionid, $questionid);
6185              }
6186  
6187              $question = $upgrader->load_question($newquestionid, $quiz->id);
6188  
6189              foreach ($layout as $key => $qid) {
6190                  if ($qid == $questionid) {
6191                      $newlayout[$key] = $newquestionid;
6192                  }
6193              }
6194  
6195              list($qsession, $qstates) = $this->find_question_session_and_states(
6196                      $data, $questionid);
6197  
6198              if (empty($qsession) || empty($qstates)) {
6199                  throw new restore_step_exception('questionattemptdatamissing',
6200                          $questionid, $questionid);
6201              }
6202  
6203              list($qsession, $qstates) = $this->recode_legacy_response_data(
6204                      $question, $qsession, $qstates);
6205  
6206              $data->layout = implode(',', $newlayout);
6207              $qas[$newquestionid] = $upgrader->convert_question_attempt(
6208                      $quiz, $data, $question, $qsession, $qstates);
6209          }
6210  
6211          // Now create a new question_usage.
6212          $usage = new stdClass();
6213          $usage->component = 'mod_quiz';
6214          $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
6215          $usage->preferredbehaviour = $quiz->preferredbehaviour;
6216          $usage->id = $DB->insert_record('question_usages', $usage);
6217  
6218          $this->inform_new_usage_id($usage->id);
6219  
6220          $data->uniqueid = $usage->id;
6221          $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
6222                  $this->questions_recode_layout($quiz->oldquestions));
6223      }
6224  
6225      protected function find_question_session_and_states($data, $questionid) {
6226          $qsession = null;
6227          foreach ($data->sessions['session'] as $session) {
6228              if ($session['questionid'] == $questionid) {
6229                  $qsession = (object) $session;
6230                  break;
6231              }
6232          }
6233  
6234          $qstates = array();
6235          foreach ($data->states['state'] as $state) {
6236              if ($state['question'] == $questionid) {
6237                  // It would be natural to use $state['seq_number'] as the array-key
6238                  // here, but it seems that buggy behaviour in 2.0 and early can
6239                  // mean that that is not unique, so we use id, which is guaranteed
6240                  // to be unique.
6241                  $qstates[$state['id']] = (object) $state;
6242              }
6243          }
6244          ksort($qstates);
6245          $qstates = array_values($qstates);
6246  
6247          return array($qsession, $qstates);
6248      }
6249  
6250      /**
6251       * Recode any ids in the response data
6252       * @param object $question the question data
6253       * @param object $qsession the question sessions.
6254       * @param array $qstates the question states.
6255       */
6256      protected function recode_legacy_response_data($question, $qsession, $qstates) {
6257          $qsession->questionid = $question->id;
6258  
6259          foreach ($qstates as &$state) {
6260              $state->question = $question->id;
6261              $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
6262          }
6263  
6264          return array($qsession, $qstates);
6265      }
6266  
6267      /**
6268       * Recode the legacy answer field.
6269       * @param object $state the state to recode the answer of.
6270       * @param string $qtype the question type.
6271       */
6272      public function restore_recode_legacy_answer($state, $qtype) {
6273          $restorer = $this->get_qtype_restorer($qtype);
6274          if ($restorer) {
6275              return $restorer->recode_legacy_state_answer($state);
6276          } else {
6277              return $state->answer;
6278          }
6279      }
6280  }
6281  
6282  
6283  /**
6284   * Restore completion defaults for each module type
6285   *
6286   * @package     core_backup
6287   * @copyright   2017 Marina Glancy
6288   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6289   */
6290  class restore_completion_defaults_structure_step extends restore_structure_step {
6291      /**
6292       * To conditionally decide if this step must be executed.
6293       */
6294      protected function execute_condition() {
6295          // No completion on the front page.
6296          if ($this->get_courseid() == SITEID) {
6297              return false;
6298          }
6299  
6300          // No default completion info found, don't execute.
6301          $fullpath = $this->task->get_taskbasepath();
6302          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
6303          if (!file_exists($fullpath)) {
6304              return false;
6305          }
6306  
6307          // Arrived here, execute the step.
6308          return true;
6309      }
6310  
6311      /**
6312       * Function that will return the structure to be processed by this restore_step.
6313       *
6314       * @return restore_path_element[]
6315       */
6316      protected function define_structure() {
6317          return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
6318      }
6319  
6320      /**
6321       * Processor for path element 'completion_defaults'
6322       *
6323       * @param stdClass|array $data
6324       */
6325      protected function process_completion_defaults($data) {
6326          global $DB;
6327  
6328          $data = (array)$data;
6329          $oldid = $data['id'];
6330          unset($data['id']);
6331  
6332          // Find the module by name since id may be different in another site.
6333          if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
6334              return;
6335          }
6336          unset($data['modulename']);
6337  
6338          // Find the existing record.
6339          $newid = $DB->get_field('course_completion_defaults', 'id',
6340              ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
6341          if (!$newid) {
6342              $newid = $DB->insert_record('course_completion_defaults',
6343                  ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
6344          } else {
6345              $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
6346          }
6347  
6348          // Save id mapping for restoring associated events.
6349          $this->set_mapping('course_completion_defaults', $oldid, $newid);
6350      }
6351  }
6352  
6353  /**
6354   * Index course after restore.
6355   *
6356   * @package core_backup
6357   * @copyright 2017 The Open University
6358   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6359   */
6360  class restore_course_search_index extends restore_execution_step {
6361      /**
6362       * When this step is executed, we add the course context to the queue for reindexing.
6363       */
6364      protected function define_execution() {
6365          $context = \context_course::instance($this->task->get_courseid());
6366          \core_search\manager::request_index($context);
6367      }
6368  }
6369  
6370  /**
6371   * Index activity after restore (when not restoring whole course).
6372   *
6373   * @package core_backup
6374   * @copyright 2017 The Open University
6375   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6376   */
6377  class restore_activity_search_index extends restore_execution_step {
6378      /**
6379       * When this step is executed, we add the activity context to the queue for reindexing.
6380       */
6381      protected function define_execution() {
6382          $context = \context::instance_by_id($this->task->get_contextid());
6383          \core_search\manager::request_index($context);
6384      }
6385  }
6386  
6387  /**
6388   * Index block after restore (when not restoring whole course).
6389   *
6390   * @package core_backup
6391   * @copyright 2017 The Open University
6392   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6393   */
6394  class restore_block_search_index extends restore_execution_step {
6395      /**
6396       * When this step is executed, we add the block context to the queue for reindexing.
6397       */
6398      protected function define_execution() {
6399          // A block in the restore list may be skipped because a duplicate is detected.
6400          // In this case, there is no new blockid (or context) to get.
6401          if (!empty($this->task->get_blockid())) {
6402              $context = \context_block::instance($this->task->get_blockid());
6403              \core_search\manager::request_index($context);
6404          }
6405      }
6406  }
6407  
6408  /**
6409   * Restore action events.
6410   *
6411   * @package     core_backup
6412   * @copyright   2017 onwards Ankit Agarwal
6413   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6414   */
6415  class restore_calendar_action_events extends restore_execution_step {
6416      /**
6417       * What to do when this step is executed.
6418       */
6419      protected function define_execution() {
6420          // We just queue the task here rather trying to recreate everything manually.
6421          // The task will automatically populate all data.
6422          $task = new \core\task\refresh_mod_calendar_events_task();
6423          $task->set_custom_data(array('courseid' => $this->get_courseid()));
6424          \core\task\manager::queue_adhoc_task($task, true);
6425      }
6426  }