You are here

function _demo_reset in Demonstration site (Sandbox / Snapshot) 8

Same name and namespace in other branches
  1. 6 demo.admin.inc \_demo_reset()
  2. 7 demo.admin.inc \_demo_reset()

Reset site using snapshot.

Parameters

$filename: Base snapshot filename, without extension.

$verbose: Whether to output status messages.

2 calls to _demo_reset()
DemoResetConfirm::submitForm in src/Form/DemoResetConfirm.php
Form submission handler.
demo_cron in ./demo.module
Implementation of hook_cron().

File

./demo.module, line 707

Code

function _demo_reset($filename, $verbose = TRUE) {

  // Increase PHP's max_execution_time for large dumps.
  drupal_set_time_limit(600);
  $fileconfig = demo_get_fileconfig($filename);
  if (!file_exists($fileconfig['sqlfile']) || !($fp = fopen($fileconfig['sqlfile'], 'r'))) {
    if ($verbose) {
      \Drupal::messenger()
        ->addError(t('Unable to read file %filename.', [
        '%filename' => $fileconfig['sqlfile'],
      ]));
    }
    \Drupal::logger('demo')
      ->error('Unable to read file %filename.', [
      '%filename' => $fileconfig['sqlfile'],
    ]);
    return FALSE;
  }

  // Load any database information in front of reset.
  $info = demo_get_info($fileconfig['infofile']);
  Drupal::moduleHandler()
    ->invokeAll('demo_reset_before', [
    $filename,
    $info,
    $fileconfig,
  ]);

  // Retain special variables, so the (demonstration) site keeps operating after
  // the reset. Specify NULL instead of default values, so unconfigured
  // variables are not retained, resp., deleted after the reset.
  $variables = [
    // Without the snapshot path, subsequent resets will not work.
    'demo_dump_path' => \Drupal::config('demo.settings')
      ->get('demo_dump_path', NULL),
  ];

  // Temporarily disable foreign key checks for the time of import and before
  // dropping existing tables. Foreign key checks should already be re-enabled
  // as one of the last operations in the SQL dump file.
  // @see demo_dump_db()
  // TODO: Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
  // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
  \Drupal::database()
    ->query("SET FOREIGN_KEY_CHECKS = 0;");

  // Drop tables.
  $is_version_1_0_dump = version_compare($info['version'], '1.1', '<');
  $watchdog = Database::getConnection()
    ->prefixTables('{watchdog}');
  foreach (demo_enum_tables() as $table => $dump_options) {

    // Skip watchdog, except for legacy dumps that included the watchdog table.
    if ($table != $watchdog || $is_version_1_0_dump) {

      // TODO: Drupal Rector Notice: Please delete the following comment after you've made any necessary changes.
      // You will need to use `\Drupal\core\Database\Database::getConnection()` if you do not yet have access to the container here.
      \Drupal::database()
        ->query("DROP TABLE {$table}");
    }
  }

  // Load data from snapshot.
  $success = TRUE;
  $query = '';
  while (!feof($fp)) {
    $line = fgets($fp, 16384);
    if ($line && $line != "\n" && strncmp($line, '--', 2) && strncmp($line, '#', 1)) {
      $query .= $line;
      if (substr($line, -2) == ";\n") {
        $options = [
          'target' => 'default',
          'return' => Database::RETURN_NULL,
        ];
        $stmt = Database::getConnection($options['target'])
          ->prepare($query);
        if (!$stmt
          ->execute([], $options)) {
          if ($verbose) {

            // Don't use t() here, as the locale_* tables might not (yet) exist.
            \Drupal::messenger()
              ->addError(strtr('Query failed: %query', [
              '%query' => $query,
            ]));
          }
          $success = FALSE;
        }
        $query = '';
      }
    }
  }
  fclose($fp);

  // Retain variables.
  // @todo check default value of private dump path.
  foreach ($variables as $key => $value) {
    if (isset($value)) {
      \Drupal::service('config.factory')
        ->getEditable('demo.settings')
        ->set($key, $value)
        ->save();
    }
    else {
      \Drupal::config('demo.settings')
        ->delete($key);
    }
  }
  if ($success) {
    if ($verbose) {
      \Drupal::messenger()
        ->addMessage(t('Restored site from %filename.', [
        '%filename' => $fileconfig['sqlfile'],
      ]));
    }
    \Drupal::logger('demo')
      ->notice('Restored site from %filename.', [
      '%filename' => $fileconfig['sqlfile'],
    ]);

    // Allow other modules to act on successful resets.
    Drupal::moduleHandler()
      ->invokeAll('demo_reset', [
      $filename,
      $info,
      $fileconfig,
    ]);

    // Save request time of last reset, but not during re-installation via
    // demo_profile.
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE !== 'install') {
      \Drupal::service('config.factory')
        ->getEditable('demo.settings')
        ->set('demo_reset_last', \Drupal::time()
        ->getRequestTime())
        ->save();
      $demo_dump_cron = \Drupal::config('demo.settings')
        ->get('demo_dump_cron', 'Set default value');
      \Drupal::service('config.factory')
        ->getEditable('demo.settings')
        ->set('demo_dump_cron', $demo_dump_cron)
        ->save();
    }
  }
  else {
    if ($verbose) {
      \Drupal::messenger()
        ->addError(t('Failed to restore site from %filename.', [
        '%filename' => $fileconfig['sqlfile'],
      ]));
    }
    \Drupal::logger('demo')
      ->error('Unable to read file %filename.', [
      '%filename' => $fileconfig['sqlfile'],
    ]);

    // Save request time of last reset, but not during re-installation via
    // demo_profile.
    if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE !== 'install') {
      $request_time = \Drupal::request()->server
        ->getRequestTime();
      \Drupal::service('config.factory')
        ->getEditable('demo.settings')
        ->set('demo_reset_last', \Drupal::time()
        ->getRequestTime())
        ->save();
      $demo_dump_cron = \Drupal::config('demo.settings')
        ->get('demo_dump_cron', 'Set default value');
      \Drupal::service('config.factory')
        ->getEditable('demo.settings')
        ->set('demo_dump_cron', $demo_dump_cron)
        ->save();
    }
    return $success;
  }
}