summaryrefslogtreecommitdiffstats
path: root/core/lib/Drupal/Core/FileTransfer/FileTransfer.php
blob: e1213925c69d3cfee50eed0fc80ac0e5d7a27c12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
<?php

/**
 * @file
 * Definition of Drupal\Core\FileTransfer\FileTransfer.
 */

namespace Drupal\Core\FileTransfer;

/**
 * Defines the base FileTransfer class.
 *
 * Classes extending this class perform file operations on directories not
 * writable by the webserver. To achieve this, the class should connect back
 * to the server using some backend (for example FTP or SSH). To keep security,
 * the password should always be asked from the user and never stored. For
 * safety, all methods operate only inside a "jail", by default the Drupal root.
 */
abstract class FileTransfer {

  /**
   * The username for this file transfer.
   *
   * @var string
   */
  protected $username;

  /**
   * The password for this file transfer.
   *
   * @var string
   */
  protected $password;

  /**
   * The hostname for this file transfer.
   *
   * @var string
   */
  protected $hostname = 'localhost';

  /**
   * The port for this file transfer.
   *
   * @var int
   */
  protected $port;

  /**
   * Constructs a Drupal\Core\FileTransfer\FileTransfer object.
   *
   * @param $jail
   *   The full path where all file operations performed by this object will
   *   be restricted to. This prevents the FileTransfer classes from being
   *   able to touch other parts of the filesystem.
   */
  function __construct($jail) {
    $this->jail = $jail;
  }

  /**
   * Defines a factory method for this class.
   *
   * Classes that extend this class must override the factory() static method.
   * They should return a new instance of the appropriate FileTransfer subclass.
   *
   * @param string $jail
   *   The full path where all file operations performed by this object will
   *   be restricted to. This prevents the FileTransfer classes from being
   *   able to touch other parts of the filesystem.
   * @param array $settings
   *   An array of connection settings for the FileTransfer subclass. If the
   *   getSettingsForm() method uses any nested settings, the same structure
   *   will be assumed here.
   *
   * @return object
   *   New instance of the appropriate FileTransfer subclass.
   *
   * @throws \Drupal\Core\FileTransfer\FileTransferException
   */
  static function factory($jail, $settings) {
    throw new FileTransferException('FileTransfer::factory() static method not overridden by FileTransfer subclass.');
  }

  /**
   * Implements the magic __get() method.
   *
   * If the connection isn't set to anything, this will call the connect()
   * method and return the result; afterwards, the connection will be returned
   * directly without using this method.
   *
   * @param string $name
   *   The name of the variable to return.
   *
   * @return string|bool
   *   The variable specified in $name.
   */
  function __get($name) {
    if ($name == 'connection') {
      $this->connect();
      return $this->connection;
    }

    if ($name == 'chroot') {
      $this->setChroot();
      return $this->chroot;
    }
  }

  /**
   * Connects to the server.
   */
  abstract protected function connect();

  /**
   * Copies a directory.
   *
   * @param string $source
   *   The source path.
   * @param string $destination
   *   The destination path.
   */
  public final function copyDirectory($source, $destination) {
    $source = $this->sanitizePath($source);
    $destination = $this->fixRemotePath($destination);
    $this->checkPath($destination);
    $this->copyDirectoryJailed($source, $destination);
  }

  /**
   * Changes the permissions of the specified $path (file or directory).
   *
   * @param string $path
   *   The file / directory to change the permissions of.
   * @param int $mode
   *   The new file permission mode to be passed to chmod().
   * @param bool $recursive
   *   Pass TRUE to recursively chmod the entire directory specified in $path.
   *
   * @throws \Drupal\Core\FileTransfer\FileTransferException
   *
   * @see http://php.net/chmod
   */
  public final function chmod($path, $mode, $recursive = FALSE) {
    if (!($this instanceof ChmodInterface)) {
      throw new FileTransferException('Unable to change file permissions');
    }
    $path = $this->sanitizePath($path);
    $path = $this->fixRemotePath($path);
    $this->checkPath($path);
    $this->chmodJailed($path, $mode, $recursive);
  }

  /**
   * Creates a directory.
   *
   * @param string $directory
   *   The directory to be created.
   */
  public final function createDirectory($directory) {
    $directory = $this->fixRemotePath($directory);
    $this->checkPath($directory);
    $this->createDirectoryJailed($directory);
  }

  /**
   * Removes a directory.
   *
   * @param string $directory
   *   The directory to be removed.
   */
  public final function removeDirectory($directory) {
    $directory = $this->fixRemotePath($directory);
    $this->checkPath($directory);
    $this->removeDirectoryJailed($directory);
  }

  /**
   * Copies a file.
   *
   * @param string $source
   *   The source file.
   * @param string $destination
   *   The destination file.
   */
  public final function copyFile($source, $destination) {
    $source = $this->sanitizePath($source);
    $destination = $this->fixRemotePath($destination);
    $this->checkPath($destination);
    $this->copyFileJailed($source, $destination);
  }

  /**
   * Removes a file.
   *
   * @param string $destination
   *   The destination file to be removed.
   */
  public final function removeFile($destination) {
    $destination = $this->fixRemotePath($destination);
    $this->checkPath($destination);
    $this->removeFileJailed($destination);
  }

  /**
   * Checks that the path is inside the jail and throws an exception if not.
   *
   * @param string $path
   *   A path to check against the jail.
   *
   * @throws \Drupal\Core\FileTransfer\FileTransferException
   */
  protected final function checkPath($path) {
    $full_jail = $this->chroot . $this->jail;
    $full_path = drupal_realpath(substr($this->chroot . $path, 0, strlen($full_jail)));
    $full_path = $this->fixRemotePath($full_path, FALSE);
    if ($full_jail !== $full_path) {
      throw new FileTransferException('@directory is outside of the @jail', NULL, array('@directory' => $path, '@jail' => $this->jail));
    }
  }

