filetransfer.inc 12 KB

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