Upgraded drupal core with security updates
[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   public final 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   public final 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   public final 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   public final 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   public final 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   public final 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   protected final function checkPath($path) {
209     $full_jail = $this->chroot . $this->jail;
210     $full_path = drupal_realpath(substr($this->chroot . $path, 0, strlen($full_jail)));
211     $full_path = $this->fixRemotePath($full_path, FALSE);
212     if ($full_jail !== $full_path) {
213       throw new FileTransferException('@directory is outside of the @jail', NULL, ['@directory' => $path, '@jail' => $this->jail]);
214     }
215   }
216
217   /**
218    * Returns a modified path suitable for passing to the server.
219    *
220    * If a path is a windows path, makes it POSIX compliant by removing the drive
221    * letter. If $this->chroot has a value and $strip_chroot is TRUE, it is
222    * stripped from the path to allow for chroot'd filetransfer systems.
223    *
224    * @param string $path
225    *   The path to modify.
226    * @param bool $strip_chroot
227    *   Whether to remove the path in $this->chroot.
228    *
229    * @return string
230    *   The modified path.
231    */
232   protected final function fixRemotePath($path, $strip_chroot = TRUE) {
233     $path = $this->sanitizePath($path);
234     $path = preg_replace('|^([a-z]{1}):|i', '', $path); // Strip out windows driveletter if its there.
235     if ($strip_chroot) {
236       if ($this->chroot && strpos($path, $this->chroot) === 0) {
237         $path = ($path == $this->chroot) ? '' : substr($path, strlen($this->chroot));
238       }
239     }
240     return $path;
241   }
242
243   /**
244    * Changes backslashes to slashes, also removes a trailing slash.
245    *
246    * @param string $path
247    *   The path to modify.
248    *
249    * @return string
250    *   The modified path.
251    */
252   public function sanitizePath($path) {
253     $path = str_replace('\\', '/', $path); // Windows path sanitization.
254     if (substr($path, -1) == '/') {
255       $path = substr($path, 0, -1);
256     }
257     return $path;
258   }
259
260   /**
261    * Copies a directory.
262    *
263    * We need a separate method to make sure the $destination is in the jail.
264    *
265    * @param string $source
266    *   The source path.
267    * @param string $destination
268    *   The destination path.
269    */
270   protected function copyDirectoryJailed($source, $destination) {
271     if ($this->isDirectory($destination)) {
272       $destination = $destination . '/' . drupal_basename($source);
273     }
274     $this->createDirectory($destination);
275     foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST) as $filename => $file) {
276       $relative_path = substr($filename, strlen($source));
277       if ($file->isDir()) {
278         $this->createDirectory($destination . $relative_path);
279       }
280       else {
281         $this->copyFile($file->getPathName(), $destination . $relative_path);
282       }
283     }
284   }
285
286   /**
287    * Creates a directory.
288    *
289    * @param string $directory
290    *   The directory to be created.
291    */
292   abstract protected function createDirectoryJailed($directory);
293
294   /**
295    * Removes a directory.
296    *
297    * @param string $directory
298    *   The directory to be removed.
299    */
300   abstract protected function removeDirectoryJailed($directory);
301
302   /**
303    * Copies a file.
304    *
305    * @param string $source
306    *   The source file.
307    * @param string $destination
308    *   The destination file.
309    */
310   abstract protected function copyFileJailed($source, $destination);
311
312   /**
313    * Removes a file.
314    *
315    * @param string $destination
316    *   The destination file to be removed.
317    */
318   abstract protected function removeFileJailed($destination);
319
320   /**
321    * Checks if a particular path is a directory.
322    *
323    * @param string $path
324    *   The path to check
325    *
326    * @return bool
327    *   TRUE if the specified path is a directory, FALSE otherwise.
328    */
329   abstract public function isDirectory($path);
330
331   /**
332    * Checks if a particular path is a file (not a directory).
333    *
334    * @param string $path
335    *   The path to check.
336    *
337    * @return bool
338    *   TRUE if the specified path is a file, FALSE otherwise.
339    */
340   abstract public function isFile($path);
341
342   /**
343    * Returns the chroot property for this connection.
344    *
345    * It does this by moving up the tree until it finds itself
346    *
347    * @return string|bool
348    *   If successful, the chroot path for this connection, otherwise FALSE.
349    */
350   public function findChroot() {
351     // If the file exists as is, there is no chroot.
352     $path = __FILE__;
353     $path = $this->fixRemotePath($path, FALSE);
354     if ($this->isFile($path)) {
355       return FALSE;
356     }
357
358     $path = __DIR__;
359     $path = $this->fixRemotePath($path, FALSE);
360     $parts = explode('/', $path);
361     $chroot = '';
362     while (count($parts)) {
363       $check = implode($parts, '/');
364       if ($this->isFile($check . '/' . drupal_basename(__FILE__))) {
365         // Remove the trailing slash.
366         return substr($chroot, 0, -1);
367       }
368       $chroot .= array_shift($parts) . '/';
369     }
370     return FALSE;
371   }
372
373   /**
374    * Sets the chroot and changes the jail to match the correct path scheme.
375    */
376   public function setChroot() {
377     $this->chroot = $this->findChroot();
378     $this->jail = $this->fixRemotePath($this->jail);
379   }
380
381   /**
382    * Returns a form to collect connection settings credentials.
383    *
384    * Implementing classes can either extend this form with fields collecting the
385    * specific information they need, or override it entirely.
386    *
387    * @return array
388    *   An array that contains a Form API definition.
389    */
390   public function getSettingsForm() {
391     $form['username'] = [
392       '#type' => 'textfield',
393       '#title' => t('Username'),
394     ];
395     $form['password'] = [
396       '#type' => 'password',
397       '#title' => t('Password'),
398       '#description' => t('Your password is not saved in the database and is only used to establish a connection.'),
399     ];
400     $form['advanced'] = [
401       '#type' => 'details',
402       '#title' => t('Advanced settings'),
403     ];
404     $form['advanced']['hostname'] = [
405       '#type' => 'textfield',
406       '#title' => t('Host'),
407       '#default_value' => 'localhost',
408       '#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.'),
409     ];
410     $form['advanced']['port'] = [
411       '#type' => 'textfield',
412       '#title' => t('Port'),
413       '#default_value' => NULL,
414     ];
415     return $form;
416   }
417
418 }