  /**
   * Returns a modified path suitable for passing to the server.
   *
   * If a path is a windows path, makes it POSIX compliant by removing the drive
   * letter. If $this->chroot has a value and $strip_chroot is TRUE, it is
   * stripped from the path to allow for chroot'd filetransfer systems.
   *
   * @param string $path
   *   The path to modify.
   * @param bool $strip_chroot
   *   Whether to remove the path in $this->chroot.
   *
   * @return string
   *   The modified path.
   */
  protected final function fixRemotePath($path, $strip_chroot = TRUE) {
    $path = $this->sanitizePath($path);
    $path = preg_replace('|^([a-z]{1}):|i', '', $path); // Strip out windows driveletter if its there.
    if ($strip_chroot) {
      if ($this->chroot && strpos($path, $this->chroot) === 0) {
        $path = ($path == $this->chroot) ? '' : substr($path, strlen($this->chroot));
      }
    }
    return $path;
  }

  /**
   * Changes backslashes to slashes, also removes a trailing slash.
   *
   * @param string $path
   *   The path to modify.
   *
   * @return string
   *   The modified path.
   */
  function sanitizePath($path) {
    $path = str_replace('\\', '/', $path); // Windows path sanitization.
    if (substr($path, -1) == '/') {
      $path = substr($path, 0, -1);
    }
    return $path;
  }

  /**
   * Copies a directory.
   *
   * We need a separate method to make sure the $destination is in the jail.
   *
   * @param string $source
   *   The source path.
   * @param string $destination
   *   The destination path.
   */
  protected function copyDirectoryJailed($source, $destination) {
    if ($this->isDirectory($destination)) {
      $destination = $destination . '/' . drupal_basename($source);
    }
    $this->createDirectory($destination);
    foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $filename => $file) {
      $relative_path = substr($filename, strlen($source));
      if ($file->isDir()) {
        $this->createDirectory($destination . $relative_path);
      }
      else {
        $this->copyFile($file->getPathName(), $destination . $relative_path);
      }
    }
  }

  /**
   * Creates a directory.
   *
   * @param string $directory
   *   The directory to be created.
   */
  abstract protected function createDirectoryJailed($directory);

  /**
   * Removes a directory.
   *
   * @param string $directory
   *   The directory to be removed.
   */
  abstract protected function removeDirectoryJailed($directory);

  /**
   * Copies a file.
   *
   * @param string $source
   *   The source file.
   * @param string $destination
   *   The destination file.
   */
  abstract protected function copyFileJailed($source, $destination);

  /**
   * Removes a file.
   *
   * @param string $destination
   *   The destination file to be removed.
   */
  abstract protected function removeFileJailed($destination);

  /**
   * Checks if a particular path is a directory.
   *
   * @param string $path
   *   The path to check
   *
   * @return bool
   *   TRUE if the specified path is a directory, FALSE otherwise.
   */
  abstract public function isDirectory($path);

  /**
   * Checks if a particular path is a file (not a directory).
   *
   * @param string $path
   *   The path to check.
   *
   * @return bool
   *   TRUE if the specified path is a file, FALSE otherwise.
   */
  abstract public function isFile($path);

  /**
   * Returns the chroot property for this connection.
   *
   * It does this by moving up the tree until it finds itself
   *
   * @return string|bool
   *   If successful, the chroot path for this connection, otherwise FALSE.
   */
  function findChroot() {
    // If the file exists as is, there is no chroot.
    $path = __FILE__;
    $path = $this->fixRemotePath($path, FALSE);
    if ($this->isFile($path)) {
      return FALSE;
    }

    $path = __DIR__;
    $path = $this->fixRemotePath($path, FALSE);
    $parts = explode('/', $path);
    $chroot = '';
    while (count($parts)) {
      $check = implode($parts, '/');
      if ($this->isFile($check . '/' . drupal_basename(__FILE__))) {
        // Remove the trailing slash.
        return substr($chroot, 0, -1);
      }
      $chroot .= array_shift($parts) . '/';
    }
    return FALSE;
  }

  /**
   * Sets the chroot and changes the jail to match the correct path scheme.
   */
  function setChroot() {
    $this->chroot = $this->findChroot();
    $this->jail = $this->fixRemotePath($this->jail);
  }

  /**
   * Returns a form to collect connection settings credentials.
   *
   * Implementing classes can either extend this form with fields collecting the
   * specific information they need, or override it entirely.
   *
   * @return array
   *   An array that contains a Form API definition.
   */
  public function getSettingsForm() {
    $form['username'] = array(
      '#type' => 'textfield',
      '#title' => t('Username'),
    );
    $form['password'] = array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#description' => t('Your password is not saved in the database and is only used to establish a connection.'),
    );
    $form['advanced'] = array(
      '#type' => 'details',
      '#title' => t('Advanced settings'),
    );
    $form['advanced']['hostname'] = array(
      '#type' => 'textfield',
      '#title' => t('Host'),
      '#default_value' => 'localhost',
      '#description' => t('The connection will be created between your web server and the machine hosting the web server files. In the vast majority of cases, this will be the same machine, and "localhost" is correct.'),
    );
    $form['advanced']['port'] = array(
      '#type' => 'textfield',
      '#title' => t('Port'),
      '#default_value' => NULL,
    );
    return $form;
  }
}