CopyDirectory.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Storage\PolyFill;
  8. trait CopyDirectory {
  9. /**
  10. * Check if a path is a directory
  11. */
  12. abstract public function is_dir(string $path): bool;
  13. /**
  14. * Check if a file or folder exists
  15. */
  16. abstract public function file_exists(string $path): bool;
  17. /**
  18. * Delete a file or folder
  19. */
  20. abstract public function unlink(string $path): bool;
  21. /**
  22. * Open a directory handle for a folder
  23. *
  24. * @return resource|false
  25. */
  26. abstract public function opendir(string $path);
  27. /**
  28. * Create a new folder
  29. */
  30. abstract public function mkdir(string $path): bool;
  31. public function copy(string $source, string $target): bool {
  32. if ($this->is_dir($source)) {
  33. if ($this->file_exists($target)) {
  34. $this->unlink($target);
  35. }
  36. $this->mkdir($target);
  37. return $this->copyRecursive($source, $target);
  38. } else {
  39. return parent::copy($source, $target);
  40. }
  41. }
  42. /**
  43. * For adapters that don't support copying folders natively
  44. */
  45. protected function copyRecursive(string $source, string $target): bool {
  46. $dh = $this->opendir($source);
  47. $result = true;
  48. while (($file = readdir($dh)) !== false) {
  49. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  50. if ($this->is_dir($source . '/' . $file)) {
  51. $this->mkdir($target . '/' . $file);
  52. $result = $this->copyRecursive($source . '/' . $file, $target . '/' . $file);
  53. } else {
  54. $result = parent::copy($source . '/' . $file, $target . '/' . $file);
  55. }
  56. if (!$result) {
  57. break;
  58. }
  59. }
  60. }
  61. return $result;
  62. }
  63. }