Updater.php 13.2 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Updater\Updater.
6 7
 */

8 9
namespace Drupal\Core\Updater;

10
use Drupal\Component\Utility\Unicode;
11
use Drupal\Core\FileTransfer\FileTransferException;
12
use Drupal\Core\FileTransfer\FileTransfer;
13

14
/**
15
 * Defines the base class for Updaters used in Drupal.
16
 */
17
class Updater {
18 19

  /**
20
   * Directory to install from.
21
   *
22
   * @var string
23
   */
24
  public $source;
25

26 27 28 29 30 31 32
  /**
   * The root directory under which new projects will be copied.
   *
   * @var string
   */
  protected $root;

33
  /**
34
   * Constructs a new updater.
35
   *
36 37
   * @param string $source
   *   Directory to install from.
38 39 40 41
   * @param string $root
   *   The root directory under which the project will be copied to if it's a
   *   new project. Usually this is the app root (the directory in which the
   *   Drupal site is installed).
42
   */
43
  public function __construct($source, $root) {
44
    $this->source = $source;
45
    $this->root = $root;
46 47 48 49 50
    $this->name = self::getProjectName($source);
    $this->title = self::getProjectTitle($source);
  }

  /**
51
   * Returns an Updater of the appropriate type depending on the source.
52 53 54 55 56 57
   *
   * If a directory is provided which contains a module, will return a
   * ModuleUpdater.
   *
   * @param string $source
   *   Directory of a Drupal project.
58 59 60 61
   * @param string $root
   *   The root directory under which the project will be copied to if it's a
   *   new project. Usually this is the app root (the directory in which the
   *   Drupal site is installed).
62
   *
63
   * @return \Drupal\Core\Updater\Updater
64 65
   *   A new Drupal\Core\Updater\Updater object.
   *
66
   * @throws \Drupal\Core\Updater\UpdaterException
67
   */
68
  public static function factory($source, $root) {
69 70 71 72 73 74
    if (is_dir($source)) {
      $updater = self::getUpdaterFromDirectory($source);
    }
    else {
      throw new UpdaterException(t('Unable to determine the type of the source directory.'));
    }
75
    return new $updater($source, $root);
76 77 78
  }

  /**
79
   * Determines which Updater class can operate on the given directory.
80 81 82 83 84 85
   *
   * @param string $directory
   *   Extracted Drupal project.
   *
   * @return string
   *   The class name which can work with this project type.
86
   *
87
   * @throws \Drupal\Core\Updater\UpdaterException
88 89 90 91 92 93 94 95 96 97 98 99 100 101
   */
  public static function getUpdaterFromDirectory($directory) {
    // Gets a list of possible implementing classes.
    $updaters = drupal_get_updaters();
    foreach ($updaters as $updater) {
      $class = $updater['class'];
      if (call_user_func(array($class, 'canUpdateDirectory'), $directory)) {
        return $class;
      }
    }
    throw new UpdaterException(t('Cannot determine the type of project.'));
  }

  /**
102
   * Determines what the most important (or only) info file is in a directory.
103 104 105 106 107 108 109 110 111 112 113 114
   *
   * Since there is no enforcement of which info file is the project's "main"
   * info file, this will get one with the same name as the directory, or the
   * first one it finds.  Not ideal, but needs a larger solution.
   *
   * @param string $directory
   *   Directory to search in.
   *
   * @return string
   *   Path to the info file.
   */
  public static function findInfoFile($directory) {
115
    $info_files = file_scan_directory($directory, '/.*\.info.yml$/');
116 117 118 119
    if (!$info_files) {
      return FALSE;
    }
    foreach ($info_files as $info_file) {
120
      if (Unicode::substr($info_file->filename, 0, -9) == drupal_basename($directory)) {
121 122 123 124 125 126 127 128 129
        // Info file Has the same name as the directory, return it.
        return $info_file->uri;
      }
    }
    // Otherwise, return the first one.
    $info_file = array_shift($info_files);
    return $info_file->uri;
  }

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  /**
   * Get Extension information from directory.
   *
   * @param string $directory
   *   Directory to search in.
   *
   * @return array
   *   Extension info.
   *
   * @throws \Drupal\Core\Updater\UpdaterException
   *   If the info parser does not provide any info.
   */
  protected static function getExtensionInfo($directory) {
    $info_file = static::findInfoFile($directory);
    $info = \Drupal::service('info_parser')->parse($info_file);
    if (empty($info)) {
      throw new UpdaterException(t('Unable to parse info file: %info_file.', ['%info_file' => $info_file]));
    }

    return $info;
  }

152
  /**
153
   * Gets the name of the project directory (basename).
154
   *
155 156
   * @todo It would be nice, if projects contained an info file which could
   *   provide their canonical name.
157 158 159 160 161 162 163 164 165 166 167
   *
   * @param string $directory
   *
   * @return string
   *   The name of the project.
   */
  public static function getProjectName($directory) {
    return drupal_basename($directory);
  }

