96eb175ab96de05c52c53e1deae737a975eb98ec
[yaffs-website] / web / core / lib / Drupal / Core / FileTransfer / FileTransfer.php
1 <?php
2
3 namespace Drupal\Core\FileTransfer;
4
5 /**
6  * Defines the base FileTransfer class.
7  *
8  * Classes extending this class perform file operations on directories not
9  * writable by the webserver. To achieve this, the class should connect back
10  * to the server using some backend (for example FTP or SSH). To keep security,
11  * the password should always be asked from the user and never stored. For
12  * safety, all methods operate only inside a "jail", by default the Drupal root.
13  */
14 abstract class FileTransfer {
15
16   /**
17    * The username for this file transfer.
18    *
19    * @var string
20    */
21   protected $username;
22
23   /**
24    * The password for this file transfer.
25    *
26    * @var string
27    */
28   protected $password;
29
30   /**
31    * The hostname for this file transfer.
32    *
33    * @var string
34    */
35   protected $hostname = 'localhost';
36
37   /**
38    * The port for this file transfer.
39    *
40    * @var int
41    */
42   protected $port;
43
44   /**
45    * Constructs a Drupal\Core\FileTransfer\FileTransfer object.
46    *
47    * @param $jail
48    *   The full path where all file operations performed by this object will
49    *   be restricted to. This prevents the FileTransfer classes from being
50    *   able to touch other parts of the filesystem.
51    */
52   public function __construct($jail) {
53     $this->jail = $jail;
54   }
55
56   /**
57    * Defines a factory method for this class.
58    *
59    * Classes that extend this class must override the factory() static method.
60    * They should return a new instance of the appropriate FileTransfer subclass.
61    *
62    * @param string $jail
63    *   The full path where all file operations performed by this object will
64    *   be restricted to. This prevents the FileTransfer classes from being
65    *   able to touch other parts of the filesystem.
66    * @param array $settings
67    *   An array of connection settings for the FileTransfer subclass. If the
68    *   getSettingsForm() method uses any nested settings, the same structure
69    *   will be assumed here.
70    *
71    * @return object
72    *   New instance of the appropriate FileTransfer subclass.
73    *
74    * @throws \Drupal\Core\FileTransfer\FileTransferException
75    */
76   public static function factory($jail, $settings) {
77     throw new FileTransferException('FileTransfer::factory() static method not overridden by FileTransfer subclass.');
78   }
79
80   /**
81    * Implements the magic __get() method.
82    *
83    * If the connection isn't set to anything, this will call the connect()
84    * method and return the result; afterwards, the connection will be returned
85    * directly without using this method.
86    *
87    * @param string $name
88    *   The name of the variable to return.
89    *
90    * @return string|bool
91    *   The variable specified in $name.
92    */
93   public function __get($name) {
94     if ($name == 'connection') {
95       $this->connect();
96       return $this->connection;
97     }
98
99     if ($name == 'chroot') {
100       $this->setChroot();
101       return $this->chroot;
102     }
103   }
104
105   /**
106    * Connects to the server.
107    */
108   abstract public function connect();
109
110   /**
111    * Copies a directory.
112    *
113    * @param string $source
114    *   The source path.
115    * @param string $destination
116    *   The destination path.
117    */
118   final public function copyDirectory($source, $destination) {
119     $source = $this->sanitizePath($source);
120     $destination = $this->fixRemotePath($destination);
121     $this->checkPath($destination);
122     $this->copyDirectoryJailed($source, $destination);
123   }
124
125   /**
126    * Changes the permissions of the specified $path (file or directory).
127    *
128    * @param string $path
129    *   The file / directory to change the permissions of.
130    * @param int $mode
131    *   The new file permission mode to be passed to chmod().
132    * @param bool $recursive
133    *   Pass TRUE to recursively chmod the entire directory specified in $path.
134    *
135    * @throws \Drupal\Core\FileTransfer\FileTransferException
136    *
137    * @see http://php.net/chmod
138    */
139   final public function chmod($path, $mode, $recursive = FALSE) {
140     if (!($this instanceof ChmodInterface)) {
141       throw new FileTransferException('Unable to change file permissions');
142     }
143     $path = $this->sanitizePath($path);
144     $path = $this->fixRemotePath($path);
145     $this->checkPath($path);
146     $this->chmodJailed($path, $mode, $recursive);
147   }
148
149   /**
150    * Creates a directory.
151    *
152    * @param string $directory
153    *   The directory to be created.
154    */
155   final public function createDirectory($directory) {
156     $directory = $this->fixRemotePath($directory);
157     $this->checkPath($directory);
158     $this->createDirectoryJailed($directory);
159   }
160
161   /**
162    * Removes a directory.
163    *
164    * @param string $directory
165    *   The directory to be removed.
166    */
167   final public function removeDirectory($directory) {
168     $directory = $this->fixRemotePath($directory);
169     $this->checkPath($directory);
170     $this->removeDirectoryJailed($directory);
171   }
172
173   /**
174    * Copies a file.
175    *
176    * @param string $source
177    *   The source file.
178    * @param string $destination
179    *   The destination file.
180    */
181   final public function copyFile($source, $destination) {
182     $source = $this->sanitizePath($source);
183     $destination = $this->fixRemotePath($destination);
184     $this->checkPath($destination);
185     $this->copyFileJailed($source, $destination);
186   }
187
188   /**
189    * Removes a file.
190    *
191    * @param string $destination
192    *   The destination file to be removed.
193    */
194   final public function removeFile($destination) {
195     $destination = $this->fixRemotePath($destination);
196     $this->checkPath($destination);
197     $this->removeFileJailed($destination);
198   }
199
200   /**
201    * Checks that the path is inside the jail and throws an exception if not.
202    *
203    * @param string $path
204    *   A path to check against the jail.
205    *
206    * @throws \Drupal\Core\FileTransfer\FileTransferException
207    */
208   final protected function checkPath($path) {
209     $full_jail = $this->chroot . $this->jail;
210     $full_path = \Drupal::service('file_system')
211       ->realpath(substr($this->chroot . $path, 0, strlen($full_jail)));
212     $full_path = $this->fixRemotePath($full_path, FALSE);
213     if ($full_jail !== $full_path) {
214       throw new FileTransferException('@directory is outside of the @jail', NULL, ['@directory' => $path, '@jail' => $this->jail]);
215     }
216   }
217
218   /**
219    * Returns a modified path suitable for passing to the server.
220    *
221    * If a path is a windows path, makes it POSIX compliant by removing the drive
222    * letter. If $this->chroot has a value and $strip_chroot is TRUE, it is
223    * stripped from the path to allow for chroot'd filetransfer systems.
224    *
225    * @param string $path
226    *   The path to modify.
227    * @param bool $strip_chroot
228    *   Whether to remove the path in $this->chroot.
229    *
230    * @return string
231    *   The modified path.
232    */
233   final protected function fixRemotePath($path, $strip_chroot = TRUE) {
234     $path = $this->sanitizePath($path);
235     // Strip out windows driveletter if its there.
236     $path = preg_replace('|^([a-z]{1}):|i', '', $path);
237     if ($strip_chroot) {
238       if ($this->chroot && strpos($path, $this->chroot) === 0) {
239         $path = ($path == $this->chroot) ? '' : substr($path, strlen($this->chroot));
240       }
241     }
242     return $path;
243   }
244
245   /**
246    * Changes backslashes to slashes, also removes a trailing slash.
247    *
248    * @param string $path
249    *   The path to modify.
250    *
251    * @return string
252    *   The modified path.
253    */
254   public function sanitizePath($path) {
255     // Windows path sanitization.
256     $path = str_replace('\\', '/', $path);
257     if (substr($path, -1) == '/') {
258       $path = substr($path, 0, -1);
259     }
260     return $path;
261   }
262
263   /**
264    * Copies a directory.
265    *
266    * We need a separate method to make sure the $destination is in the jail.
267    *
268    * @param string $source
269    *   The source path.
270    * @param string $destination
271    *   The destination path.
272    */
273   protected function copyDirectoryJailed($source, $destination) {
274     if ($this->isDirectory($destination)) {
275       $destination = $destination . '/' . drupal_basename($source);
276     }
277     $this->createDirectory($destination);
278     foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $filename => $file) {
279       $relative_path = substr($filename, strlen($source));
280       if ($file->isDir()) {
281         $this->createDirectory($destination . $relative_path);
282       }
283       else {
284         $this->copyFile($file->getPathName(), $destination . $relative_path);
285       }
286     }
287   }
288
289   /**
290    * Creates a directory.
291    *
292    * @param string $directory
293    *   The directory to be created.
294    */
295   abstract protected function createDirectoryJailed($directory);
296
297   /**
298    * Removes a directory.
299    *
300    * @param string $directory
301    *   The directory to be removed.
302    */
303   abstract protected function removeDirectoryJailed($directory);
304
305   /**
306    * Copies a file.
307    *
308    * @param string $source
309    *   The source file.
310    * @param string $destination
311    *   The destination file.
312    */
313   abstract protected function copyFileJailed($source, $destination);
314
315   /**
316    * Removes a file.
317    *
318    * @param string $destination
319    *   The destination file to be removed.
320    */
321   abstract protected function removeFileJailed($destination);
322
323   /**
324    * Checks if a particular path is a directory.
325    *
326    * @param string $path
327    *   The path to check
328    *
329    * @return bool
330    *   TRUE if the specified path is a directory, FALSE otherwise.
331    */
332   abstract public function isDirectory($path);
333
334   /**
335    * Checks if a particular path is a file (not a directory).
336    *
337    * @param string $path
338    *   The path to check.
339    *
340    * @return bool
341    *   TRUE if the specified path is a file, FALSE otherwise.
342    */
343   abstract public function isFile($path);
344
345   /**
346    * Returns the chroot property for this connection.
347    *
348    * It does this by moving up the tree until it finds itself
349    *
350    * @return string|bool
351    *   If successful, the chroot path for this connection, otherwise FALSE.
352    */
353   public function findChroot() {
354     // If the file exists as is, there is no chroot.
355     $path = __FILE__;
356     $path = $this->fixRemotePath($path, FALSE);
357     if ($this->isFile($path)) {
358       return FALSE;
359     }
360
361     $path = __DIR__;
362     $path = $this->fixRemotePath($path, FALSE);
363     $parts = explode('/', $path);
364     $chroot = '';
365     while (count($parts)) {
366       $check = implode($parts, '/');
367       if ($this->isFile($check . '/' . drupal_basename(__FILE__))) {
368         // Remove the trailing slash.
369         return substr($chroot, 0, -1);
370       }
371       $chroot .= array_shift($parts) . '/';
372     }
373     return FALSE;
374   }
375
376   /**
377    * Sets the chroot and changes the jail to match the correct path scheme.
378    */
379   public function setChroot() {
380     $this->chroot = $this->findChroot();
381     $this->jail = $this->fixRemotePath($this->jail);
382   }
383
384   /**
385    * Returns a form to collect connection settings credentials.
386    *
387    * Implementing classes can either extend this form with fields collecting the
388    * specific information they need, or override it entirely.
389    *
390    * @return array
391    *   An array that contains a Form API definition.
392    */
393   public function getSettingsForm() {
394     $form['username'] = [
395       '#type' => 'textfield',
396       '#title' => t('Username'),
397     ];
398     $form['password'] = [
399       '#type' => 'password',
400       '#title' => t('Password'),
401       '#description' => t('Your password is not saved in the database and is only used to establish a connection.'),
402     ];
403     $form['advanced'] = [
404       '#type' => 'details',
405       '#title' => t('Advanced settings'),
406     ];
407     $form['advanced']['hostname'] = [
408       '#type' => 'textfield',
409       '#title' => t('Host'),
410       '#default_value' => 'localhost',
411       '#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.'),
412     ];
413     $form['advanced']['port'] = [
414       '#type' => 'textfield',
415       '#title' => t('Port'),
416       '#default_value' => NULL,
417     ];
418     return $form;
419   }
420
421 }