CopyDirectory.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. * @param string $path
  13. * @return bool
  14. */
  15. abstract public function is_dir($path);
  16. /**
  17. * Check if a file or folder exists
  18. *
  19. * @param string $path
  20. * @return bool
  21. */
  22. abstract public function file_exists($path);
  23. /**
  24. * Delete a file or folder
  25. *
  26. * @param string $path
  27. * @return bool
  28. */
  29. abstract public function unlink($path);
  30. /**
  31. * Open a directory handle for a folder
  32. *
  33. * @param string $path
  34. * @return resource | bool
  35. */
  36. abstract public function opendir($path);
  37. /**
  38. * Create a new folder
  39. *
  40. * @param string $path
  41. * @return bool
  42. */
  43. abstract public function mkdir($path);
  44. public function copy($source, $target) {
  45. if ($this->is_dir($source)) {
  46. if ($this->file_exists($target)) {
  47. $this->unlink($target);
  48. }
  49. $this->mkdir($target);
  50. return $this->copyRecursive($source, $target);
  51. } else {
  52. return parent::copy($source, $target);
  53. }
  54. }
  55. /**
  56. * For adapters that don't support copying folders natively
  57. *
  58. * @param $source
  59. * @param $target
  60. * @return bool
  61. */
  62. protected function copyRecursive($source, $target) {
  63. $dh = $this->opendir($source);
  64. $result = true;
  65. while (($file = readdir($dh)) !== false) {
  66. if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
  67. if ($this->is_dir($source . '/' . $file)) {
  68. $this->mkdir($target . '/' . $file);
  69. $result = $this->copyRecursive($source . '/' . $file, $target . '/' . $file);
  70. } else {
  71. $result = parent::copy($source . '/' . $file, $target . '/' . $file);
  72. }
  73. if (!$result) {
  74. break;
  75. }
  76. }
  77. }
  78. return $result;
  79. }
  80. }