Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 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              $record->overridegrade = $data->overridegrade;
3750              $coursemodulecompetency = new \core_competency\course_module_competency(0, $record);
3751              $coursemodulecompetency->create();
3752          }
3753      }
3754  
3755      /**
3756       * Execute conditions.
3757       *
3758       * @return bool
3759       */
3760      protected function execute_condition() {
3761  
3762          // Do not execute if competencies are not included.
3763          if (!$this->get_setting_value('competencies')) {
3764              return false;
3765          }
3766  
3767          // Do not execute if the competencies XML file is not found.
3768          $fullpath = $this->task->get_taskbasepath();
3769          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3770          if (!file_exists($fullpath)) {
3771              return false;
3772          }
3773  
3774          return true;
3775      }
3776  }
3777  
3778  /**
3779   * Defines the restore step for advanced grading methods attached to the activity module
3780   */
3781  class restore_activity_grading_structure_step extends restore_structure_step {
3782  
3783      /**
3784       * This step is executed only if the grading file is present
3785       */
3786       protected function execute_condition() {
3787  
3788          if ($this->get_courseid() == SITEID) {
3789              return false;
3790          }
3791  
3792          $fullpath = $this->task->get_taskbasepath();
3793          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
3794          if (!file_exists($fullpath)) {
3795              return false;
3796          }
3797  
3798          return true;
3799      }
3800  
3801  
3802      /**
3803       * Declares paths in the grading.xml file we are interested in
3804       */
3805      protected function define_structure() {
3806  
3807          $paths = array();
3808          $userinfo = $this->get_setting_value('userinfo');
3809  
3810          $area = new restore_path_element('grading_area', '/areas/area');
3811          $paths[] = $area;
3812          // attach local plugin stucture to $area element
3813          $this->add_plugin_structure('local', $area);
3814  
3815          $definition = new restore_path_element('grading_definition', '/areas/area/definitions/definition');
3816          $paths[] = $definition;
3817          $this->add_plugin_structure('gradingform', $definition);
3818          // attach local plugin stucture to $definition element
3819          $this->add_plugin_structure('local', $definition);
3820  
3821  
3822          if ($userinfo) {
3823              $instance = new restore_path_element('grading_instance',
3824                  '/areas/area/definitions/definition/instances/instance');
3825              $paths[] = $instance;
3826              $this->add_plugin_structure('gradingform', $instance);
3827              // attach local plugin stucture to $intance element
3828              $this->add_plugin_structure('local', $instance);
3829          }
3830  
3831          return $paths;
3832      }
3833  
3834      /**
3835       * Processes one grading area element
3836       *
3837       * @param array $data element data
3838       */
3839      protected function process_grading_area($data) {
3840          global $DB;
3841  
3842          $task = $this->get_task();
3843          $data = (object)$data;
3844          $oldid = $data->id;
3845          $data->component = 'mod_'.$task->get_modulename();
3846          $data->contextid = $task->get_contextid();
3847  
3848          $newid = $DB->insert_record('grading_areas', $data);
3849          $this->set_mapping('grading_area', $oldid, $newid);
3850      }
3851  
3852      /**
3853       * Processes one grading definition element
3854       *
3855       * @param array $data element data
3856       */
3857      protected function process_grading_definition($data) {
3858          global $DB;
3859  
3860          $task = $this->get_task();
3861          $data = (object)$data;
3862          $oldid = $data->id;
3863          $data->areaid = $this->get_new_parentid('grading_area');
3864          $data->copiedfromid = null;
3865          $data->timecreated = time();
3866          $data->usercreated = $task->get_userid();
3867          $data->timemodified = $data->timecreated;
3868          $data->usermodified = $data->usercreated;
3869  
3870          $newid = $DB->insert_record('grading_definitions', $data);
3871          $this->set_mapping('grading_definition', $oldid, $newid, true);
3872      }
3873  
3874      /**
3875       * Processes one grading form instance element
3876       *
3877       * @param array $data element data
3878       */
3879      protected function process_grading_instance($data) {
3880          global $DB;
3881  
3882          $data = (object)$data;
3883  
3884          // new form definition id
3885          $newformid = $this->get_new_parentid('grading_definition');
3886  
3887          // get the name of the area we are restoring to
3888          $sql = "SELECT ga.areaname
3889                    FROM {grading_definitions} gd
3890                    JOIN {grading_areas} ga ON gd.areaid = ga.id
3891                   WHERE gd.id = ?";
3892          $areaname = $DB->get_field_sql($sql, array($newformid), MUST_EXIST);
3893  
3894          // get the mapped itemid - the activity module is expected to define the mappings
3895          // for each gradable area
3896          $newitemid = $this->get_mappingid(restore_gradingform_plugin::itemid_mapping($areaname), $data->itemid);
3897  
3898          $oldid = $data->id;
3899          $data->definitionid = $newformid;
3900          $data->raterid = $this->get_mappingid('user', $data->raterid);
3901          $data->itemid = $newitemid;
3902  
3903          $newid = $DB->insert_record('grading_instances', $data);
3904          $this->set_mapping('grading_instance', $oldid, $newid);
3905      }
3906  
3907      /**
3908       * Final operations when the database records are inserted
3909       */
3910      protected function after_execute() {
3911          // Add files embedded into the definition description
3912          $this->add_related_files('grading', 'description', 'grading_definition');
3913      }
3914  }
3915  
3916  
3917  /**
3918   * This structure step restores the grade items associated with one activity
3919   * All the grade items are made child of the "course" grade item but the original
3920   * categoryid is saved as parentitemid in the backup_ids table, so, when restoring
3921   * the complete gradebook (categories and calculations), that information is
3922   * available there
3923   */
3924  class restore_activity_grades_structure_step extends restore_structure_step {
3925  
3926      /**
3927       * No grades in front page.
3928       * @return bool
3929       */
3930      protected function execute_condition() {
3931          return ($this->get_courseid() != SITEID);
3932      }
3933  
3934      protected function define_structure() {
3935  
3936          $paths = array();
3937          $userinfo = $this->get_setting_value('userinfo');
3938  
3939          $paths[] = new restore_path_element('grade_item', '/activity_gradebook/grade_items/grade_item');
3940          $paths[] = new restore_path_element('grade_letter', '/activity_gradebook/grade_letters/grade_letter');
3941          if ($userinfo) {
3942              $paths[] = new restore_path_element('grade_grade',
3943                             '/activity_gradebook/grade_items/grade_item/grade_grades/grade_grade');
3944          }
3945          return $paths;
3946      }
3947  
3948      protected function process_grade_item($data) {
3949          global $DB;
3950  
3951          $data = (object)($data);
3952          $oldid       = $data->id;        // We'll need these later
3953          $oldparentid = $data->categoryid;
3954          $courseid = $this->get_courseid();
3955  
3956          $idnumber = null;
3957          if (!empty($data->idnumber)) {
3958              // Don't get any idnumber from course module. Keep them as they are in grade_item->idnumber
3959              // Reason: it's not clear what happens with outcomes->idnumber or activities with multiple items (workshop)
3960              // so the best is to keep the ones already in the gradebook
3961              // Potential problem: duplicates if same items are restored more than once. :-(
3962              // This needs to be fixed in some way (outcomes & activities with multiple items)
3963              // $data->idnumber     = get_coursemodule_from_instance($data->itemmodule, $data->iteminstance)->idnumber;
3964              // In any case, verify always for uniqueness
3965              $sql = "SELECT cm.id
3966                        FROM {course_modules} cm
3967                       WHERE cm.course = :courseid AND
3968                             cm.idnumber = :idnumber AND
3969                             cm.id <> :cmid";
3970              $params = array(
3971                  'courseid' => $courseid,
3972                  'idnumber' => $data->idnumber,
3973                  'cmid' => $this->task->get_moduleid()
3974              );
3975              if (!$DB->record_exists_sql($sql, $params) && !$DB->record_exists('grade_items', array('courseid' => $courseid, 'idnumber' => $data->idnumber))) {
3976                  $idnumber = $data->idnumber;
3977              }
3978          }
3979  
3980          if (!empty($data->categoryid)) {
3981              // If the grade category id of the grade item being restored belongs to this course
3982              // then it is a fair assumption that this is the correct grade category for the activity
3983              // and we should leave it in place, if not then unset it.
3984              // TODO MDL-34790 Gradebook does not import if target course has gradebook categories.
3985              $conditions = array('id' => $data->categoryid, 'courseid' => $courseid);
3986              if (!$this->task->is_samesite() || !$DB->record_exists('grade_categories', $conditions)) {
3987                  unset($data->categoryid);
3988              }
3989          }
3990  
3991          unset($data->id);
3992          $data->courseid     = $this->get_courseid();
3993          $data->iteminstance = $this->task->get_activityid();
3994          $data->idnumber     = $idnumber;
3995          $data->scaleid      = $this->get_mappingid('scale', $data->scaleid);
3996          $data->outcomeid    = $this->get_mappingid('outcome', $data->outcomeid);
3997  
3998          $gradeitem = new grade_item($data, false);
3999          $gradeitem->insert('restore');
4000  
4001          //sortorder is automatically assigned when inserting. Re-instate the previous sortorder
4002          $gradeitem->sortorder = $data->sortorder;
4003          $gradeitem->update('restore');
4004  
4005          // Set mapping, saving the original category id into parentitemid
4006          // gradebook restore (final task) will need it to reorganise items
4007          $this->set_mapping('grade_item', $oldid, $gradeitem->id, false, null, $oldparentid);
4008      }
4009  
4010      protected function process_grade_grade($data) {
4011          global $CFG;
4012  
4013          require_once($CFG->libdir . '/grade/constants.php');
4014  
4015          $data = (object)($data);
4016          $olduserid = $data->userid;
4017          $oldid = $data->id;
4018          unset($data->id);
4019  
4020          $data->itemid = $this->get_new_parentid('grade_item');
4021  
4022          $data->userid = $this->get_mappingid('user', $data->userid, null);
4023          if (!empty($data->userid)) {
4024              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4025              $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4026  
4027              $grade = new grade_grade($data, false);
4028              $grade->insert('restore');
4029  
4030              $this->set_mapping('grade_grades', $oldid, $grade->id, true);
4031  
4032              $this->add_related_files(
4033                  GRADE_FILE_COMPONENT,
4034                  GRADE_FEEDBACK_FILEAREA,
4035                  'grade_grades',
4036                  null,
4037                  $oldid
4038              );
4039          } else {
4040              debugging("Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'");
4041          }
4042      }
4043  
4044      /**
4045       * process activity grade_letters. Note that, while these are possible,
4046       * because grade_letters are contextid based, in practice, only course
4047       * context letters can be defined. So we keep here this method knowing
4048       * it won't be executed ever. gradebook restore will restore course letters.
4049       */
4050      protected function process_grade_letter($data) {
4051          global $DB;
4052  
4053          $data['contextid'] = $this->task->get_contextid();
4054          $gradeletter = (object)$data;
4055  
4056          // Check if it exists before adding it
4057          unset($data['id']);
4058          if (!$DB->record_exists('grade_letters', $data)) {
4059              $newitemid = $DB->insert_record('grade_letters', $gradeletter);
4060          }
4061          // no need to save any grade_letter mapping
4062      }
4063  
4064      public function after_restore() {
4065          // Fix grade item's sortorder after restore, as it might have duplicates.
4066          $courseid = $this->get_task()->get_courseid();
4067          grade_item::fix_duplicate_sortorder($courseid);
4068      }
4069  }
4070  
4071  /**
4072   * Step in charge of restoring the grade history of an activity.
4073   *
4074   * This step is added to the task regardless of the setting 'grade_histories'.
4075   * The reason is to allow for a more flexible step in case the logic needs to be
4076   * split accross different settings to control the history of items and/or grades.
4077   */
4078  class restore_activity_grade_history_structure_step extends restore_structure_step {
4079  
4080      /**
4081       * This step is executed only if the grade history file is present.
4082       */
4083       protected function execute_condition() {
4084  
4085          if ($this->get_courseid() == SITEID) {
4086              return false;
4087          }
4088  
4089          $fullpath = $this->task->get_taskbasepath();
4090          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4091          if (!file_exists($fullpath)) {
4092              return false;
4093          }
4094          return true;
4095      }
4096  
4097      protected function define_structure() {
4098          $paths = array();
4099  
4100          // Settings to use.
4101          $userinfo = $this->get_setting_value('userinfo');
4102          $history = $this->get_setting_value('grade_histories');
4103  
4104          if ($userinfo && $history) {
4105              $paths[] = new restore_path_element('grade_grade',
4106                 '/grade_history/grade_grades/grade_grade');
4107          }
4108  
4109          return $paths;
4110      }
4111  
4112      protected function process_grade_grade($data) {
4113          global $CFG, $DB;
4114  
4115          require_once($CFG->libdir . '/grade/constants.php');
4116  
4117          $data = (object) $data;
4118          $oldhistoryid = $data->id;
4119          $olduserid = $data->userid;
4120          unset($data->id);
4121  
4122          $data->userid = $this->get_mappingid('user', $data->userid, null);
4123          if (!empty($data->userid)) {
4124              // Do not apply the date offsets as this is history.
4125              $data->itemid = $this->get_mappingid('grade_item', $data->itemid);
4126              $data->oldid = $this->get_mappingid('grade_grades', $data->oldid);
4127              $data->usermodified = $this->get_mappingid('user', $data->usermodified, null);
4128              $data->rawscaleid = $this->get_mappingid('scale', $data->rawscaleid);
4129  
4130              $newhistoryid = $DB->insert_record('grade_grades_history', $data);
4131  
4132              $this->set_mapping('grade_grades_history', $oldhistoryid, $newhistoryid, true);
4133  
4134              $this->add_related_files(
4135                  GRADE_FILE_COMPONENT,
4136                  GRADE_HISTORY_FEEDBACK_FILEAREA,
4137                  'grade_grades_history',
4138                  null,
4139                  $oldhistoryid
4140              );
4141          } else {
4142              $message = "Mapped user id not found for user id '{$olduserid}', grade item id '{$data->itemid}'";
4143              $this->log($message, backup::LOG_DEBUG);
4144          }
4145      }
4146  }
4147  
4148  /**
4149   * This structure steps restores the content bank content
4150   */
4151  class restore_contentbankcontent_structure_step extends restore_structure_step {
4152  
4153      /**
4154       * Define structure for content bank step
4155       */
4156      protected function define_structure() {
4157  
4158          $paths = [];
4159          $paths[] = new restore_path_element('contentbankcontent', '/contents/content');
4160  
4161          return $paths;
4162      }
4163  
4164      /**
4165       * Define data processed for content bank
4166       *
4167       * @param mixed  $data
4168       */
4169      public function process_contentbankcontent($data) {
4170          global $DB;
4171  
4172          $data = (object)$data;
4173          $oldid = $data->id;
4174  
4175          $params = [
4176              'name'           => $data->name,
4177              'contextid'      => $this->task->get_contextid(),
4178              'contenttype'    => $data->contenttype,
4179              'instanceid'     => $data->instanceid,
4180              'timecreated'    => $data->timecreated,
4181          ];
4182          $exists = $DB->record_exists('contentbank_content', $params);
4183          if (!$exists) {
4184              $params['configdata'] = $data->configdata;
4185              $params['timemodified'] = time();
4186  
4187              // Trying to map users. Users cannot always be mapped, e.g. when copying.
4188              $params['usercreated'] = $this->get_mappingid('user', $data->usercreated);
4189              if (!$params['usercreated']) {
4190                  // Leave the content creator unchanged when we are restoring the same site.
4191                  // Otherwise use current user id.
4192                  if ($this->task->is_samesite()) {
4193                      $params['usercreated'] = $data->usercreated;
4194                  } else {
4195                      $params['usercreated'] = $this->task->get_userid();
4196                  }
4197              }
4198              $params['usermodified'] = $this->get_mappingid('user', $data->usermodified);
4199              if (!$params['usermodified']) {
4200                  // Leave the content modifier unchanged when we are restoring the same site.
4201                  // Otherwise use current user id.
4202                  if ($this->task->is_samesite()) {
4203                      $params['usermodified'] = $data->usermodified;
4204                  } else {
4205                      $params['usermodified'] = $this->task->get_userid();
4206                  }
4207              }
4208  
4209              $newitemid = $DB->insert_record('contentbank_content', $params);
4210              $this->set_mapping('contentbank_content', $oldid, $newitemid, true);
4211          }
4212      }
4213  
4214      /**
4215       * Define data processed after execute for content bank
4216       */
4217      protected function after_execute() {
4218          // Add related files.
4219          $this->add_related_files('contentbank', 'public', 'contentbank_content');
4220      }
4221  }
4222  
4223  /**
4224   * This structure steps restores one instance + positions of one block
4225   * Note: Positions corresponding to one existing context are restored
4226   * here, but all the ones having unknown contexts are sent to backup_ids
4227   * for a later chance to be restored at the end (final task)
4228   */
4229  class restore_block_instance_structure_step extends restore_structure_step {
4230  
4231      protected function define_structure() {
4232  
4233          $paths = array();
4234  
4235          $paths[] = new restore_path_element('block', '/block', true); // Get the whole XML together
4236          $paths[] = new restore_path_element('block_position', '/block/block_positions/block_position');
4237  
4238          return $paths;
4239      }
4240  
4241      public function process_block($data) {
4242          global $DB, $CFG;
4243  
4244          $data = (object)$data; // Handy
4245          $oldcontextid = $data->contextid;
4246          $oldid        = $data->id;
4247          $positions = isset($data->block_positions['block_position']) ? $data->block_positions['block_position'] : array();
4248  
4249          // Look for the parent contextid
4250          if (!$data->parentcontextid = $this->get_mappingid('context', $data->parentcontextid)) {
4251              // Parent contextid does not exist, ignore this block.
4252              return false;
4253          }
4254  
4255          // TODO: it would be nice to use standard plugin supports instead of this instance_allow_multiple()
4256          // If there is already one block of that type in the parent context
4257          // and the block is not multiple, stop processing
4258          // Use blockslib loader / method executor
4259          if (!$bi = block_instance($data->blockname)) {
4260              return false;
4261          }
4262  
4263          if (!$bi->instance_allow_multiple()) {
4264              // The block cannot be added twice, so we will check if the same block is already being
4265              // displayed on the same page. For this, rather than mocking a page and using the block_manager
4266              // we use a similar query to the one in block_manager::load_blocks(), this will give us
4267              // a very good idea of the blocks already displayed in the context.
4268              $params =  array(
4269                  'blockname' => $data->blockname
4270              );
4271  
4272              // Context matching test.
4273              $context = context::instance_by_id($data->parentcontextid);
4274              $contextsql = 'bi.parentcontextid = :contextid';
4275              $params['contextid'] = $context->id;
4276  
4277              $parentcontextids = $context->get_parent_context_ids();
4278              if ($parentcontextids) {
4279                  list($parentcontextsql, $parentcontextparams) =
4280                          $DB->get_in_or_equal($parentcontextids, SQL_PARAMS_NAMED);
4281                  $contextsql = "($contextsql OR (bi.showinsubcontexts = 1 AND bi.parentcontextid $parentcontextsql))";
4282                  $params = array_merge($params, $parentcontextparams);
4283              }
4284  
4285              // Page type pattern test.
4286              $pagetypepatterns = matching_page_type_patterns_from_pattern($data->pagetypepattern);
4287              list($pagetypepatternsql, $pagetypepatternparams) =
4288                  $DB->get_in_or_equal($pagetypepatterns, SQL_PARAMS_NAMED);
4289              $params = array_merge($params, $pagetypepatternparams);
4290  
4291              // Sub page pattern test.
4292              $subpagepatternsql = 'bi.subpagepattern IS NULL';
4293              if ($data->subpagepattern !== null) {
4294                  $subpagepatternsql = "($subpagepatternsql OR bi.subpagepattern = :subpagepattern)";
4295                  $params['subpagepattern'] = $data->subpagepattern;
4296              }
4297  
4298              $existingblock = $DB->get_records_sql("SELECT bi.id
4299                                                  FROM {block_instances} bi
4300                                                  JOIN {block} b ON b.name = bi.blockname
4301                                                 WHERE bi.blockname = :blockname
4302                                                   AND $contextsql
4303                                                   AND bi.pagetypepattern $pagetypepatternsql
4304                                                   AND $subpagepatternsql", $params);
4305              if (!empty($existingblock)) {
4306                  // Save the context mapping in case something else is linking to this block's context.
4307                  $newcontext = context_block::instance(reset($existingblock)->id);
4308                  $this->set_mapping('context', $oldcontextid, $newcontext->id);
4309                  // There is at least one very similar block visible on the page where we
4310                  // are trying to restore the block. In these circumstances the block API
4311                  // would not allow the user to add another instance of the block, so we
4312                  // apply the same rule here.
4313                  return false;
4314              }
4315          }
4316  
4317          // If there is already one block of that type in the parent context
4318          // with the same showincontexts, pagetypepattern, subpagepattern, defaultregion and configdata
4319          // stop processing
4320          $params = array(
4321              'blockname' => $data->blockname, 'parentcontextid' => $data->parentcontextid,
4322              'showinsubcontexts' => $data->showinsubcontexts, 'pagetypepattern' => $data->pagetypepattern,
4323              'subpagepattern' => $data->subpagepattern, 'defaultregion' => $data->defaultregion);
4324          if ($birecs = $DB->get_records('block_instances', $params)) {
4325              foreach($birecs as $birec) {
4326                  if ($birec->configdata == $data->configdata) {
4327                      // Save the context mapping in case something else is linking to this block's context.
4328                      $newcontext = context_block::instance($birec->id);
4329                      $this->set_mapping('context', $oldcontextid, $newcontext->id);
4330                      return false;
4331                  }
4332              }
4333          }
4334  
4335          // Set task old contextid, blockid and blockname once we know them
4336          $this->task->set_old_contextid($oldcontextid);
4337          $this->task->set_old_blockid($oldid);
4338          $this->task->set_blockname($data->blockname);
4339  
4340          // Let's look for anything within configdata neededing processing
4341          // (nulls and uses of legacy file.php)
4342          if ($attrstotransform = $this->task->get_configdata_encoded_attributes()) {
4343              $configdata = array_filter(
4344                  (array) unserialize_object(base64_decode($data->configdata)),
4345                  static function($value): bool {
4346                      return !($value instanceof __PHP_Incomplete_Class);
4347                  }
4348              );
4349  
4350              foreach ($configdata as $attribute => $value) {
4351                  if (in_array($attribute, $attrstotransform)) {
4352                      $configdata[$attribute] = $this->contentprocessor->process_cdata($value);
4353                  }
4354              }
4355              $data->configdata = base64_encode(serialize((object)$configdata));
4356          }
4357  
4358          // Set timecreated, timemodified if not included (older backup).
4359          if (empty($data->timecreated)) {
4360              $data->timecreated = time();
4361          }
4362          if (empty($data->timemodified)) {
4363              $data->timemodified = $data->timecreated;
4364          }
4365  
4366          // Create the block instance
4367          $newitemid = $DB->insert_record('block_instances', $data);
4368          // Save the mapping (with restorefiles support)
4369          $this->set_mapping('block_instance', $oldid, $newitemid, true);
4370          // Create the block context
4371          $newcontextid = context_block::instance($newitemid)->id;
4372          // Save the block contexts mapping and sent it to task
4373          $this->set_mapping('context', $oldcontextid, $newcontextid);
4374          $this->task->set_contextid($newcontextid);
4375          $this->task->set_blockid($newitemid);
4376  
4377          // Restore block fileareas if declared
4378          $component = 'block_' . $this->task->get_blockname();
4379          foreach ($this->task->get_fileareas() as $filearea) { // Simple match by contextid. No itemname needed
4380              $this->add_related_files($component, $filearea, null);
4381          }
4382  
4383          // Process block positions, creating them or accumulating for final step
4384          foreach($positions as $position) {
4385              $position = (object)$position;
4386              $position->blockinstanceid = $newitemid; // The instance is always the restored one
4387              // If position is for one already mapped (known) contextid
4388              // process it now, creating the position
4389              if ($newpositionctxid = $this->get_mappingid('context', $position->contextid)) {
4390                  $position->contextid = $newpositionctxid;
4391                  // Create the block position
4392                  $DB->insert_record('block_positions', $position);
4393  
4394              // The position belongs to an unknown context, send it to backup_ids
4395              // to process them as part of the final steps of restore. We send the
4396              // whole $position object there, hence use the low level method.
4397              } else {
4398                  restore_dbops::set_backup_ids_record($this->get_restoreid(), 'block_position', $position->id, 0, null, $position);
4399              }
4400          }
4401      }
4402  }
4403  
4404  /**
4405   * Structure step to restore common course_module information
4406   *
4407   * This step will process the module.xml file for one activity, in order to restore
4408   * the corresponding information to the course_modules table, skipping various bits
4409   * of information based on CFG settings (groupings, completion...) in order to fullfill
4410   * all the reqs to be able to create the context to be used by all the rest of steps
4411   * in the activity restore task
4412   */
4413  class restore_module_structure_step extends restore_structure_step {
4414  
4415      protected function define_structure() {
4416          global $CFG;
4417  
4418          $paths = array();
4419  
4420          $module = new restore_path_element('module', '/module');
4421          $paths[] = $module;
4422          if ($CFG->enableavailability) {
4423              $paths[] = new restore_path_element('availability', '/module/availability_info/availability');
4424              $paths[] = new restore_path_element('availability_field', '/module/availability_info/availability_field');
4425          }
4426  
4427          $paths[] = new restore_path_element('tag', '/module/tags/tag');
4428  
4429          // Apply for 'format' plugins optional paths at module level
4430          $this->add_plugin_structure('format', $module);
4431  
4432          // Apply for 'report' plugins optional paths at module level.
4433          $this->add_plugin_structure('report', $module);
4434  
4435          // Apply for 'plagiarism' plugins optional paths at module level
4436          $this->add_plugin_structure('plagiarism', $module);
4437  
4438          // Apply for 'local' plugins optional paths at module level
4439          $this->add_plugin_structure('local', $module);
4440  
4441          // Apply for 'admin tool' plugins optional paths at module level.
4442          $this->add_plugin_structure('tool', $module);
4443  
4444          return $paths;
4445      }
4446  
4447      protected function process_module($data) {
4448          global $CFG, $DB;
4449  
4450          $data = (object)$data;
4451          $oldid = $data->id;
4452          $this->task->set_old_moduleversion($data->version);
4453  
4454          $data->course = $this->task->get_courseid();
4455          $data->module = $DB->get_field('modules', 'id', array('name' => $data->modulename));
4456          // Map section (first try by course_section mapping match. Useful in course and section restores)
4457          $data->section = $this->get_mappingid('course_section', $data->sectionid);
4458          if (!$data->section) { // mapping failed, try to get section by sectionnumber matching
4459              $params = array(
4460                  'course' => $this->get_courseid(),
4461                  'section' => $data->sectionnumber);
4462              $data->section = $DB->get_field('course_sections', 'id', $params);
4463          }
4464          if (!$data->section) { // sectionnumber failed, try to get first section in course
4465              $params = array(
4466                  'course' => $this->get_courseid());
4467              $data->section = $DB->get_field('course_sections', 'MIN(id)', $params);
4468          }
4469          if (!$data->section) { // no sections in course, create section 0 and 1 and assign module to 1
4470              $sectionrec = array(
4471                  'course' => $this->get_courseid(),
4472                  'section' => 0,
4473                  'timemodified' => time());
4474              $DB->insert_record('course_sections', $sectionrec); // section 0
4475              $sectionrec = array(
4476                  'course' => $this->get_courseid(),
4477                  'section' => 1,
4478                  'timemodified' => time());
4479              $data->section = $DB->insert_record('course_sections', $sectionrec); // section 1
4480          }
4481          $data->groupingid= $this->get_mappingid('grouping', $data->groupingid);      // grouping
4482          if (!grade_verify_idnumber($data->idnumber, $this->get_courseid())) {        // idnumber uniqueness
4483              $data->idnumber = '';
4484          }
4485          if (empty($CFG->enablecompletion)) { // completion
4486              $data->completion = 0;
4487              $data->completiongradeitemnumber = null;
4488              $data->completionview = 0;
4489              $data->completionexpected = 0;
4490          } else {
4491              $data->completionexpected = $this->apply_date_offset($data->completionexpected);
4492          }
4493          if (empty($CFG->enableavailability)) {
4494              $data->availability = null;
4495          }
4496          // Backups that did not include showdescription, set it to default 0
4497          // (this is not totally necessary as it has a db default, but just to
4498          // be explicit).
4499          if (!isset($data->showdescription)) {
4500              $data->showdescription = 0;
4501          }
4502          $data->instance = 0; // Set to 0 for now, going to create it soon (next step)
4503  
4504          if (empty($data->availability)) {
4505              // If there are legacy availablility data fields (and no new format data),
4506              // convert the old fields.
4507              $data->availability = \core_availability\info::convert_legacy_fields(
4508                      $data, false);
4509          } else if (!empty($data->groupmembersonly)) {
4510              // There is current availability data, but it still has groupmembersonly
4511              // as well (2.7 backups), convert just that part.
4512              require_once($CFG->dirroot . '/lib/db/upgradelib.php');
4513              $data->availability = upgrade_group_members_only($data->groupingid, $data->availability);
4514          }
4515  
4516          if (!has_capability('moodle/course:setforcedlanguage', context_course::instance($data->course))) {
4517              unset($data->lang);
4518          }
4519  
4520          // course_module record ready, insert it
4521          $newitemid = $DB->insert_record('course_modules', $data);
4522          // save mapping
4523          $this->set_mapping('course_module', $oldid, $newitemid);
4524          // set the new course_module id in the task
4525          $this->task->set_moduleid($newitemid);
4526          // we can now create the context safely
4527          $ctxid = context_module::instance($newitemid)->id;
4528          // set the new context id in the task
4529          $this->task->set_contextid($ctxid);
4530          // update sequence field in course_section
4531          if ($sequence = $DB->get_field('course_sections', 'sequence', array('id' => $data->section))) {
4532              $sequence .= ',' . $newitemid;
4533          } else {
4534              $sequence = $newitemid;
4535          }
4536  
4537          $updatesection = new \stdClass();
4538          $updatesection->id = $data->section;
4539          $updatesection->sequence = $sequence;
4540          $updatesection->timemodified = time();
4541          $DB->update_record('course_sections', $updatesection);
4542  
4543          // If there is the legacy showavailability data, store this for later use.
4544          // (This data is not present when restoring 'new' backups.)
4545          if (isset($data->showavailability)) {
4546              // Cache the showavailability flag using the backup_ids data field.
4547              restore_dbops::set_backup_ids_record($this->get_restoreid(),
4548                      'module_showavailability', $newitemid, 0, null,
4549                      (object)array('showavailability' => $data->showavailability));
4550          }
4551      }
4552  
4553      /**
4554       * Fetch all the existing because tag_set() deletes them
4555       * so everything must be reinserted on each call.
4556       *
4557       * @param stdClass $data Record data
4558       */
4559      protected function process_tag($data) {
4560          global $CFG;
4561  
4562          $data = (object)$data;
4563  
4564          if (core_tag_tag::is_enabled('core', 'course_modules')) {
4565              $modcontext = context::instance_by_id($this->task->get_contextid());
4566              $instanceid = $this->task->get_moduleid();
4567  
4568              core_tag_tag::add_item_tag('core', 'course_modules', $instanceid, $modcontext, $data->rawname);
4569          }
4570      }
4571  
4572      /**
4573       * Process the legacy availability table record. This table does not exist
4574       * in Moodle 2.7+ but we still support restore.
4575       *
4576       * @param stdClass $data Record data
4577       */
4578      protected function process_availability($data) {
4579          $data = (object)$data;
4580          // Simply going to store the whole availability record now, we'll process
4581          // all them later in the final task (once all activities have been restored)
4582          // Let's call the low level one to be able to store the whole object
4583          $data->coursemoduleid = $this->task->get_moduleid(); // Let add the availability cmid
4584          restore_dbops::set_backup_ids_record($this->get_restoreid(), 'module_availability', $data->id, 0, null, $data);
4585      }
4586  
4587      /**
4588       * Process the legacy availability fields table record. This table does not
4589       * exist in Moodle 2.7+ but we still support restore.
4590       *
4591       * @param stdClass $data Record data
4592       */
4593      protected function process_availability_field($data) {
4594          global $DB, $CFG;
4595          require_once($CFG->dirroot.'/user/profile/lib.php');
4596  
4597          $data = (object)$data;
4598          // Mark it is as passed by default
4599          $passed = true;
4600          $customfieldid = null;
4601  
4602          // If a customfield has been used in order to pass we must be able to match an existing
4603          // customfield by name (data->customfield) and type (data->customfieldtype)
4604          if (!empty($data->customfield) xor !empty($data->customfieldtype)) {
4605              // xor is sort of uncommon. If either customfield is null or customfieldtype is null BUT not both.
4606              // If one is null but the other isn't something clearly went wrong and we'll skip this condition.
4607              $passed = false;
4608          } else if (!empty($data->customfield)) {
4609              $field = profile_get_custom_field_data_by_shortname($data->customfield);
4610              $passed = $field && $field->datatype == $data->customfieldtype;
4611          }
4612  
4613          if ($passed) {
4614              // Create the object to insert into the database
4615              $availfield = new stdClass();
4616              $availfield->coursemoduleid = $this->task->get_moduleid(); // Lets add the availability cmid
4617              $availfield->userfield = $data->userfield;
4618              $availfield->customfieldid = $customfieldid;
4619              $availfield->operator = $data->operator;
4620              $availfield->value = $data->value;
4621  
4622              // Get showavailability option.
4623              $showrec = restore_dbops::get_backup_ids_record($this->get_restoreid(),
4624                      'module_showavailability', $availfield->coursemoduleid);
4625              if (!$showrec) {
4626                  // Should not happen.
4627                  throw new coding_exception('No matching showavailability record');
4628              }
4629              $show = $showrec->info->showavailability;
4630  
4631              // The $availfieldobject is now in the format used in the old
4632              // system. Interpret this and convert to new system.
4633              $currentvalue = $DB->get_field('course_modules', 'availability',
4634                      array('id' => $availfield->coursemoduleid), MUST_EXIST);
4635              $newvalue = \core_availability\info::add_legacy_availability_field_condition(
4636                      $currentvalue, $availfield, $show);
4637              $DB->set_field('course_modules', 'availability', $newvalue,
4638                      array('id' => $availfield->coursemoduleid));
4639          }
4640      }
4641      /**
4642       * This method will be executed after the rest of the restore has been processed.
4643       *
4644       * Update old tag instance itemid(s).
4645       */
4646      protected function after_restore() {
4647          global $DB;
4648  
4649          $contextid = $this->task->get_contextid();
4650          $instanceid = $this->task->get_activityid();
4651          $olditemid = $this->task->get_old_activityid();
4652  
4653          $DB->set_field('tag_instance', 'itemid', $instanceid, array('contextid' => $contextid, 'itemid' => $olditemid));
4654      }
4655  }
4656  
4657  /**
4658   * Structure step that will process the user activity completion
4659   * information if all these conditions are met:
4660   *  - Target site has completion enabled ($CFG->enablecompletion)
4661   *  - Activity includes completion info (file_exists)
4662   */
4663  class restore_userscompletion_structure_step extends restore_structure_step {
4664      /**
4665       * To conditionally decide if this step must be executed
4666       * Note the "settings" conditions are evaluated in the
4667       * corresponding task. Here we check for other conditions
4668       * not being restore settings (files, site settings...)
4669       */
4670       protected function execute_condition() {
4671           global $CFG;
4672  
4673           // Completion disabled in this site, don't execute
4674           if (empty($CFG->enablecompletion)) {
4675               return false;
4676           }
4677  
4678          // No completion on the front page.
4679          if ($this->get_courseid() == SITEID) {
4680              return false;
4681          }
4682  
4683           // No user completion info found, don't execute
4684          $fullpath = $this->task->get_taskbasepath();
4685          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
4686           if (!file_exists($fullpath)) {
4687               return false;
4688           }
4689  
4690           // Arrived here, execute the step
4691           return true;
4692       }
4693  
4694       protected function define_structure() {
4695  
4696          $paths = array();
4697  
4698          // Restore completion.
4699          $paths[] = new restore_path_element('completion', '/completions/completion');
4700  
4701          // Restore completion view.
4702          $paths[] = new restore_path_element('completionview', '/completions/completionviews/completionview');
4703  
4704          return $paths;
4705      }
4706  
4707      protected function process_completion($data) {
4708          global $DB;
4709  
4710          $data = (object)$data;
4711  
4712          $data->coursemoduleid = $this->task->get_moduleid();
4713          $data->userid = $this->get_mappingid('user', $data->userid);
4714  
4715          // Find the existing record
4716          $existing = $DB->get_record('course_modules_completion', array(
4717                  'coursemoduleid' => $data->coursemoduleid,
4718                  'userid' => $data->userid), 'id, timemodified');
4719          // Check we didn't already insert one for this cmid and userid
4720          // (there aren't supposed to be duplicates in that field, but
4721          // it was possible until MDL-28021 was fixed).
4722          if ($existing) {
4723              // Update it to these new values, but only if the time is newer
4724              if ($existing->timemodified < $data->timemodified) {
4725                  $data->id = $existing->id;
4726                  $DB->update_record('course_modules_completion', $data);
4727              }
4728          } else {
4729              // Normal entry where it doesn't exist already
4730              $DB->insert_record('course_modules_completion', $data);
4731          }
4732  
4733          // Add viewed to course_modules_viewed.
4734          if (isset($data->viewed) && $data->viewed) {
4735              $dataview = clone($data);
4736              unset($dataview->id);
4737              unset($dataview->viewed);
4738              $dataview->timecreated = $data->timemodified;
4739              $DB->insert_record('course_modules_viewed', $dataview);
4740          }
4741      }
4742  
4743      /**
4744       * Process the completioinview data.
4745       * @param array $data The data from the XML file.
4746       */
4747      protected function process_completionview(array $data) {
4748          global $DB;
4749  
4750          $data = (object)$data;
4751          $data->coursemoduleid = $this->task->get_moduleid();
4752          $data->userid = $this->get_mappingid('user', $data->userid);
4753  
4754          $DB->insert_record('course_modules_viewed', $data);
4755      }
4756  }
4757  
4758  /**
4759   * Abstract structure step, parent of all the activity structure steps. Used to support
4760   * the main <activity ...> tag and process it.
4761   */
4762  abstract class restore_activity_structure_step extends restore_structure_step {
4763  
4764      /**
4765       * Adds support for the 'activity' path that is common to all the activities
4766       * and will be processed globally here
4767       */
4768      protected function prepare_activity_structure($paths) {
4769  
4770          $paths[] = new restore_path_element('activity', '/activity');
4771  
4772          return $paths;
4773      }
4774  
4775      /**
4776       * Process the activity path, informing the task about various ids, needed later
4777       */
4778      protected function process_activity($data) {
4779          $data = (object)$data;
4780          $this->task->set_old_contextid($data->contextid); // Save old contextid in task
4781          $this->set_mapping('context', $data->contextid, $this->task->get_contextid()); // Set the mapping
4782          $this->task->set_old_activityid($data->id); // Save old activityid in task
4783      }
4784  
4785      /**
4786       * This must be invoked immediately after creating the "module" activity record (forum, choice...)
4787       * and will adjust the new activity id (the instance) in various places
4788       */
4789      protected function apply_activity_instance($newitemid) {
4790          global $DB;
4791  
4792          $this->task->set_activityid($newitemid); // Save activity id in task
4793          // Apply the id to course_sections->instanceid
4794          $DB->set_field('course_modules', 'instance', $newitemid, array('id' => $this->task->get_moduleid()));
4795          // Do the mapping for modulename, preparing it for files by oldcontext
4796          $modulename = $this->task->get_modulename();
4797          $oldid = $this->task->get_old_activityid();
4798          $this->set_mapping($modulename, $oldid, $newitemid, true);
4799      }
4800  }
4801  
4802  /**
4803   * Structure step in charge of creating/mapping all the qcats and qs
4804   * by parsing the questions.xml file and checking it against the
4805   * results calculated by {@link restore_process_categories_and_questions}
4806   * and stored in backup_ids_temp.
4807   */
4808  class restore_create_categories_and_questions extends restore_structure_step {
4809  
4810      /** @var array $cachedcategory store a question category */
4811      protected $cachedcategory = null;
4812  
4813      protected function define_structure() {
4814  
4815          // Check if the backup is a pre 4.0 one.
4816          $restoretask = $this->get_task();
4817          $before40 = $restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<');
4818          // Start creating the path, category should be the first one.
4819          $paths = [];
4820          $paths [] = new restore_path_element('question_category', '/question_categories/question_category');
4821          // For the backups done before 4.0.
4822          if ($before40) {
4823              // This path is to recreate the bank entry and version for the legacy question objets.
4824              $question = new restore_path_element('question', '/question_categories/question_category/questions/question');
4825  
4826              // Apply for 'qtype' plugins optional paths at question level.
4827              $this->add_plugin_structure('qtype', $question);
4828  
4829              // Apply for 'local' plugins optional paths at question level.
4830              $this->add_plugin_structure('local', $question);
4831  
4832              $paths [] = $question;
4833              $paths [] = new restore_path_element('question_hint',
4834                  '/question_categories/question_category/questions/question/question_hints/question_hint');
4835              $paths [] = new restore_path_element('tag', '/question_categories/question_category/questions/question/tags/tag');
4836          } else {
4837              // For all the new backups.
4838              $paths [] = new restore_path_element('question_bank_entry',
4839                  '/question_categories/question_category/question_bank_entries/question_bank_entry');
4840              $paths [] = new restore_path_element('question_versions', '/question_categories/question_category/'.
4841                  'question_bank_entries/question_bank_entry/question_version/question_versions');
4842              $question = new restore_path_element('question', '/question_categories/question_category/'.
4843                  'question_bank_entries/question_bank_entry/question_version/question_versions/questions/question');
4844  
4845              // Apply for 'qtype' plugins optional paths at question level.
4846              $this->add_plugin_structure('qtype', $question);
4847  
4848              // Apply for 'qbank' plugins optional paths at question level.
4849              $this->add_plugin_structure('qbank', $question);
4850  
4851              // Apply for 'local' plugins optional paths at question level.
4852              $this->add_plugin_structure('local', $question);
4853  
4854              $paths [] = $question;
4855              $paths [] = new restore_path_element('question_hint', '/question_categories/question_category/question_bank_entries/'.
4856                  'question_bank_entry/question_version/question_versions/questions/question/question_hints/question_hint');
4857              $paths [] = new restore_path_element('tag', '/question_categories/question_category/question_bank_entries/'.
4858                  'question_bank_entry/question_version/question_versions/questions/question/tags/tag');
4859          }
4860  
4861          return $paths;
4862      }
4863  
4864      /**
4865       * Process question category restore.
4866       *
4867       * @param array $data the data from the XML file.
4868       */
4869      protected function process_question_category($data) {
4870          global $DB;
4871  
4872          $data = (object)$data;
4873          $oldid = $data->id;
4874  
4875          // Check we have one mapping for this category.
4876          if (!$mapping = $this->get_mapping('question_category', $oldid)) {
4877              return self::SKIP_ALL_CHILDREN; // No mapping = this category doesn't need to be created/mapped
4878          }
4879  
4880          // Check we have to create the category (newitemid = 0).
4881          if ($mapping->newitemid) {
4882              // By performing this set_mapping() we make get_old/new_parentid() to work for all the
4883              // children elements of the 'question_category' one.
4884              $this->set_mapping('question_category', $oldid, $mapping->newitemid);
4885              return; // newitemid != 0, this category is going to be mapped. Nothing to do
4886          }
4887  
4888          // Arrived here, newitemid = 0, we need to create the category
4889          // we'll do it at parentitemid context, but for CONTEXT_MODULE
4890          // categories, that will be created at CONTEXT_COURSE and moved
4891          // to module context later when the activity is created.
4892          if ($mapping->info->contextlevel == CONTEXT_MODULE) {
4893              $mapping->parentitemid = $this->get_mappingid('context', $this->task->get_old_contextid());
4894          }
4895          $data->contextid = $mapping->parentitemid;
4896  
4897          // Before 3.5, question categories could be created at top level.
4898          // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
4899          $restoretask = $this->get_task();
4900          $before35 = $restoretask->backup_release_compare('3.5', '<') || $restoretask->backup_version_compare(20180205, '<');
4901          if (empty($mapping->info->parent) && $before35) {
4902              $top = question_get_top_category($data->contextid, true);
4903              $data->parent = $top->id;
4904          }
4905  
4906          if (empty($data->parent)) {
4907              if (!$top = question_get_top_category($data->contextid)) {
4908                  $top = question_get_top_category($data->contextid, true);
4909                  $this->set_mapping('question_category_created', $oldid, $top->id, false, null, $data->contextid);
4910              }
4911              $this->set_mapping('question_category', $oldid, $top->id);
4912          } else {
4913  
4914              // Before 3.1, the 'stamp' field could be erroneously duplicated.
4915              // From 3.1 onwards, there's a unique index of (contextid, stamp).
4916              // If we encounter a duplicate in an old restore file, just generate a new stamp.
4917              // This is the same as what happens during an upgrade to 3.1+ anyway.
4918              if ($DB->record_exists('question_categories', ['stamp' => $data->stamp, 'contextid' => $data->contextid])) {
4919                  $data->stamp = make_unique_id_code();
4920              }
4921  
4922              // The idnumber if it exists also needs to be unique within a context or reset it to null.
4923              if (!empty($data->idnumber) && $DB->record_exists('question_categories',
4924                      ['idnumber' => $data->idnumber, 'contextid' => $data->contextid])) {
4925                  unset($data->idnumber);
4926              }
4927  
4928              // Let's create the question_category and save mapping.
4929              $newitemid = $DB->insert_record('question_categories', $data);
4930              $this->set_mapping('question_category', $oldid, $newitemid);
4931              // Also annotate them as question_category_created, we need
4932              // that later when remapping parents.
4933              $this->set_mapping('question_category_created', $oldid, $newitemid, false, null, $data->contextid);
4934          }
4935      }
4936  
4937      /**
4938       * Process pre 4.0 question data where in creates the record for version and entry table.
4939       *
4940       * @param array $data the data from the XML file.
4941       */
4942      protected function process_question_legacy_data($data) {
4943          global $DB;
4944  
4945          $oldid = $data->id;
4946          // Process question bank entry.
4947          $entrydata = new stdClass();
4948          $entrydata->questioncategoryid = $data->category;
4949          $userid = $this->get_mappingid('user', $data->createdby);
4950          if ($userid) {
4951              $entrydata->ownerid = $userid;
4952          } else {
4953              if (!$this->task->is_samesite()) {
4954                  $entrydata->ownerid = $this->task->get_userid();
4955              }
4956          }
4957          // The idnumber if it exists also needs to be unique within a category or reset it to null.
4958          if (isset($data->idnumber) && !$DB->record_exists('question_bank_entries',
4959                  ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->category])) {
4960              $entrydata->idnumber = $data->idnumber;
4961          }
4962  
4963          $newentryid = $DB->insert_record('question_bank_entries', $entrydata);
4964          // Process question versions.
4965          $versiondata = new stdClass();
4966          $versiondata->questionbankentryid = $newentryid;
4967          $versiondata->version = 1;
4968          // Question id is updated after inserting the question.
4969          $versiondata->questionid = 0;
4970          $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_READY;
4971          if ((int)$data->hidden === 1) {
4972              $versionstatus = \core_question\local\bank\question_version_status::QUESTION_STATUS_HIDDEN;
4973          }
4974          $versiondata->status = $versionstatus;
4975          $newversionid = $DB->insert_record('question_versions', $versiondata);
4976          $this->set_mapping('question_version_created', $oldid, $newversionid);
4977      }
4978  
4979      /**
4980       * Process question bank entry data.
4981       *
4982       * @param array $data the data from the XML file.
4983       */
4984      protected function process_question_bank_entry($data) {
4985          global $DB;
4986  
4987          $data = (object)$data;
4988          $oldid = $data->id;
4989  
4990          $questioncreated = $this->get_mappingid('question_category_created', $data->questioncategoryid) ? true : false;
4991          $recordexist = $DB->record_exists('question_bank_entries', ['id' => $data->id,
4992              'questioncategoryid' => $data->questioncategoryid]);
4993          // Check we have category created.
4994          if (!$questioncreated && $recordexist) {
4995              return self::SKIP_ALL_CHILDREN;
4996          }
4997  
4998          $data->questioncategoryid = $this->get_new_parentid('question_category');
4999          $userid = $this->get_mappingid('user', $data->ownerid);
5000          if ($userid) {
5001              $data->ownerid = $userid;
5002          } else {
5003              if (!$this->task->is_samesite()) {
5004                  $data->ownerid = $this->task->get_userid();
5005              }
5006          }
5007  
5008          // The idnumber if it exists also needs to be unique within a category or reset it to null.
5009          if (!empty($data->idnumber) && $DB->record_exists('question_bank_entries',
5010                  ['idnumber' => $data->idnumber, 'questioncategoryid' => $data->questioncategoryid])) {
5011              unset($data->idnumber);
5012          }
5013  
5014          $newitemid = $DB->insert_record('question_bank_entries', $data);
5015          $this->set_mapping('question_bank_entry', $oldid, $newitemid);
5016      }
5017  
5018      /**
5019       * Process question versions.
5020       *
5021       * @param array $data the data from the XML file.
5022       */
5023      protected function process_question_versions($data) {
5024          global $DB;
5025  
5026          $data = (object)$data;
5027          $oldid = $data->id;
5028  
5029          $data->questionbankentryid = $this->get_new_parentid('question_bank_entry');
5030          // Question id is updated after inserting the question.
5031          $data->questionid = 0;
5032          $newitemid = $DB->insert_record('question_versions', $data);
5033          $this->set_mapping('question_versions', $oldid, $newitemid);
5034      }
5035  
5036      /**
5037       * Process the actual question.
5038       *
5039       * @param array $data the data from the XML file.
5040       */
5041      protected function process_question($data) {
5042          global $DB;
5043  
5044          $data = (object)$data;
5045          $oldid = $data->id;
5046  
5047          // Check if the backup is a pre 4.0 one.
5048          $restoretask = $this->get_task();
5049          if ($restoretask->backup_release_compare('4.0', '<') || $restoretask->backup_version_compare(20220202, '<')) {
5050              // Check we have one mapping for this question.
5051              if (!$questionmapping = $this->get_mapping('question', $oldid)) {
5052                  return; // No mapping = this question doesn't need to be created/mapped.
5053              }
5054  
5055              // Get the mapped category (cannot use get_new_parentid() because not
5056              // all the categories have been created, so it is not always available
5057              // Instead we get the mapping for the question->parentitemid because
5058              // we have loaded qcatids there for all parsed questions.
5059              $data->category = $this->get_mappingid('question_category', $questionmapping->parentitemid);
5060              $this->process_question_legacy_data($data);
5061          }
5062  
5063          // In the past, there were some very sloppy values of penalty. Fix them.
5064          if ($data->penalty >= 0.33 && $data->penalty <= 0.34) {
5065              $data->penalty = 0.3333333;
5066          }
5067          if ($data->penalty >= 0.66 && $data->penalty <= 0.67) {
5068              $data->penalty = 0.6666667;
5069          }
5070          if ($data->penalty >= 1) {
5071              $data->penalty = 1;
5072          }
5073  
5074          $userid = $this->get_mappingid('user', $data->createdby);
5075          if ($userid) {
5076              // The question creator is included in the backup, so we can use their mapping id.
5077              $data->createdby = $userid;
5078          } else {
5079              // Leave the question creator unchanged when we are restoring the same site.
5080              // Otherwise use current user id.
5081              if (!$this->task->is_samesite()) {
5082                  $data->createdby = $this->task->get_userid();
5083              }
5084          }
5085  
5086          $userid = $this->get_mappingid('user', $data->modifiedby);
5087          if ($userid) {
5088              // The question modifier is included in the backup, so we can use their mapping id.
5089              $data->modifiedby = $userid;
5090          } else {
5091              // Leave the question modifier unchanged when we are restoring the same site.
5092              // Otherwise use current user id.
5093              if (!$this->task->is_samesite()) {
5094                  $data->modifiedby = $this->task->get_userid();
5095              }
5096          }
5097  
5098          $newitemid = $DB->insert_record('question', $data);
5099          $this->set_mapping('question', $oldid, $newitemid);
5100          // Also annotate them as question_created, we need
5101          // that later when remapping parents (keeping the old categoryid as parentid).
5102          $parentcatid = $this->get_old_parentid('question_category');
5103          $this->set_mapping('question_created', $oldid, $newitemid, false, null, $parentcatid);
5104          // Now update the question_versions table with the new question id. we dont need to do that for random qtypes.
5105          $legacyquestiondata = $this->get_mappingid('question_version_created', $oldid) ? true : false;
5106          if ($legacyquestiondata) {
5107              $parentitemid = $this->get_mappingid('question_version_created', $oldid);
5108          } else {
5109              $parentitemid = $this->get_new_parentid('question_versions');
5110          }
5111          $version = new stdClass();
5112          $version->id = $parentitemid;
5113          $version->questionid = $newitemid;
5114          $DB->update_record('question_versions', $version);
5115  
5116          // Note, we don't restore any question files yet
5117          // as far as the CONTEXT_MODULE categories still
5118          // haven't their contexts to be restored to
5119          // The {@link restore_create_question_files}, executed in the final step
5120          // step will be in charge of restoring all the question files.
5121      }
5122  
5123      protected function process_question_hint($data) {
5124          global $DB;
5125  
5126          $data = (object)$data;
5127          $oldid = $data->id;
5128  
5129          // Detect if the question is created or mapped
5130          $oldquestionid   = $this->get_old_parentid('question');
5131          $newquestionid   = $this->get_new_parentid('question');
5132          $questioncreated = $this->get_mappingid('question_created', $oldquestionid) ? true : false;
5133  
5134          // If the question has been created by restore, we need to create its question_answers too
5135          if ($questioncreated) {
5136              // Adjust some columns
5137              $data->questionid = $newquestionid;
5138              // Insert record
5139              $newitemid = $DB->insert_record('question_hints', $data);
5140  
5141          // The question existed, we need to map the existing question_hints
5142          } else {
5143              // Look in question_hints by hint text matching
5144              $sql = 'SELECT id
5145                        FROM {question_hints}
5146                       WHERE questionid = ?
5147                         AND ' . $DB->sql_compare_text('hint', 255) . ' = ' . $DB->sql_compare_text('?', 255);
5148              $params = array($newquestionid, $data->hint);
5149              $newitemid = $DB->get_field_sql($sql, $params);
5150  
5151              // Not able to find the hint, let's try cleaning the hint text
5152              // of all the question's hints in DB as slower fallback. MDL-33863.
5153              if (!$newitemid) {
5154                  $potentialhints = $DB->get_records('question_hints',
5155                          array('questionid' => $newquestionid), '', 'id, hint');
5156                  foreach ($potentialhints as $potentialhint) {
5157                      // Clean in the same way than {@link xml_writer::xml_safe_utf8()}.
5158                      $cleanhint = preg_replace('/[\x-\x8\xb-\xc\xe-\x1f\x7f]/is','', $potentialhint->hint); // Clean CTRL chars.
5159                      $cleanhint = preg_replace("/\r\n|\r/", "\n", $cleanhint); // Normalize line ending.
5160                      if ($cleanhint === $data->hint) {
5161                          $newitemid = $data->id;
5162                      }
5163                  }
5164              }
5165  
5166              // If we haven't found the newitemid, something has gone really wrong, question in DB
5167              // is missing hints, exception
5168              if (!$newitemid) {
5169                  $info = new stdClass();
5170                  $info->filequestionid = $oldquestionid;
5171                  $info->dbquestionid   = $newquestionid;
5172                  $info->hint           = $data->hint;
5173                  throw new restore_step_exception('error_question_hint_missing_in_db', $info);
5174              }
5175          }
5176          // Create mapping (I'm not sure if this is really needed?)
5177          $this->set_mapping('question_hint', $oldid, $newitemid);
5178      }
5179  
5180      protected function process_tag($data) {
5181          global $DB;
5182  
5183          $data = (object)$data;
5184          $newquestion = $this->get_new_parentid('question');
5185          $questioncreated = (bool) $this->get_mappingid('question_created', $this->get_old_parentid('question'));
5186          if (!$questioncreated) {
5187              // This question already exists in the question bank. Nothing for us to do.
5188              return;
5189          }
5190  
5191          if (core_tag_tag::is_enabled('core_question', 'question')) {
5192              $tagname = $data->rawname;
5193              if (!empty($data->contextid) && $newcontextid = $this->get_mappingid('context', $data->contextid)) {
5194                      $tagcontextid = $newcontextid;
5195              } else {
5196                  // Get the category, so we can then later get the context.
5197                  $categoryid = $this->get_new_parentid('question_category');
5198                  if (empty($this->cachedcategory) || $this->cachedcategory->id != $categoryid) {
5199                      $this->cachedcategory = $DB->get_record('question_categories', array('id' => $categoryid));
5200                  }
5201                  $tagcontextid = $this->cachedcategory->contextid;
5202              }
5203              // Add the tag to the question.
5204              core_tag_tag::add_item_tag('core_question', 'question', $newquestion,
5205                      context::instance_by_id($tagcontextid),
5206                      $tagname);
5207          }
5208      }
5209  
5210      protected function after_execute() {
5211          global $DB;
5212  
5213          // First of all, recode all the created question_categories->parent fields
5214          $qcats = $DB->get_records('backup_ids_temp', array(
5215                       'backupid' => $this->get_restoreid(),
5216                       'itemname' => 'question_category_created'));
5217          foreach ($qcats as $qcat) {
5218              $dbcat = $DB->get_record('question_categories', array('id' => $qcat->newitemid));
5219              // Get new parent (mapped or created, so we look in quesiton_category mappings)
5220              if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5221                                   'backupid' => $this->get_restoreid(),
5222                                   'itemname' => 'question_category',
5223                                   'itemid'   => $dbcat->parent))) {
5224                  // contextids must match always, as far as we always include complete qbanks, just check it
5225                  $newparentctxid = $DB->get_field('question_categories', 'contextid', array('id' => $newparent));
5226                  if ($dbcat->contextid == $newparentctxid) {
5227                      $DB->set_field('question_categories', 'parent', $newparent, array('id' => $dbcat->id));
5228                  } else {
5229                      $newparent = 0; // No ctx match for both cats, no parent relationship
5230                  }
5231              }
5232              // Here with $newparent empty, problem with contexts or remapping, set it to top cat
5233              if (!$newparent && $dbcat->parent) {
5234                  $topcat = question_get_top_category($dbcat->contextid, true);
5235                  if ($dbcat->parent != $topcat->id) {
5236                      $DB->set_field('question_categories', 'parent', $topcat->id, array('id' => $dbcat->id));
5237                  }
5238              }
5239          }
5240  
5241          // Now, recode all the created question->parent fields
5242          $qs = $DB->get_records('backup_ids_temp', array(
5243                    'backupid' => $this->get_restoreid(),
5244                    'itemname' => 'question_created'));
5245          foreach ($qs as $q) {
5246              $dbq = $DB->get_record('question', array('id' => $q->newitemid));
5247              // Get new parent (mapped or created, so we look in question mappings)
5248              if ($newparent = $DB->get_field('backup_ids_temp', 'newitemid', array(
5249                                   'backupid' => $this->get_restoreid(),
5250                                   'itemname' => 'question',
5251                                   'itemid'   => $dbq->parent))) {
5252                  $DB->set_field('question', 'parent', $newparent, array('id' => $dbq->id));
5253              }
5254          }
5255  
5256          // Note, we don't restore any question files yet
5257          // as far as the CONTEXT_MODULE categories still
5258          // haven't their contexts to be restored to
5259          // The {@link restore_create_question_files}, executed in the final step
5260          // step will be in charge of restoring all the question files
5261      }
5262  }
5263  
5264  /**
5265   * Execution step that will move all the CONTEXT_MODULE question categories
5266   * created at early stages of restore in course context (because modules weren't
5267   * created yet) to their target module (matching by old-new-contextid mapping)
5268   */
5269  class restore_move_module_questions_categories extends restore_execution_step {
5270  
5271      protected function define_execution() {
5272          global $DB;
5273  
5274          $after35 = $this->task->backup_release_compare('3.5', '>=') && $this->task->backup_version_compare(20180205, '>');
5275  
5276          $contexts = restore_dbops::restore_get_question_banks($this->get_restoreid(), CONTEXT_MODULE);
5277          foreach ($contexts as $contextid => $contextlevel) {
5278              // Only if context mapping exists (i.e. the module has been restored)
5279              if ($newcontext = restore_dbops::get_backup_ids_record($this->get_restoreid(), 'context', $contextid)) {
5280                  // Update all the qcats having their parentitemid set to the original contextid
5281                  $modulecats = $DB->get_records_sql("SELECT itemid, newitemid, info
5282                                                        FROM {backup_ids_temp}
5283                                                       WHERE backupid = ?
5284                                                         AND itemname = 'question_category'
5285                                                         AND parentitemid = ?", array($this->get_restoreid(), $contextid));
5286                  $top = question_get_top_category($newcontext->newitemid, true);
5287                  $oldtopid = 0;
5288                  $categoryids = [];
5289                  foreach ($modulecats as $modulecat) {
5290                      // Before 3.5, question categories could be created at top level.
5291                      // From 3.5 onwards, all question categories should be a child of a special category called the "top" category.
5292                      $info = backup_controller_dbops::decode_backup_temp_info($modulecat->info);
5293                      if ($after35 && empty($info->parent)) {
5294                          $oldtopid = $modulecat->newitemid;
5295                          $modulecat->newitemid = $top->id;
5296                      } else {
5297                          $cat = new stdClass();
5298                          $cat->id = $modulecat->newitemid;
5299                          $cat->contextid = $newcontext->newitemid;
5300                          if (empty($info->parent)) {
5301                              $cat->parent = $top->id;
5302                          }
5303                          $DB->update_record('question_categories', $cat);
5304                          $categoryids[] = (int)$cat->id;
5305                      }
5306  
5307                      // And set new contextid (and maybe update newitemid) also in question_category mapping (will be
5308                      // used by {@link restore_create_question_files} later.
5309                      restore_dbops::set_backup_ids_record($this->get_restoreid(), 'question_category', $modulecat->itemid,
5310                              $modulecat->newitemid, $newcontext->newitemid);
5311                  }
5312  
5313                  // Update the context id of any tags applied to any questions in these categories.
5314                  if ($categoryids) {
5315                      [$categorysql, $categoryidparams] = $DB->get_in_or_equal($categoryids, SQL_PARAMS_NAMED);
5316                      $sqlupdate = "UPDATE {tag_instance}
5317                                       SET contextid = :newcontext
5318                                     WHERE component = :component
5319                                           AND itemtype = :itemtype
5320                                           AND itemid IN (SELECT DISTINCT bi.newitemid as questionid
5321                                                            FROM {backup_ids_temp} bi
5322                                                            JOIN {question} q ON q.id = bi.newitemid
5323                                                            JOIN {question_versions} qv ON qv.questionid = q.id
5324                                                            JOIN {question_bank_entries} qbe ON qbe.id = qv.questionbankentryid
5325                                                           WHERE bi.backupid = :backupid AND bi.itemname = 'question_created'
5326                                                                 AND qbe.questioncategoryid {$categorysql}) ";
5327                      $params = [
5328                          'newcontext' => $newcontext->newitemid,
5329                          'component' => 'core_question',
5330                          'itemtype' => 'question',
5331                          'backupid' => $this->get_restoreid(),
5332                      ];
5333                      $params += $categoryidparams;
5334                      $DB->execute($sqlupdate, $params);
5335                  }
5336  
5337                  // Now set the parent id for the question categories that were in the top category in the course context
5338                  // and have been moved now.
5339                  if ($oldtopid) {
5340                      $DB->set_field('question_categories', 'parent', $top->id,
5341                              array('contextid' => $newcontext->newitemid, 'parent' => $oldtopid));
5342                  }
5343              }
5344          }
5345      }
5346  }
5347  
5348  /**
5349   * Execution step that will create all the question/answers/qtype-specific files for the restored
5350   * questions. It must be executed after {@link restore_move_module_questions_categories}
5351   * because only then each question is in its final category and only then the
5352   * contexts can be determined.
5353   */
5354  class restore_create_question_files extends restore_execution_step {
5355  
5356      /** @var array Question-type specific component items cache. */
5357      private $qtypecomponentscache = array();
5358  
5359      /**
5360       * Preform the restore_create_question_files step.
5361       */
5362      protected function define_execution() {
5363          global $DB;
5364  
5365          // Track progress, as this task can take a long time.
5366          $progress = $this->task->get_progress();
5367          $progress->start_progress($this->get_name(), \core\progress\base::INDETERMINATE);
5368  
5369          // Parentitemids of question_createds in backup_ids_temp are the category it is in.
5370          // MUST use a recordset, as there is no unique key in the first (or any) column.
5371          $catqtypes = $DB->get_recordset_sql("SELECT DISTINCT bi.parentitemid AS categoryid, q.qtype as qtype
5372                                                     FROM {backup_ids_temp} bi
5373                                                     JOIN {question} q ON q.id = bi.newitemid
5374                                                    WHERE bi.backupid = ?
5375                                                          AND bi.itemname = 'question_created'
5376                                                 ORDER BY categoryid ASC", array($this->get_restoreid()));
5377  
5378          $currentcatid = -1;
5379          foreach ($catqtypes as $categoryid => $row) {
5380              $qtype = $row->qtype;
5381  
5382              // Check if we are in a new category.
5383              if ($currentcatid !== $categoryid) {
5384                  // Report progress for each category.
5385                  $progress->progress();
5386  
5387                  if (!$qcatmapping = restore_dbops::get_backup_ids_record($this->get_restoreid(),
5388                          'question_category', $categoryid)) {
5389                      // Something went really wrong, cannot find the question_category for the question_created records.
5390                      debugging('Error fetching target context for question', DEBUG_DEVELOPER);
5391                      continue;
5392                  }
5393  
5394                  // Calculate source and target contexts.
5395                  $oldctxid = $qcatmapping->info->contextid;
5396                  $newctxid = $qcatmapping->parentitemid;
5397  
5398                  $this->send_common_files($oldctxid, $newctxid, $progress);
5399                  $currentcatid = $categoryid;
5400              }
5401  
5402              $this->send_qtype_files($qtype, $oldctxid, $newctxid, $progress);
5403          }
5404          $catqtypes->close();
5405          $progress->end_progress();
5406      }
5407  
5408      /**
5409       * Send the common question files to a new context.
5410       *
5411       * @param int             $oldctxid Old context id.
5412       * @param int             $newctxid New context id.
5413       * @param \core\progress  $progress Progress object to use.
5414       */
5415      private function send_common_files($oldctxid, $newctxid, $progress) {
5416          // Add common question files (question and question_answer ones).
5417          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'questiontext',
5418                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5419          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'generalfeedback',
5420                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5421          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answer',
5422                  $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5423          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'answerfeedback',
5424                  $oldctxid, $this->task->get_userid(), 'question_answer', null, $newctxid, true, $progress);
5425          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'hint',
5426                  $oldctxid, $this->task->get_userid(), 'question_hint', null, $newctxid, true, $progress);
5427          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'correctfeedback',
5428                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5429          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'partiallycorrectfeedback',
5430                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5431          restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), 'question', 'incorrectfeedback',
5432                  $oldctxid, $this->task->get_userid(), 'question_created', null, $newctxid, true, $progress);
5433      }
5434  
5435      /**
5436       * Send the question type specific files to a new context.
5437       *
5438       * @param text            $qtype The qtype name to send.
5439       * @param int             $oldctxid Old context id.
5440       * @param int             $newctxid New context id.
5441       * @param \core\progress  $progress Progress object to use.
5442       */
5443      private function send_qtype_files($qtype, $oldctxid, $newctxid, $progress) {
5444          if (!isset($this->qtypecomponentscache[$qtype])) {
5445              $this->qtypecomponentscache[$qtype] = backup_qtype_plugin::get_components_and_fileareas($qtype);
5446          }
5447          $components = $this->qtypecomponentscache[$qtype];
5448          foreach ($components as $component => $fileareas) {
5449              foreach ($fileareas as $filearea => $mapping) {
5450                  restore_dbops::send_files_to_pool($this->get_basepath(), $this->get_restoreid(), $component, $filearea,
5451                          $oldctxid, $this->task->get_userid(), $mapping, null, $newctxid, true, $progress);
5452              }
5453          }
5454      }
5455  }
5456  
5457  /**
5458   * Try to restore aliases and references to external files.
5459   *
5460   * The queue of these files was prepared for us in {@link restore_dbops::send_files_to_pool()}.
5461   * We expect that all regular (non-alias) files have already been restored. Make sure
5462   * there is no restore step executed after this one that would call send_files_to_pool() again.
5463   *
5464   * You may notice we have hardcoded support for Server files, Legacy course files
5465   * and user Private files here at the moment. This could be eventually replaced with a set of
5466   * callbacks in the future if needed.
5467   *
5468   * @copyright 2012 David Mudrak <david@moodle.com>
5469   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5470   */
5471  class restore_process_file_aliases_queue extends restore_execution_step {
5472  
5473      /** @var array internal cache for {@link choose_repository()} */
5474      private $cachereposbyid = array();
5475  
5476      /** @var array internal cache for {@link choose_repository()} */
5477      private $cachereposbytype = array();
5478  
5479      /**
5480       * What to do when this step is executed.
5481       */
5482      protected function define_execution() {
5483          global $DB;
5484  
5485          $fs = get_file_storage();
5486  
5487          // Load the queue.
5488          $aliascount = $DB->count_records('backup_ids_temp',
5489              ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue']);
5490          $rs = $DB->get_recordset('backup_ids_temp',
5491              ['backupid' => $this->get_restoreid(), 'itemname' => 'file_aliases_queue'],
5492              '', 'info');
5493  
5494          $this->log('processing file aliases queue. ' . $aliascount . ' entries.', backup::LOG_DEBUG);
5495          $progress = $this->task->get_progress();
5496          $progress->start_progress('Processing file aliases queue', $aliascount);
5497  
5498          // Iterate over aliases in the queue.
5499          foreach ($rs as $record) {
5500              $progress->increment_progress();
5501              $info = backup_controller_dbops::decode_backup_temp_info($record->info);
5502  
5503              // Try to pick a repository instance that should serve the alias.
5504              $repository = $this->choose_repository($info);
5505  
5506              if (is_null($repository)) {
5507                  $this->notify_failure($info, 'unable to find a matching repository instance');
5508                  continue;
5509              }
5510  
5511              if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5512                      || $info->oldfile->repositorytype === 'contentbank') {
5513                  // Aliases to Server files and Legacy course files may refer to a file
5514                  // contained in the backup file or to some existing file (if we are on the
5515                  // same site).
5516                  try {
5517                      $reference = file_storage::unpack_reference($info->oldfile->reference);
5518                  } catch (Exception $e) {
5519                      $this->notify_failure($info, 'invalid reference field format');
5520                      continue;
5521                  }
5522  
5523                  // Let's see if the referred source file was also included in the backup.
5524                  $candidates = $DB->get_recordset('backup_files_temp', array(
5525                          'backupid' => $this->get_restoreid(),
5526                          'contextid' => $reference['contextid'],
5527                          'component' => $reference['component'],
5528                          'filearea' => $reference['filearea'],
5529                          'itemid' => $reference['itemid'],
5530                      ), '', 'info, newcontextid, newitemid');
5531  
5532                  $source = null;
5533  
5534                  foreach ($candidates as $candidate) {
5535                      $candidateinfo = backup_controller_dbops::decode_backup_temp_info($candidate->info);
5536                      if ($candidateinfo->filename === $reference['filename']
5537                              and $candidateinfo->filepath === $reference['filepath']
5538                              and !is_null($candidate->newcontextid)
5539                              and !is_null($candidate->newitemid) ) {
5540                          $source = $candidateinfo;
5541                          $source->contextid = $candidate->newcontextid;
5542                          $source->itemid = $candidate->newitemid;
5543                          break;
5544                      }
5545                  }
5546                  $candidates->close();
5547  
5548                  if ($source) {
5549                      // We have an alias that refers to another file also included in
5550                      // the backup. Let us change the reference field so that it refers
5551                      // to the restored copy of the original file.
5552                      $reference = file_storage::pack_reference($source);
5553  
5554                      // Send the new alias to the filepool.
5555                      $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5556                      $this->notify_success($info);
5557                      continue;
5558  
5559                  } else {
5560                      // This is a reference to some moodle file that was not contained in the backup
5561                      // file. If we are restoring to the same site, keep the reference untouched
5562                      // and restore the alias as is if the referenced file exists.
5563                      if ($this->task->is_samesite()) {
5564                          if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5565                                  $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5566                              $reference = file_storage::pack_reference($reference);
5567                              $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5568                              $this->notify_success($info);
5569                              continue;
5570                          } else {
5571                              $this->notify_failure($info, 'referenced file not found');
5572                              continue;
5573                          }
5574  
5575                      // If we are at other site, we can't restore this alias.
5576                      } else {
5577                          $this->notify_failure($info, 'referenced file not included');
5578                          continue;
5579                      }
5580                  }
5581  
5582              } else if ($info->oldfile->repositorytype === 'user') {
5583                  if ($this->task->is_samesite()) {
5584                      // For aliases to user Private files at the same site, we have a chance to check
5585                      // if the referenced file still exists.
5586                      try {
5587                          $reference = file_storage::unpack_reference($info->oldfile->reference);
5588                      } catch (Exception $e) {
5589                          $this->notify_failure($info, 'invalid reference field format');
5590                          continue;
5591                      }
5592                      if ($fs->file_exists($reference['contextid'], $reference['component'], $reference['filearea'],
5593                              $reference['itemid'], $reference['filepath'], $reference['filename'])) {
5594                          $reference = file_storage::pack_reference($reference);
5595                          $fs->create_file_from_reference($info->newfile, $repository->id, $reference);
5596                          $this->notify_success($info);
5597                          continue;
5598                      } else {
5599                          $this->notify_failure($info, 'referenced file not found');
5600                          continue;
5601                      }
5602  
5603                  // If we are at other site, we can't restore this alias.
5604                  } else {
5605                      $this->notify_failure($info, 'restoring at another site');
5606                      continue;
5607                  }
5608  
5609              } else {
5610                  // This is a reference to some external file such as dropbox.
5611                  // If we are restoring to the same site, keep the reference untouched and
5612                  // restore the alias as is.
5613                  if ($this->task->is_samesite()) {
5614                      $fs->create_file_from_reference($info->newfile, $repository->id, $info->oldfile->reference);
5615                      $this->notify_success($info);
5616                      continue;
5617  
5618                  // If we are at other site, we can't restore this alias.
5619                  } else {
5620                      $this->notify_failure($info, 'restoring at another site');
5621                      continue;
5622                  }
5623              }
5624          }
5625          $progress->end_progress();
5626          $rs->close();
5627      }
5628  
5629      /**
5630       * Choose the repository instance that should handle the alias.
5631       *
5632       * At the same site, we can rely on repository instance id and we just
5633       * check it still exists. On other site, try to find matching Server files or
5634       * Legacy course files repository instance. Return null if no matching
5635       * repository instance can be found.
5636       *
5637       * @param stdClass $info
5638       * @return repository|null
5639       */
5640      private function choose_repository(stdClass $info) {
5641          global $DB, $CFG;
5642          require_once($CFG->dirroot.'/repository/lib.php');
5643  
5644          if ($this->task->is_samesite()) {
5645              // We can rely on repository instance id.
5646  
5647              if (array_key_exists($info->oldfile->repositoryid, $this->cachereposbyid)) {
5648                  return $this->cachereposbyid[$info->oldfile->repositoryid];
5649              }
5650  
5651              $this->log('looking for repository instance by id', backup::LOG_DEBUG, $info->oldfile->repositoryid, 1);
5652  
5653              try {
5654                  $this->cachereposbyid[$info->oldfile->repositoryid] = repository::get_repository_by_id($info->oldfile->repositoryid, SYSCONTEXTID);
5655                  return $this->cachereposbyid[$info->oldfile->repositoryid];
5656              } catch (Exception $e) {
5657                  $this->cachereposbyid[$info->oldfile->repositoryid] = null;
5658                  return null;
5659              }
5660  
5661          } else {
5662              // We can rely on repository type only.
5663  
5664              if (empty($info->oldfile->repositorytype)) {
5665                  return null;
5666              }
5667  
5668              if (array_key_exists($info->oldfile->repositorytype, $this->cachereposbytype)) {
5669                  return $this->cachereposbytype[$info->oldfile->repositorytype];
5670              }
5671  
5672              $this->log('looking for repository instance by type', backup::LOG_DEBUG, $info->oldfile->repositorytype, 1);
5673  
5674              // Both Server files and Legacy course files repositories have a single
5675              // instance at the system context to use. Let us try to find it.
5676              if ($info->oldfile->repositorytype === 'local' || $info->oldfile->repositorytype === 'coursefiles'
5677                      || $info->oldfile->repositorytype === 'contentbank') {
5678                  $sql = "SELECT ri.id
5679                            FROM {repository} r
5680                            JOIN {repository_instances} ri ON ri.typeid = r.id
5681                           WHERE r.type = ? AND ri.contextid = ?";
5682                  $ris = $DB->get_records_sql($sql, array($info->oldfile->repositorytype, SYSCONTEXTID));
5683                  if (empty($ris)) {
5684                      return null;
5685                  }
5686                  $repoids = array_keys($ris);
5687                  $repoid = reset($repoids);
5688                  try {
5689                      $this->cachereposbytype[$info->oldfile->repositorytype] = repository::get_repository_by_id($repoid, SYSCONTEXTID);
5690                      return $this->cachereposbytype[$info->oldfile->repositorytype];
5691                  } catch (Exception $e) {
5692                      $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5693                      return null;
5694                  }
5695              }
5696  
5697              $this->cachereposbytype[$info->oldfile->repositorytype] = null;
5698              return null;
5699          }
5700      }
5701  
5702      /**
5703       * Let the user know that the given alias was successfully restored
5704       *
5705       * @param stdClass $info
5706       */
5707      private function notify_success(stdClass $info) {
5708          $filedesc = $this->describe_alias($info);
5709          $this->log('successfully restored alias', backup::LOG_DEBUG, $filedesc, 1);
5710      }
5711  
5712      /**
5713       * Let the user know that the given alias can't be restored
5714       *
5715       * @param stdClass $info
5716       * @param string $reason detailed reason to be logged
5717       */
5718      private function notify_failure(stdClass $info, $reason = '') {
5719          $filedesc = $this->describe_alias($info);
5720          if ($reason) {
5721              $reason = ' ('.$reason.')';
5722          }
5723          $this->log('unable to restore alias'.$reason, backup::LOG_WARNING, $filedesc, 1);
5724          $this->add_result_item('file_aliases_restore_failures', $filedesc);
5725      }
5726  
5727      /**
5728       * Return a human readable description of the alias file
5729       *
5730       * @param stdClass $info
5731       * @return string
5732       */
5733      private function describe_alias(stdClass $info) {
5734  
5735          $filedesc = $this->expected_alias_location($info->newfile);
5736  
5737          if (!is_null($info->oldfile->source)) {
5738              $filedesc .= ' ('.$info->oldfile->source.')';
5739          }
5740  
5741          return $filedesc;
5742      }
5743  
5744      /**
5745       * Return the expected location of a file
5746       *
5747       * Please note this may and may not work as a part of URL to pluginfile.php
5748       * (depends on how the given component/filearea deals with the itemid).
5749       *
5750       * @param stdClass $filerecord
5751       * @return string
5752       */
5753      private function expected_alias_location($filerecord) {
5754  
5755          $filedesc = '/'.$filerecord->contextid.'/'.$filerecord->component.'/'.$filerecord->filearea;
5756          if (!is_null($filerecord->itemid)) {
5757              $filedesc .= '/'.$filerecord->itemid;
5758          }
5759          $filedesc .= $filerecord->filepath.$filerecord->filename;
5760  
5761          return $filedesc;
5762      }
5763  
5764      /**
5765       * Append a value to the given resultset
5766       *
5767       * @param string $name name of the result containing a list of values
5768       * @param mixed $value value to add as another item in that result
5769       */
5770      private function add_result_item($name, $value) {
5771  
5772          $results = $this->task->get_results();
5773  
5774          if (isset($results[$name])) {
5775              if (!is_array($results[$name])) {
5776                  throw new coding_exception('Unable to append a result item into a non-array structure.');
5777              }
5778              $current = $results[$name];
5779              $current[] = $value;
5780              $this->task->add_result(array($name => $current));
5781  
5782          } else {
5783              $this->task->add_result(array($name => array($value)));
5784          }
5785      }
5786  }
5787  
5788  
5789  /**
5790   * Helper code for use by any plugin that stores question attempt data that it needs to back up.
5791   */
5792  trait restore_questions_attempt_data_trait {
5793      /** @var array question_attempt->id to qtype. */
5794      protected $qtypes = array();
5795      /** @var array question_attempt->id to questionid. */
5796      protected $newquestionids = array();
5797  
5798      /**
5799       * Attach below $element (usually attempts) the needed restore_path_elements
5800       * to restore question_usages and all they contain.
5801       *
5802       * If you use the $nameprefix parameter, then you will need to implement some
5803       * extra methods in your class, like
5804       *
5805       * protected function process_{nameprefix}question_attempt($data) {
5806       *     $this->restore_question_usage_worker($data, '{nameprefix}');
5807       * }
5808       * protected function process_{nameprefix}question_attempt($data) {
5809       *     $this->restore_question_attempt_worker($data, '{nameprefix}');
5810       * }
5811       * protected function process_{nameprefix}question_attempt_step($data) {
5812       *     $this->restore_question_attempt_step_worker($data, '{nameprefix}');
5813       * }
5814       *
5815       * @param restore_path_element $element the parent element that the usages are stored inside.
5816       * @param array $paths the paths array that is being built.
5817       * @param string $nameprefix should match the prefix passed to the corresponding
5818       *      backup_questions_activity_structure_step::add_question_usages call.
5819       */
5820      protected function add_question_usages($element, &$paths, $nameprefix = '') {
5821          // Check $element is restore_path_element
5822          if (! $element instanceof restore_path_element) {
5823              throw new restore_step_exception('element_must_be_restore_path_element', $element);
5824          }
5825  
5826          // Check $paths is one array
5827          if (!is_array($paths)) {
5828              throw new restore_step_exception('paths_must_be_array', $paths);
5829          }
5830          $paths[] = new restore_path_element($nameprefix . 'question_usage',
5831                  $element->get_path() . "/{$nameprefix}question_usage");
5832          $paths[] = new restore_path_element($nameprefix . 'question_attempt',
5833                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt");
5834          $paths[] = new restore_path_element($nameprefix . 'question_attempt_step',
5835                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step",
5836                  true);
5837          $paths[] = new restore_path_element($nameprefix . 'question_attempt_step_data',
5838                  $element->get_path() . "/{$nameprefix}question_usage/{$nameprefix}question_attempts/{$nameprefix}question_attempt/{$nameprefix}steps/{$nameprefix}step/{$nameprefix}response/{$nameprefix}variable");
5839      }
5840  
5841      /**
5842       * Process question_usages
5843       */
5844      public function process_question_usage($data) {
5845          $this->restore_question_usage_worker($data, '');
5846      }
5847  
5848      /**
5849       * Process question_attempts
5850       */
5851      public function process_question_attempt($data) {
5852          $this->restore_question_attempt_worker($data, '');
5853      }
5854  
5855      /**
5856       * Process question_attempt_steps
5857       */
5858      public function process_question_attempt_step($data) {
5859          $this->restore_question_attempt_step_worker($data, '');
5860      }
5861  
5862      /**
5863       * This method does the actual work for process_question_usage or
5864       * process_{nameprefix}_question_usage.
5865       * @param array $data the data from the XML file.
5866       * @param string $nameprefix the element name prefix.
5867       */
5868      protected function restore_question_usage_worker($data, $nameprefix) {
5869          global $DB;
5870  
5871          // Clear our caches.
5872          $this->qtypes = array();
5873          $this->newquestionids = array();
5874  
5875          $data = (object)$data;
5876          $oldid = $data->id;
5877  
5878          $data->contextid  = $this->task->get_contextid();
5879  
5880          // Everything ready, insert (no mapping needed)
5881          $newitemid = $DB->insert_record('question_usages', $data);
5882  
5883          $this->inform_new_usage_id($newitemid);
5884  
5885          $this->set_mapping($nameprefix . 'question_usage', $oldid, $newitemid, false);
5886      }
5887  
5888      /**
5889       * When process_question_usage creates the new usage, it calls this method
5890       * to let the activity link to the new usage. For example, the quiz uses
5891       * this method to set quiz_attempts.uniqueid to the new usage id.
5892       * @param integer $newusageid
5893       */
5894      abstract protected function inform_new_usage_id($newusageid);
5895  
5896      /**
5897       * This method does the actual work for process_question_attempt or
5898       * process_{nameprefix}_question_attempt.
5899       * @param array $data the data from the XML file.
5900       * @param string $nameprefix the element name prefix.
5901       */
5902      protected function restore_question_attempt_worker($data, $nameprefix) {
5903          global $DB;
5904  
5905          $data = (object)$data;
5906          $oldid = $data->id;
5907  
5908          $questioncreated = $this->get_mappingid('question_created', $data->questionid) ? true : false;
5909          $question = $this->get_mapping('question', $data->questionid);
5910          if ($questioncreated) {
5911              $data->questionid = $question->newitemid;
5912          }
5913  
5914          $data->questionusageid = $this->get_new_parentid($nameprefix . 'question_usage');
5915  
5916          if (!property_exists($data, 'variant')) {
5917              $data->variant = 1;
5918          }
5919  
5920          if (!property_exists($data, 'maxfraction')) {
5921              $data->maxfraction = 1;
5922          }
5923  
5924          $newitemid = $DB->insert_record('question_attempts', $data);
5925  
5926          $this->set_mapping($nameprefix . 'question_attempt', $oldid, $newitemid);
5927          if (isset($question->info->qtype)) {
5928              $qtype = $question->info->qtype;
5929          } else {
5930              $qtype = $DB->get_record('question', ['id' => $data->questionid])->qtype;
5931          }
5932          $this->qtypes[$newitemid] = $qtype;
5933          $this->newquestionids[$newitemid] = $data->questionid;
5934      }
5935  
5936      /**
5937       * This method does the actual work for process_question_attempt_step or
5938       * process_{nameprefix}_question_attempt_step.
5939       * @param array $data the data from the XML file.
5940       * @param string $nameprefix the element name prefix.
5941       */
5942      protected function restore_question_attempt_step_worker($data, $nameprefix) {
5943          global $DB;
5944  
5945          $data = (object)$data;
5946          $oldid = $data->id;
5947  
5948          // Pull out the response data.
5949          $response = array();
5950          if (!empty($data->{$nameprefix . 'response'}[$nameprefix . 'variable'])) {
5951              foreach ($data->{$nameprefix . 'response'}[$nameprefix . 'variable'] as $variable) {
5952                  $response[$variable['name']] = $variable['value'];
5953              }
5954          }
5955          unset($data->response);
5956  
5957          $data->questionattemptid = $this->get_new_parentid($nameprefix . 'question_attempt');
5958          $data->userid = $this->get_mappingid('user', $data->userid);
5959  
5960          // Everything ready, insert and create mapping (needed by question_sessions)
5961          $newitemid = $DB->insert_record('question_attempt_steps', $data);
5962          $this->set_mapping('question_attempt_step', $oldid, $newitemid, true);
5963  
5964          // Now process the response data.
5965          $response = $this->questions_recode_response_data(
5966                  $this->qtypes[$data->questionattemptid],
5967                  $this->newquestionids[$data->questionattemptid],
5968                  $data->sequencenumber, $response);
5969  
5970          foreach ($response as $name => $value) {
5971              $row = new stdClass();
5972              $row->attemptstepid = $newitemid;
5973              $row->name = $name;
5974              $row->value = $value;
5975              $DB->insert_record('question_attempt_step_data', $row, false);
5976          }
5977      }
5978  
5979      /**
5980       * Recode the respones data for a particular step of an attempt at at particular question.
5981       * @param string $qtype the question type.
5982       * @param int $newquestionid the question id.
5983       * @param int $sequencenumber the sequence number.
5984       * @param array $response the response data to recode.
5985       */
5986      public function questions_recode_response_data(
5987              $qtype, $newquestionid, $sequencenumber, array $response) {
5988          $qtyperestorer = $this->get_qtype_restorer($qtype);
5989          if ($qtyperestorer) {
5990              $response = $qtyperestorer->recode_response($newquestionid, $sequencenumber, $response);
5991          }
5992          return $response;
5993      }
5994  
5995      /**
5996       * Given a list of question->ids, separated by commas, returns the
5997       * recoded list, with all the restore question mappings applied.
5998       * Note: Used by quiz->questions and quiz_attempts->layout
5999       * Note: 0 = page break (unconverted)
6000       */
6001      protected function questions_recode_layout($layout) {
6002          // Extracts question id from sequence
6003          if ($questionids = explode(',', $layout)) {
6004              foreach ($questionids as $id => $questionid) {
6005                  if ($questionid) { // If it is zero then this is a pagebreak, don't translate
6006                      $newquestionid = $this->get_mappingid('question', $questionid);
6007                      $questionids[$id] = $newquestionid;
6008                  }
6009              }
6010          }
6011          return implode(',', $questionids);
6012      }
6013  
6014      /**
6015       * Get the restore_qtype_plugin subclass for a specific question type.
6016       * @param string $qtype e.g. multichoice.
6017       * @return restore_qtype_plugin instance.
6018       */
6019      protected function get_qtype_restorer($qtype) {
6020          // Build one static cache to store {@link restore_qtype_plugin}
6021          // while we are needing them, just to save zillions of instantiations
6022          // or using static stuff that will break our nice API
6023          static $qtypeplugins = array();
6024  
6025          if (!isset($qtypeplugins[$qtype])) {
6026              $classname = 'restore_qtype_' . $qtype . '_plugin';
6027              if (class_exists($classname)) {
6028                  $qtypeplugins[$qtype] = new $classname('qtype', $qtype, $this);
6029              } else {
6030                  $qtypeplugins[$qtype] = null;
6031              }
6032          }
6033          return $qtypeplugins[$qtype];
6034      }
6035  
6036      protected function after_execute() {
6037          parent::after_execute();
6038  
6039          // Restore any files belonging to responses.
6040          foreach (question_engine::get_all_response_file_areas() as $filearea) {
6041              $this->add_related_files('question', $filearea, 'question_attempt_step');
6042          }
6043      }
6044  }
6045  
6046  /**
6047   * Helper trait to restore question reference data.
6048   */
6049  trait restore_question_reference_data_trait {
6050  
6051      /**
6052       * Attach the question reference data to the restore.
6053       *
6054       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6055       * @param array $paths the paths array that is being built to describe the structure.
6056       */
6057      protected function add_question_references($element, &$paths) {
6058          // Check $element is restore_path_element.
6059          if (! $element instanceof restore_path_element) {
6060              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6061          }
6062  
6063          // Check $paths is one array.
6064          if (!is_array($paths)) {
6065              throw new restore_step_exception('paths_must_be_array', $paths);
6066          }
6067  
6068          $paths[] = new restore_path_element('question_reference',
6069              $element->get_path() . '/question_reference');
6070      }
6071  
6072      /**
6073       * Process question references which replaces the direct connection to quiz slots to question.
6074       *
6075       * @param array $data the data from the XML file.
6076       */
6077      public function process_question_reference($data) {
6078          global $DB;
6079          $data = (object) $data;
6080          $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6081          $data->itemid = $this->get_new_parentid('quiz_question_instance');
6082          if ($entry = $this->get_mappingid('question_bank_entry', $data->questionbankentryid)) {
6083              $data->questionbankentryid = $entry;
6084          }
6085          $DB->insert_record('question_references', $data);
6086      }
6087  }
6088  
6089  /**
6090   * Helper trait to restore question set reference data.
6091   */
6092  trait restore_question_set_reference_data_trait {
6093  
6094      /**
6095       * Attach the question reference data to the restore.
6096       *
6097       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6098       * @param array $paths the paths array that is being built to describe the structure.
6099       */
6100      protected function add_question_set_references($element, &$paths) {
6101          // Check $element is restore_path_element.
6102          if (! $element instanceof restore_path_element) {
6103              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6104          }
6105  
6106          // Check $paths is one array.
6107          if (!is_array($paths)) {
6108              throw new restore_step_exception('paths_must_be_array', $paths);
6109          }
6110  
6111          $paths[] = new restore_path_element('question_set_reference',
6112              $element->get_path() . '/question_set_reference');
6113      }
6114  
6115      /**
6116       * Process question set references data which replaces the random qtype.
6117       *
6118       * @param array $data the data from the XML file.
6119       */
6120      public function process_question_set_reference($data) {
6121          global $DB;
6122          $data = (object) $data;
6123          $data->usingcontextid = $this->get_mappingid('context', $data->usingcontextid);
6124          $data->itemid = $this->get_new_parentid('quiz_question_instance');
6125          $filtercondition = json_decode($data->filtercondition);
6126          if ($category = $this->get_mappingid('question_category', $filtercondition->questioncategoryid)) {
6127              $filtercondition->questioncategoryid = $category;
6128          }
6129          $data->filtercondition = json_encode($filtercondition);
6130          if ($context = $this->get_mappingid('context', $data->questionscontextid)) {
6131              $data->questionscontextid = $context;
6132          }
6133  
6134          $DB->insert_record('question_set_references', $data);
6135      }
6136  }
6137  
6138  
6139  /**
6140   * Abstract structure step to help activities that store question attempt data.
6141   *
6142   * @copyright 2011 The Open University
6143   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6144   */
6145  abstract class restore_questions_activity_structure_step extends restore_activity_structure_step {
6146      use restore_questions_attempt_data_trait;
6147      use restore_question_reference_data_trait;
6148      use restore_question_set_reference_data_trait;
6149  
6150      /**
6151       * Attach below $element (usually attempts) the needed restore_path_elements
6152       * to restore question attempt data from Moodle 2.0.
6153       *
6154       * When using this method, the parent element ($element) must be defined with
6155       * $grouped = true. Then, in that elements process method, you must call
6156       * {@link process_legacy_attempt_data()} with the groupded data. See, for
6157       * example, the usage of this method in {@link restore_quiz_activity_structure_step}.
6158       * @param restore_path_element $element the parent element. (E.g. a quiz attempt.)
6159       * @param array $paths the paths array that is being built to describe the
6160       *      structure.
6161       */
6162      protected function add_legacy_question_attempt_data($element, &$paths) {
6163          global $CFG;
6164          require_once($CFG->dirroot . '/question/engine/upgrade/upgradelib.php');
6165  
6166          // Check $element is restore_path_element
6167          if (!($element instanceof restore_path_element)) {
6168              throw new restore_step_exception('element_must_be_restore_path_element', $element);
6169          }
6170          // Check $paths is one array
6171          if (!is_array($paths)) {
6172              throw new restore_step_exception('paths_must_be_array', $paths);
6173          }
6174  
6175          $paths[] = new restore_path_element('question_state',
6176                  $element->get_path() . '/states/state');
6177          $paths[] = new restore_path_element('question_session',
6178                  $element->get_path() . '/sessions/session');
6179      }
6180  
6181      protected function get_attempt_upgrader() {
6182          if (empty($this->attemptupgrader)) {
6183              $this->attemptupgrader = new question_engine_attempt_upgrader();
6184              $this->attemptupgrader->prepare_to_restore();
6185          }
6186          return $this->attemptupgrader;
6187      }
6188  
6189      /**
6190       * Process the attempt data defined by {@link add_legacy_question_attempt_data()}.
6191       * @param object $data contains all the grouped attempt data to process.
6192       * @param object $quiz data about the activity the attempts belong to. Required
6193       * fields are (basically this only works for the quiz module):
6194       *      oldquestions => list of question ids in this activity - using old ids.
6195       *      preferredbehaviour => the behaviour to use for questionattempts.
6196       */
6197      protected function process_legacy_quiz_attempt_data($data, $quiz) {
6198          global $DB;
6199          $upgrader = $this->get_attempt_upgrader();
6200  
6201          $data = (object)$data;
6202  
6203          $layout = explode(',', $data->layout);
6204          $newlayout = $layout;
6205  
6206          // Convert each old question_session into a question_attempt.
6207          $qas = array();
6208          foreach (explode(',', $quiz->oldquestions) as $questionid) {
6209              if ($questionid == 0) {
6210                  continue;
6211              }
6212  
6213              $newquestionid = $this->get_mappingid('question', $questionid);
6214              if (!$newquestionid) {
6215                  throw new restore_step_exception('questionattemptreferstomissingquestion',
6216                          $questionid, $questionid);
6217              }
6218  
6219              $question = $upgrader->load_question($newquestionid, $quiz->id);
6220  
6221              foreach ($layout as $key => $qid) {
6222                  if ($qid == $questionid) {
6223                      $newlayout[$key] = $newquestionid;
6224                  }
6225              }
6226  
6227              list($qsession, $qstates) = $this->find_question_session_and_states(
6228                      $data, $questionid);
6229  
6230              if (empty($qsession) || empty($qstates)) {
6231                  throw new restore_step_exception('questionattemptdatamissing',
6232                          $questionid, $questionid);
6233              }
6234  
6235              list($qsession, $qstates) = $this->recode_legacy_response_data(
6236                      $question, $qsession, $qstates);
6237  
6238              $data->layout = implode(',', $newlayout);
6239              $qas[$newquestionid] = $upgrader->convert_question_attempt(
6240                      $quiz, $data, $question, $qsession, $qstates);
6241          }
6242  
6243          // Now create a new question_usage.
6244          $usage = new stdClass();
6245          $usage->component = 'mod_quiz';
6246          $usage->contextid = $this->get_mappingid('context', $this->task->get_old_contextid());
6247          $usage->preferredbehaviour = $quiz->preferredbehaviour;
6248          $usage->id = $DB->insert_record('question_usages', $usage);
6249  
6250          $this->inform_new_usage_id($usage->id);
6251  
6252          $data->uniqueid = $usage->id;
6253          $upgrader->save_usage($quiz->preferredbehaviour, $data, $qas,
6254                  $this->questions_recode_layout($quiz->oldquestions));
6255      }
6256  
6257      protected function find_question_session_and_states($data, $questionid) {
6258          $qsession = null;
6259          foreach ($data->sessions['session'] as $session) {
6260              if ($session['questionid'] == $questionid) {
6261                  $qsession = (object) $session;
6262                  break;
6263              }
6264          }
6265  
6266          $qstates = array();
6267          foreach ($data->states['state'] as $state) {
6268              if ($state['question'] == $questionid) {
6269                  // It would be natural to use $state['seq_number'] as the array-key
6270                  // here, but it seems that buggy behaviour in 2.0 and early can
6271                  // mean that that is not unique, so we use id, which is guaranteed
6272                  // to be unique.
6273                  $qstates[$state['id']] = (object) $state;
6274              }
6275          }
6276          ksort($qstates);
6277          $qstates = array_values($qstates);
6278  
6279          return array($qsession, $qstates);
6280      }
6281  
6282      /**
6283       * Recode any ids in the response data
6284       * @param object $question the question data
6285       * @param object $qsession the question sessions.
6286       * @param array $qstates the question states.
6287       */
6288      protected function recode_legacy_response_data($question, $qsession, $qstates) {
6289          $qsession->questionid = $question->id;
6290  
6291          foreach ($qstates as &$state) {
6292              $state->question = $question->id;
6293              $state->answer = $this->restore_recode_legacy_answer($state, $question->qtype);
6294          }
6295  
6296          return array($qsession, $qstates);
6297      }
6298  
6299      /**
6300       * Recode the legacy answer field.
6301       * @param object $state the state to recode the answer of.
6302       * @param string $qtype the question type.
6303       */
6304      public function restore_recode_legacy_answer($state, $qtype) {
6305          $restorer = $this->get_qtype_restorer($qtype);
6306          if ($restorer) {
6307              return $restorer->recode_legacy_state_answer($state);
6308          } else {
6309              return $state->answer;
6310          }
6311      }
6312  }
6313  
6314  
6315  /**
6316   * Restore completion defaults for each module type
6317   *
6318   * @package     core_backup
6319   * @copyright   2017 Marina Glancy
6320   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6321   */
6322  class restore_completion_defaults_structure_step extends restore_structure_step {
6323      /**
6324       * To conditionally decide if this step must be executed.
6325       */
6326      protected function execute_condition() {
6327          // No completion on the front page.
6328          if ($this->get_courseid() == SITEID) {
6329              return false;
6330          }
6331  
6332          // No default completion info found, don't execute.
6333          $fullpath = $this->task->get_taskbasepath();
6334          $fullpath = rtrim($fullpath, '/') . '/' . $this->filename;
6335          if (!file_exists($fullpath)) {
6336              return false;
6337          }
6338  
6339          // Arrived here, execute the step.
6340          return true;
6341      }
6342  
6343      /**
6344       * Function that will return the structure to be processed by this restore_step.
6345       *
6346       * @return restore_path_element[]
6347       */
6348      protected function define_structure() {
6349          return [new restore_path_element('completion_defaults', '/course_completion_defaults/course_completion_default')];
6350      }
6351  
6352      /**
6353       * Processor for path element 'completion_defaults'
6354       *
6355       * @param stdClass|array $data
6356       */
6357      protected function process_completion_defaults($data) {
6358          global $DB;
6359  
6360          $data = (array)$data;
6361          $oldid = $data['id'];
6362          unset($data['id']);
6363  
6364          // Find the module by name since id may be different in another site.
6365          if (!$mod = $DB->get_record('modules', ['name' => $data['modulename']])) {
6366              return;
6367          }
6368          unset($data['modulename']);
6369  
6370          // Find the existing record.
6371          $newid = $DB->get_field('course_completion_defaults', 'id',
6372              ['course' => $this->task->get_courseid(), 'module' => $mod->id]);
6373          if (!$newid) {
6374              $newid = $DB->insert_record('course_completion_defaults',
6375                  ['course' => $this->task->get_courseid(), 'module' => $mod->id] + $data);
6376          } else {
6377              $DB->update_record('course_completion_defaults', ['id' => $newid] + $data);
6378          }
6379  
6380          // Save id mapping for restoring associated events.
6381          $this->set_mapping('course_completion_defaults', $oldid, $newid);
6382      }
6383  }
6384  
6385  /**
6386   * Index course after restore.
6387   *
6388   * @package core_backup
6389   * @copyright 2017 The Open University
6390   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6391   */
6392  class restore_course_search_index extends restore_execution_step {
6393      /**
6394       * When this step is executed, we add the course context to the queue for reindexing.
6395       */
6396      protected function define_execution() {
6397          $context = \context_course::instance($this->task->get_courseid());
6398          \core_search\manager::request_index($context);
6399      }
6400  }
6401  
6402  /**
6403   * Index activity after restore (when not restoring whole course).
6404   *
6405   * @package core_backup
6406   * @copyright 2017 The Open University
6407   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6408   */
6409  class restore_activity_search_index extends restore_execution_step {
6410      /**
6411       * When this step is executed, we add the activity context to the queue for reindexing.
6412       */
6413      protected function define_execution() {
6414          $context = \context::instance_by_id($this->task->get_contextid());
6415          \core_search\manager::request_index($context);
6416      }
6417  }
6418  
6419  /**
6420   * Index block after restore (when not restoring whole course).
6421   *
6422   * @package core_backup
6423   * @copyright 2017 The Open University
6424   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6425   */
6426  class restore_block_search_index extends restore_execution_step {
6427      /**
6428       * When this step is executed, we add the block context to the queue for reindexing.
6429       */
6430      protected function define_execution() {
6431          // A block in the restore list may be skipped because a duplicate is detected.
6432          // In this case, there is no new blockid (or context) to get.
6433          if (!empty($this->task->get_blockid())) {
6434              $context = \context_block::instance($this->task->get_blockid());
6435              \core_search\manager::request_index($context);
6436          }
6437      }
6438  }
6439  
6440  /**
6441   * Restore action events.
6442   *
6443   * @package     core_backup
6444   * @copyright   2017 onwards Ankit Agarwal
6445   * @license     http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6446   */
6447  class restore_calendar_action_events extends restore_execution_step {
6448      /**
6449       * What to do when this step is executed.
6450       */
6451      protected function define_execution() {
6452          // We just queue the task here rather trying to recreate everything manually.
6453          // The task will automatically populate all data.
6454          $task = new \core\task\refresh_mod_calendar_events_task();
6455          $task->set_custom_data(array('courseid' => $this->get_courseid()));
6456          \core\task\manager::queue_adhoc_task($task, true);
6457      }
6458  }