FtpConnection.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2020 Robin Appelman <robin@icewind.nl>
  5. *
  6. * @license GNU AGPL version 3 or any later version
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU Affero General Public License as
  10. * published by the Free Software Foundation, either version 3 of the
  11. * License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. namespace OCA\Files_External\Lib\Storage;
  23. /**
  24. * Low level wrapper around the ftp functions that smooths over some difference between servers
  25. */
  26. class FtpConnection {
  27. /** @var resource|\FTP\Connection */
  28. private $connection;
  29. public function __construct(bool $secure, string $hostname, int $port, string $username, string $password) {
  30. if ($secure) {
  31. $connection = ftp_ssl_connect($hostname, $port);
  32. } else {
  33. $connection = ftp_connect($hostname, $port);
  34. }
  35. if ($connection === false) {
  36. throw new \Exception("Failed to connect to ftp");
  37. }
  38. if (ftp_login($connection, $username, $password) === false) {
  39. throw new \Exception("Failed to connect to login to ftp");
  40. }
  41. ftp_pasv($connection, true);
  42. $this->connection = $connection;
  43. }
  44. public function __destruct() {
  45. if ($this->connection) {
  46. ftp_close($this->connection);
  47. }
  48. $this->connection = null;
  49. }
  50. public function setUtf8Mode(): bool {
  51. $response = ftp_raw($this->connection, "OPTS UTF8 ON");
  52. return substr($response[0], 0, 3) === '200';
  53. }
  54. public function fput(string $path, $handle) {
  55. return @ftp_fput($this->connection, $path, $handle, FTP_BINARY);
  56. }
  57. public function fget($handle, string $path) {
  58. return @ftp_fget($this->connection, $handle, $path, FTP_BINARY);
  59. }
  60. public function mkdir(string $path) {
  61. return @ftp_mkdir($this->connection, $path);
  62. }
  63. public function chdir(string $path) {
  64. return @ftp_chdir($this->connection, $path);
  65. }
  66. public function delete(string $path) {
  67. return @ftp_delete($this->connection, $path);
  68. }
  69. public function rmdir(string $path) {
  70. return @ftp_rmdir($this->connection, $path);
  71. }
  72. public function rename(string $path1, string $path2) {
  73. return @ftp_rename($this->connection, $path1, $path2);
  74. }
  75. public function mdtm(string $path) {
  76. return @ftp_mdtm($this->connection, $path);
  77. }
  78. public function size(string $path) {
  79. return @ftp_size($this->connection, $path);
  80. }
  81. public function systype() {
  82. return @ftp_systype($this->connection);
  83. }
  84. public function nlist(string $path) {
  85. $files = @ftp_nlist($this->connection, $path);
  86. return array_map(function ($name) {
  87. if (strpos($name, '/') !== false) {
  88. $name = basename($name);
  89. }
  90. return $name;
  91. }, $files);
  92. }
  93. public function mlsd(string $path) {
  94. $files = @ftp_mlsd($this->connection, $path);
  95. if ($files !== false) {
  96. return array_map(function ($file) {
  97. if (strpos($file['name'], '/') !== false) {
  98. $file['name'] = basename($file['name']);
  99. }
  100. return $file;
  101. }, $files);
  102. } else {
  103. // not all servers support mlsd, in those cases we parse the raw list ourselves
  104. $rawList = @ftp_rawlist($this->connection, '-aln ' . $path);
  105. if ($rawList === false) {
  106. return false;
  107. }
  108. return $this->parseRawList($rawList, $path);
  109. }
  110. }
  111. // rawlist parsing logic is based on the ftp implementation from https://github.com/thephpleague/flysystem
  112. private function parseRawList(array $rawList, string $directory): array {
  113. return array_map(function ($item) use ($directory) {
  114. return $this->parseRawListItem($item, $directory);
  115. }, $rawList);
  116. }
  117. private function parseRawListItem(string $item, string $directory): array {
  118. $isWindows = preg_match('/^[0-9]{2,4}-[0-9]{2}-[0-9]{2}/', $item);
  119. return $isWindows ? $this->parseWindowsItem($item, $directory) : $this->parseUnixItem($item, $directory);
  120. }
  121. private function parseUnixItem(string $item, string $directory): array {
  122. $item = preg_replace('#\s+#', ' ', $item, 7);
  123. if (count(explode(' ', $item, 9)) !== 9) {
  124. throw new \RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
  125. }
  126. [$permissions, /* $number */, /* $owner */, /* $group */, $size, $month, $day, $time, $name] = explode(' ', $item, 9);
  127. if ($name === '.') {
  128. $type = 'cdir';
  129. } elseif ($name === '..') {
  130. $type = 'pdir';
  131. } else {
  132. $type = substr($permissions, 0, 1) === 'd' ? 'dir' : 'file';
  133. }
  134. $parsedDate = (new \DateTime())
  135. ->setTimestamp(strtotime("$month $day $time"));
  136. $tomorrow = (new \DateTime())->add(new \DateInterval("P1D"));
  137. // since the provided date doesn't include the year, we either set it to the correct year
  138. // or when the date would otherwise be in the future (by more then 1 day to account for timezone errors)
  139. // we use last year
  140. if ($parsedDate > $tomorrow) {
  141. $parsedDate = $parsedDate->sub(new \DateInterval("P1Y"));
  142. }
  143. $formattedDate = $parsedDate
  144. ->format('YmdHis');
  145. return [
  146. 'type' => $type,
  147. 'name' => $name,
  148. 'modify' => $formattedDate,
  149. 'perm' => $this->normalizePermissions($permissions),
  150. 'size' => (int)$size,
  151. ];
  152. }
  153. private function normalizePermissions(string $permissions) {
  154. $isDir = substr($permissions, 0, 1) === 'd';
  155. // remove the type identifier and only use owner permissions
  156. $permissions = substr($permissions, 1, 4);
  157. // map the string rights to the ftp counterparts
  158. $filePermissionsMap = ['r' => 'r', 'w' => 'fadfw'];
  159. $dirPermissionsMap = ['r' => 'e', 'w' => 'flcdmp'];
  160. $map = $isDir ? $dirPermissionsMap : $filePermissionsMap;
  161. return array_reduce(str_split($permissions), function ($ftpPermissions, $permission) use ($map) {
  162. if (isset($map[$permission])) {
  163. $ftpPermissions .= $map[$permission];
  164. }
  165. return $ftpPermissions;
  166. }, '');
  167. }
  168. private function parseWindowsItem(string $item, string $directory): array {
  169. $item = preg_replace('#\s+#', ' ', trim($item), 3);
  170. if (count(explode(' ', $item, 4)) !== 4) {
  171. throw new \RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
  172. }
  173. [$date, $time, $size, $name] = explode(' ', $item, 4);
  174. // Check for the correct date/time format
  175. $format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i';
  176. $formattedDate = \DateTime::createFromFormat($format, $date . $time)->format('YmdGis');
  177. if ($name === '.') {
  178. $type = 'cdir';
  179. } elseif ($name === '..') {
  180. $type = 'pdir';
  181. } else {
  182. $type = ($size === '<DIR>') ? 'dir' : 'file';
  183. }
  184. return [
  185. 'type' => $type,
  186. 'name' => $name,
  187. 'modify' => $formattedDate,
  188. 'perm' => ($type === 'file') ? 'adfrw' : 'flcdmpe',
  189. 'size' => (int)$size,
  190. ];
  191. }
  192. }