FtpConnection.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. private \FTP\Connection $connection;
  28. public function __construct(bool $secure, string $hostname, int $port, string $username, string $password) {
  29. if ($secure) {
  30. $connection = ftp_ssl_connect($hostname, $port);
  31. } else {
  32. $connection = ftp_connect($hostname, $port);
  33. }
  34. if ($connection === false) {
  35. throw new \Exception("Failed to connect to ftp");
  36. }
  37. if (ftp_login($connection, $username, $password) === false) {
  38. throw new \Exception("Failed to connect to login to ftp");
  39. }
  40. ftp_pasv($connection, true);
  41. $this->connection = $connection;
  42. }
  43. public function __destruct() {
  44. ftp_close($this->connection);
  45. }
  46. public function setUtf8Mode(): bool {
  47. $response = ftp_raw($this->connection, "OPTS UTF8 ON");
  48. return substr($response[0], 0, 3) === '200';
  49. }
  50. public function fput(string $path, $handle) {
  51. return @ftp_fput($this->connection, $path, $handle, FTP_BINARY);
  52. }
  53. public function fget($handle, string $path) {
  54. return @ftp_fget($this->connection, $handle, $path, FTP_BINARY);
  55. }
  56. public function mkdir(string $path) {
  57. return @ftp_mkdir($this->connection, $path);
  58. }
  59. public function chdir(string $path) {
  60. return @ftp_chdir($this->connection, $path);
  61. }
  62. public function delete(string $path) {
  63. return @ftp_delete($this->connection, $path);
  64. }
  65. public function rmdir(string $path) {
  66. return @ftp_rmdir($this->connection, $path);
  67. }
  68. public function rename(string $source, string $target) {
  69. return @ftp_rename($this->connection, $source, $target);
  70. }
  71. public function mdtm(string $path): int {
  72. $result = @ftp_mdtm($this->connection, $path);
  73. // filezilla doesn't like empty path with mdtm
  74. if ($result === -1 && $path === "") {
  75. $result = @ftp_mdtm($this->connection, "/");
  76. }
  77. return $result;
  78. }
  79. public function size(string $path) {
  80. return @ftp_size($this->connection, $path);
  81. }
  82. public function systype() {
  83. return @ftp_systype($this->connection);
  84. }
  85. public function nlist(string $path) {
  86. $files = @ftp_nlist($this->connection, $path);
  87. return array_map(function ($name) {
  88. if (str_contains($name, '/')) {
  89. $name = basename($name);
  90. }
  91. return $name;
  92. }, $files);
  93. }
  94. public function mlsd(string $path) {
  95. $files = @ftp_mlsd($this->connection, $path);
  96. if ($files !== false) {
  97. return array_map(function ($file) {
  98. if (str_contains($file['name'], '/')) {
  99. $file['name'] = basename($file['name']);
  100. }
  101. return $file;
  102. }, $files);
  103. } else {
  104. // not all servers support mlsd, in those cases we parse the raw list ourselves
  105. $rawList = @ftp_rawlist($this->connection, '-aln ' . $path);
  106. if ($rawList === false) {
  107. return false;
  108. }
  109. return $this->parseRawList($rawList, $path);
  110. }
  111. }
  112. // rawlist parsing logic is based on the ftp implementation from https://github.com/thephpleague/flysystem
  113. private function parseRawList(array $rawList, string $directory): array {
  114. return array_map(function ($item) use ($directory) {
  115. return $this->parseRawListItem($item, $directory);
  116. }, $rawList);
  117. }
  118. private function parseRawListItem(string $item, string $directory): array {
  119. $isWindows = preg_match('/^[0-9]{2,4}-[0-9]{2}-[0-9]{2}/', $item);
  120. return $isWindows ? $this->parseWindowsItem($item, $directory) : $this->parseUnixItem($item, $directory);
  121. }
  122. private function parseUnixItem(string $item, string $directory): array {
  123. $item = preg_replace('#\s+#', ' ', $item, 7);
  124. if (count(explode(' ', $item, 9)) !== 9) {
  125. throw new \RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
  126. }
  127. [$permissions, /* $number */, /* $owner */, /* $group */, $size, $month, $day, $time, $name] = explode(' ', $item, 9);
  128. if ($name === '.') {
  129. $type = 'cdir';
  130. } elseif ($name === '..') {
  131. $type = 'pdir';
  132. } else {
  133. $type = substr($permissions, 0, 1) === 'd' ? 'dir' : 'file';
  134. }
  135. $parsedDate = (new \DateTime())
  136. ->setTimestamp(strtotime("$month $day $time"));
  137. $tomorrow = (new \DateTime())->add(new \DateInterval("P1D"));
  138. // since the provided date doesn't include the year, we either set it to the correct year
  139. // or when the date would otherwise be in the future (by more then 1 day to account for timezone errors)
  140. // we use last year
  141. if ($parsedDate > $tomorrow) {
  142. $parsedDate = $parsedDate->sub(new \DateInterval("P1Y"));
  143. }
  144. $formattedDate = $parsedDate
  145. ->format('YmdHis');
  146. return [
  147. 'type' => $type,
  148. 'name' => $name,
  149. 'modify' => $formattedDate,
  150. 'perm' => $this->normalizePermissions($permissions),
  151. 'size' => (int)$size,
  152. ];
  153. }
  154. private function normalizePermissions(string $permissions) {
  155. $isDir = substr($permissions, 0, 1) === 'd';
  156. // remove the type identifier and only use owner permissions
  157. $permissions = substr($permissions, 1, 4);
  158. // map the string rights to the ftp counterparts
  159. $filePermissionsMap = ['r' => 'r', 'w' => 'fadfw'];
  160. $dirPermissionsMap = ['r' => 'e', 'w' => 'flcdmp'];
  161. $map = $isDir ? $dirPermissionsMap : $filePermissionsMap;
  162. return array_reduce(str_split($permissions), function ($ftpPermissions, $permission) use ($map) {
  163. if (isset($map[$permission])) {
  164. $ftpPermissions .= $map[$permission];
  165. }
  166. return $ftpPermissions;
  167. }, '');
  168. }
  169. private function parseWindowsItem(string $item, string $directory): array {
  170. $item = preg_replace('#\s+#', ' ', trim($item), 3);
  171. if (count(explode(' ', $item, 4)) !== 4) {
  172. throw new \RuntimeException("Metadata can't be parsed from item '$item' , not enough parts.");
  173. }
  174. [$date, $time, $size, $name] = explode(' ', $item, 4);
  175. // Check for the correct date/time format
  176. $format = strlen($date) === 8 ? 'm-d-yH:iA' : 'Y-m-dH:i';
  177. $formattedDate = \DateTime::createFromFormat($format, $date . $time)->format('YmdGis');
  178. if ($name === '.') {
  179. $type = 'cdir';
  180. } elseif ($name === '..') {
  181. $type = 'pdir';
  182. } else {
  183. $type = ($size === '<DIR>') ? 'dir' : 'file';
  184. }
  185. return [
  186. 'type' => $type,
  187. 'name' => $name,
  188. 'modify' => $formattedDate,
  189. 'perm' => ($type === 'file') ? 'adfrw' : 'flcdmpe',
  190. 'size' => (int)$size,
  191. ];
  192. }
  193. }