  /**
168
   * Returns the project name from a Drupal info file.
169 170 171 172 173 174
   *
   * @param string $directory
   *   Directory to search for the info file.
   *
   * @return string
   *   The title of the project.
175
   *
176
   * @throws \Drupal\Core\Updater\UpdaterException
177 178 179
   */
  public static function getProjectTitle($directory) {
    $info_file = self::findInfoFile($directory);
180
    $info = \Drupal::service('info_parser')->parse($info_file);
181 182 183 184 185 186 187
    if (empty($info)) {
      throw new UpdaterException(t('Unable to parse info file: %info_file.', array('%info_file' => $info_file)));
    }
    return $info['name'];
  }

  /**
188
   * Stores the default parameters for the Updater.
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
   *
   * @param array $overrides
   *   An array of overrides for the default parameters.
   *
   * @return array
   *   An array of configuration parameters for an update or install operation.
   */
  protected function getInstallArgs($overrides = array()) {
    $args = array(
      'make_backup' => FALSE,
      'install_dir' => $this->getInstallDirectory(),
      'backup_dir'  => $this->getBackupDir(),
    );
    return array_merge($args, $overrides);
  }

  /**
206
   * Updates a Drupal project and returns a list of next actions.
207
   *
208
   * @param \Drupal\Core\FileTransfer\FileTransfer $filetransfer
209 210 211 212 213 214 215
   *   Object that is a child of FileTransfer. Used for moving files
   *   to the server.
   * @param array $overrides
   *   An array of settings to override defaults; see self::getInstallArgs().
   *
   * @return array
   *   An array of links which the user may need to complete the update
216
   *
217 218
   * @throws \Drupal\Core\Updater\UpdaterException
   * @throws \Drupal\Core\Updater\UpdaterFileTransferException
219 220 221 222 223 224 225 226
   */
  public function update(&$filetransfer, $overrides = array()) {
    try {
      // Establish arguments with possible overrides.
      $args = $this->getInstallArgs($overrides);

      // Take a Backup.
      if ($args['make_backup']) {
227
        $this->makeBackup($filetransfer, $args['install_dir'], $args['backup_dir']);
228 229 230 231 232 233 234 235 236 237
      }

      if (!$this->name) {
        // This is bad, don't want to delete the install directory.
        throw new UpdaterException(t('Fatal error in update, cowardly refusing to wipe out the install directory.'));
      }

      // Make sure the installation parent directory exists and is writable.
      $this->prepareInstallDirectory($filetransfer, $args['install_dir']);

238
      // Note: If the project is installed in the top-level, it will not be
239
      // deleted. It will be installed in sites/default as that will override
240
      // the top-level reference and not break other sites which are using it.
241 242 243 244 245 246 247 248 249 250 251 252
      if (is_dir($args['install_dir'] . '/' . $this->name)) {
        // Remove the existing installed file.
        $filetransfer->removeDirectory($args['install_dir'] . '/' . $this->name);
      }

      // Copy the directory in place.
      $filetransfer->copyDirectory($this->source, $args['install_dir']);

      // Make sure what we just installed is readable by the web server.
      $this->makeWorldReadable($filetransfer, $args['install_dir'] . '/' . $this->name);

      // Run the updates.
253
      // @todo Decide if we want to implement this.
254 255 256 257 258 259
      $this->postUpdate();

      // For now, just return a list of links of things to do.
      return $this->postUpdateTasks();
    }
    catch (FileTransferException $e) {
260
      throw new UpdaterFileTransferException(t('File Transfer failed, reason: @reason', array('@reason' => strtr($e->getMessage(), $e->arguments))));
261 262 263 264 265 266
    }
  }

  /**
   * Installs a Drupal project, returns a list of next actions.
   *
267
   * @param \Drupal\Core\FileTransfer\FileTransfer $filetransfer
268 269 270 271 272 273
   *   Object that is a child of FileTransfer.
   * @param array $overrides
   *   An array of settings to override defaults; see self::getInstallArgs().
   *
   * @return array
   *   An array of links which the user may need to complete the install.
274
   *
275
   * @throws \Drupal\Core\Updater\UpdaterFileTransferException
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
   */
  public function install(&$filetransfer, $overrides = array()) {
    try {
      // Establish arguments with possible overrides.
      $args = $this->getInstallArgs($overrides);

      // Make sure the installation parent directory exists and is writable.
      $this->prepareInstallDirectory($filetransfer, $args['install_dir']);

      // Copy the directory in place.
      $filetransfer->copyDirectory($this->source, $args['install_dir']);

      // Make sure what we just installed is readable by the web server.
      $this->makeWorldReadable($filetransfer, $args['install_dir'] . '/' . $this->name);

      // Potentially enable something?
292
      // @todo Decide if we want to implement this.
293 294 295 296 297
      $this->postInstall();
      // For now, just return a list of links of things to do.
      return $this->postInstallTasks();
    }
    catch (FileTransferException $e) {
298
      throw new UpdaterFileTransferException(t('File Transfer failed, reason: @reason', array('@reason' => strtr($e->getMessage(), $e->arguments))));
299 300 301 302
    }
  }

