filetransfer.inc 12 KB

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