Search moodle.org's
Developer Documentation

See Release Notes

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

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

   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   * @package    moodlecore
  20   * @subpackage backup-dbops
  21   * @copyright  2010 onwards Eloy Lafuente (stronk7) {@link http://stronk7.com}
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  /**
  26   * Non instantiable helper class providing DB support to the @restore_controller
  27   *
  28   * This class contains various static methods available for all the DB operations
  29   * performed by the restore_controller class
  30   *
  31   * TODO: Finish phpdocs
  32   */
  33  abstract class restore_controller_dbops extends restore_dbops {
  34  
  35      /**
  36       * Send one restore controller to DB
  37       *
  38       * @param restore_controller $controller controller to send to DB
  39       * @param string $checksum hash of the controller to be checked
  40       * @param bool $includeobj to decide if the object itself must be updated (true) or no (false)
  41       * @param bool $cleanobj to decide if the object itself must be cleaned (true) or no (false)
  42       * @return int id of the controller record in the DB
  43       * @throws backup_controller_exception|restore_dbops_exception
  44       */
  45      public static function save_controller($controller, $checksum, $includeobj = true, $cleanobj = false) {
  46          global $DB;
  47          // Check we are going to save one backup_controller
  48          if (! $controller instanceof restore_controller) {
  49              throw new backup_controller_exception('restore_controller_expected');
  50          }
  51          // Check checksum is ok. Only if we are including object info. Sounds silly but it isn't ;-).
  52          if ($includeobj and !$controller->is_checksum_correct($checksum)) {
  53              throw new restore_dbops_exception('restore_controller_dbops_saving_checksum_mismatch');
  54          }
  55          // Cannot request to $includeobj and $cleanobj at the same time.
  56          if ($includeobj and $cleanobj) {
  57              throw new restore_dbops_exception('restore_controller_dbops_saving_cannot_include_and_delete');
  58          }
  59          // Get all the columns
  60          $rec = new stdclass();
  61          $rec->backupid     = $controller->get_restoreid();
  62          $rec->operation    = $controller->get_operation();
  63          $rec->type         = $controller->get_type();
  64          $rec->itemid       = $controller->get_courseid();
  65          $rec->format       = $controller->get_format();
  66          $rec->interactive  = $controller->get_interactive();
  67          $rec->purpose      = $controller->get_mode();
  68          $rec->userid       = $controller->get_userid();
  69          $rec->status       = $controller->get_status();
  70          $rec->execution    = $controller->get_execution();
  71          $rec->executiontime= $controller->get_executiontime();
  72          $rec->checksum     = $checksum;
  73          // Serialize information
  74          if ($includeobj) {
  75              $rec->controller = base64_encode(serialize($controller));
  76          } else if ($cleanobj) {
  77              $rec->controller = '';
  78          }
  79          // Send it to DB
  80          if ($recexists = $DB->get_record('backup_controllers', array('backupid' => $rec->backupid))) {
  81              $rec->id = $recexists->id;
  82              $rec->timemodified = time();
  83              $DB->update_record('backup_controllers', $rec);
  84          } else {
  85              $rec->timecreated = time();
  86              $rec->timemodified = 0;
  87              $rec->id = $DB->insert_record('backup_controllers', $rec);
  88          }
  89          return $rec->id;
  90      }
  91  
  92      public static function load_controller($restoreid) {
  93          global $DB;
  94          if (! $controllerrec = $DB->get_record('backup_controllers', array('backupid' => $restoreid))) {
  95              throw new backup_dbops_exception('restore_controller_dbops_nonexisting');
  96          }
  97          $controller = unserialize(base64_decode($controllerrec->controller));
  98          if (!is_object($controller)) {
  99              // The controller field of the table did not contain a serialized object.
 100              // It is made empty after it has been used successfully, it is likely that
 101              // the user has pressed the browser back button at some point.
 102              throw new backup_dbops_exception('restore_controller_dbops_loading_invalid_controller');
 103          }
 104          // Check checksum is ok. Sounds silly but it isn't ;-)
 105          if (!$controller->is_checksum_correct($controllerrec->checksum)) {
 106              throw new backup_dbops_exception('restore_controller_dbops_loading_checksum_mismatch');
 107          }
 108          return $controller;
 109      }
 110  
 111      public static function create_restore_temp_tables($restoreid) {
 112          global $CFG, $DB;
 113          $dbman = $DB->get_manager(); // We are going to use database_manager services
 114  
 115          if ($dbman->table_exists('backup_ids_temp')) { // Table exists, from restore prechecks
 116              // TODO: Improve this by inserting/selecting some record to see there is restoreid match
 117              // TODO: If not match, exception, table corresponds to another backup/restore operation
 118              return true;
 119          }
 120          backup_controller_dbops::create_backup_ids_temp_table($restoreid);
 121          backup_controller_dbops::create_backup_files_temp_table($restoreid);
 122          return false;
 123      }
 124  
 125      public static function drop_restore_temp_tables($backupid) {
 126          global $DB;
 127          $dbman = $DB->get_manager(); // We are going to use database_manager services
 128  
 129          $targettablenames = array('backup_ids_temp', 'backup_files_temp');
 130          foreach ($targettablenames as $targettablename) {
 131              $table = new xmldb_table($targettablename);
 132              $dbman->drop_table($table); // And drop it
 133          }
 134          // Invalidate the backup_ids caches.
 135          restore_dbops::reset_backup_ids_cached();
 136      }
 137  
 138      /**
 139       * Sets the default values for the settings in a restore operation
 140       *
 141       * @param restore_controller $controller
 142       */
 143      public static function apply_config_defaults(restore_controller $controller) {
 144  
 145          $settings = array(
 146              'restore_general_users'              => 'users',
 147              'restore_general_enrolments'         => 'enrolments',
 148              'restore_general_role_assignments'   => 'role_assignments',
 149              'restore_general_activities'         => 'activities',
 150              'restore_general_blocks'             => 'blocks',
 151              'restore_general_filters'            => 'filters',
 152              'restore_general_comments'           => 'comments',
 153              'restore_general_badges'             => 'badges',
 154              'restore_general_calendarevents'     => 'calendarevents',
 155              'restore_general_userscompletion'    => 'userscompletion',
 156              'restore_general_logs'               => 'logs',
 157              'restore_general_histories'          => 'grade_histories',
 158              'restore_general_questionbank'       => 'questionbank',
 159              'restore_general_groups'             => 'groups',
 160              'restore_general_competencies'       => 'competencies',
 161              'restore_general_contentbankcontent' => 'contentbankcontent',
 162              'restore_general_legacyfiles'        => 'legacyfiles'
 163          );
 164          self::apply_admin_config_defaults($controller, $settings, true);
 165  
 166          $target = $controller->get_target();
 167          if ($target == backup::TARGET_EXISTING_ADDING || $target == backup::TARGET_CURRENT_ADDING) {
 168              $settings = array(
 169                  'restore_merge_overwrite_conf'  => 'overwrite_conf',
 170                  'restore_merge_course_fullname'  => 'course_fullname',
 171                  'restore_merge_course_shortname' => 'course_shortname',
 172                  'restore_merge_course_startdate' => 'course_startdate',
 173              );
 174              self::apply_admin_config_defaults($controller, $settings, true);
 175          }
 176  
 177          if ($target == backup::TARGET_EXISTING_DELETING || $target == backup::TARGET_CURRENT_DELETING) {
 178              $settings = array(
 179                  'restore_replace_overwrite_conf'  => 'overwrite_conf',
 180                  'restore_replace_course_fullname'  => 'course_fullname',
 181                  'restore_replace_course_shortname' => 'course_shortname',
 182                  'restore_replace_course_startdate' => 'course_startdate',
 183                  'restore_replace_keep_roles_and_enrolments' => 'keep_roles_and_enrolments',
 184                  'restore_replace_keep_groups_and_groupings' => 'keep_groups_and_groupings',
 185              );
 186              self::apply_admin_config_defaults($controller, $settings, true);
 187          }
 188          if ($controller->get_mode() == backup::MODE_IMPORT &&
 189                  (!$controller->get_interactive()) &&
 190                  $controller->get_type() == backup::TYPE_1ACTIVITY) {
 191              // This is duplicate - there is no concept of defaults - these settings must be on.
 192              $settings = array(
 193                      'activities',
 194                      'blocks',
 195                      'filters',
 196                      'questionbank'
 197              );
 198              self::force_enable_settings($controller, $settings);
 199          };
 200  
 201          // Add some dependencies.
 202          $plan = $controller->get_plan();
 203          if ($plan->setting_exists('overwrite_conf')) {
 204              /** @var restore_course_overwrite_conf_setting $overwriteconf */
 205              $overwriteconf = $plan->get_setting('overwrite_conf');
 206              if ($overwriteconf->get_visibility()) {
 207                  foreach (['course_fullname', 'course_shortname', 'course_startdate'] as $settingname) {
 208                      if ($plan->setting_exists($settingname)) {
 209                          $setting = $plan->get_setting($settingname);
 210                          $overwriteconf->add_dependency($setting, setting_dependency::DISABLED_FALSE,
 211                              array('defaultvalue' => $setting->get_value()));
 212                      }
 213                  }
 214              }
 215          }
 216      }
 217  
 218      /**
 219       * Returns the default value to be used for a setting from the admin restore config
 220       *
 221       * @param string $config
 222       * @param backup_setting $setting
 223       * @return mixed
 224       */
 225      private static function get_setting_default($config, $setting) {
 226          $value = get_config('restore', $config);
 227  
 228          if (in_array($setting->get_name(), ['course_fullname', 'course_shortname', 'course_startdate']) &&
 229                  $setting->get_ui() instanceof backup_setting_ui_defaultcustom) {
 230              // Special case - admin config settings course_fullname, etc. are boolean and the restore settings are strings.
 231              $value = (bool)$value;
 232              if ($value) {
 233                  $attributes = $setting->get_ui()->get_attributes();
 234                  $value = $attributes['customvalue'];
 235              }
 236          }
 237  
 238          if ($setting->get_ui() instanceof backup_setting_ui_select) {
 239              // Make sure the value is a valid option in the select element, otherwise just pick the first from the options list.
 240              // Example: enrolments dropdown may not have the "enrol_withusers" option because users info can not be restored.
 241              $options = array_keys($setting->get_ui()->get_values());
 242              if (!in_array($value, $options)) {
 243                  $value = reset($options);
 244              }
 245          }
 246  
 247          return $value;
 248      }
 249  
 250      /**
 251       * Turn these settings on. No defaults from admin settings.
 252       *
 253       * @param restore_controller $controller
 254       * @param array $settings a map from admin config names to setting names (Config name => Setting name)
 255       */
 256      private static function force_enable_settings(restore_controller $controller, array $settings) {
 257          $plan = $controller->get_plan();
 258          foreach ($settings as $config => $settingname) {
 259              $value = true;
 260              if ($plan->setting_exists($settingname)) {
 261                  $setting = $plan->get_setting($settingname);
 262                  // We do not allow this setting to be locked for a duplicate function.
 263                  if ($setting->get_status() !== base_setting::NOT_LOCKED) {
 264                      $setting->set_status(base_setting::NOT_LOCKED);
 265                  }
 266                  $setting->set_value($value);
 267                  $setting->set_status(base_setting::LOCKED_BY_CONFIG);
 268              } else {
 269                  $controller->log('Unknown setting: ' . $settingname, BACKUP::LOG_DEBUG);
 270              }
 271          }
 272      }
 273  
 274      /**
 275       * Sets the controller settings default values from the admin config.
 276       *
 277       * @param restore_controller $controller
 278       * @param array $settings a map from admin config names to setting names (Config name => Setting name)
 279       * @param boolean $uselocks whether "locked" admin settings should be honoured
 280       */
 281      private static function apply_admin_config_defaults(restore_controller $controller, array $settings, $uselocks) {
 282          $plan = $controller->get_plan();
 283          foreach ($settings as $config => $settingname) {
 284              if ($plan->setting_exists($settingname)) {
 285                  $setting = $plan->get_setting($settingname);
 286                  $value = self::get_setting_default($config, $setting);
 287                  $locked = (get_config('restore',$config . '_locked') == true);
 288  
 289                  // Use the original value when this is an import and the setting is unlocked.
 290                  if ($controller->get_mode() == backup::MODE_IMPORT && $controller->get_interactive()) {
 291                      if (!$uselocks || !$locked) {
 292                          $value = $setting->get_value();
 293                      }
 294                  }
 295  
 296                  // We can only update the setting if it isn't already locked by config or permission.
 297                  if ($setting->get_status() != base_setting::LOCKED_BY_CONFIG
 298                          && $setting->get_status() != base_setting::LOCKED_BY_PERMISSION
 299                          && $setting->get_ui()->is_changeable()) {
 300                      $setting->set_value($value);
 301                      if ($uselocks && $locked) {
 302                          $setting->set_status(base_setting::LOCKED_BY_CONFIG);
 303                      }
 304                  }
 305              } else {
 306                  $controller->log('Unknown setting: ' . $settingname, BACKUP::LOG_DEBUG);
 307              }
 308          }
 309      }
 310  }