  /**
303
   * Makes sure the installation parent directory exists and is writable.
304
   *
305
   * @param \Drupal\Core\FileTransfer\FileTransfer $filetransfer
306 307 308
   *   Object which is a child of FileTransfer.
   * @param string $directory
   *   The installation directory to prepare.
309
   *
310
   * @throws \Drupal\Core\Updater\UpdaterException
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
   */
  public function prepareInstallDirectory(&$filetransfer, $directory) {
    // Make the parent dir writable if need be and create the dir.
    if (!is_dir($directory)) {
      $parent_dir = dirname($directory);
      if (!is_writable($parent_dir)) {
        @chmod($parent_dir, 0755);
        // It is expected that this will fail if the directory is owned by the
        // FTP user. If the FTP user == web server, it will succeed.
        try {
          $filetransfer->createDirectory($directory);
          $this->makeWorldReadable($filetransfer, $directory);
        }
        catch (FileTransferException $e) {
          // Probably still not writable. Try to chmod and do it again.
326
          // @todo Make a new exception class so we can catch it differently.
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
          try {
            $old_perms = substr(sprintf('%o', fileperms($parent_dir)), -4);
            $filetransfer->chmod($parent_dir, 0755);
            $filetransfer->createDirectory($directory);
            $this->makeWorldReadable($filetransfer, $directory);
            // Put the permissions back.
            $filetransfer->chmod($parent_dir, intval($old_perms, 8));
          }
          catch (FileTransferException $e) {
            $message = t($e->getMessage(), $e->arguments);
            $throw_message = t('Unable to create %directory due to the following: %reason', array('%directory' => $directory, '%reason' => $message));
            throw new UpdaterException($throw_message);
          }
        }
        // Put the parent directory back.
        @chmod($parent_dir, 0555);
      }
    }
  }

  /**
348
   * Ensures that a given directory is world readable.
349
   *
350
   * @param \Drupal\Core\FileTransfer\FileTransfer $filetransfer
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
   *   Object which is a child of FileTransfer.
   * @param string $path
   *   The file path to make world readable.
   * @param bool $recursive
   *   If the chmod should be applied recursively.
   */
  public function makeWorldReadable(&$filetransfer, $path, $recursive = TRUE) {
    if (!is_executable($path)) {
      // Set it to read + execute.
      $new_perms = substr(sprintf('%o', fileperms($path)), -4, -1) . "5";
      $filetransfer->chmod($path, intval($new_perms, 8), $recursive);
    }
  }

  /**
366
   * Performs a backup.
367
   *
368
   * @param \Drupal\Core\FileTransfer\FileTransfer $filetransfer
369 370 371 372 373 374
   *   Object which is a child of FileTransfer.
   * @param string $from
   *   The file path to copy from.
   * @param string $to
   *   The file path to copy to.
   *
375
   * @todo Not implemented: https://www.drupal.org/node/2474355
376
   */
377
  public function makeBackup(FileTransfer $filetransfer, $from, $to) {
378 379 380
  }

  /**
381
   * Returns the full path to a directory where backups should be written.
382 383
   */
  public function getBackupDir() {
384
    return \Drupal::service('stream_wrapper_manager')->getViaScheme('temporary')->getDirectoryPath();
385 386 387
  }

  /**
388
   * Performs actions after new code is updated.
389 390 391 392 393
   */
  public function postUpdate() {
  }

  /**
394
   * Performs actions after installation.
395 396 397 398 399
   */
  public function postInstall() {
  }

  /**
400
   * Returns an array of links to pages that should be visited post operation.
401 402 403 404 405 406 407 408 409
   *
   * @return array
   *   Links which provide actions to take after the install is finished.
   */
  public function postInstallTasks() {
    return array();
  }

  /**
410
   * Returns an array of links to pages that should be visited post operation.
411 412 413 414 415 416 417 418
   *
   * @return array
   *   Links which provide actions to take after the update is finished.
   */
  public function postUpdateTasks() {
    return array();
  }
}