View.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176
  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;
  8. use Icewind\Streams\CallbackWrapper;
  9. use OC\Files\Mount\MoveableMount;
  10. use OC\Files\Storage\Storage;
  11. use OC\Share\Share;
  12. use OC\User\LazyUser;
  13. use OC\User\Manager as UserManager;
  14. use OC\User\User;
  15. use OCA\Files_Sharing\SharedMount;
  16. use OCP\Constants;
  17. use OCP\Files\Cache\ICacheEntry;
  18. use OCP\Files\ConnectionLostException;
  19. use OCP\Files\EmptyFileNameException;
  20. use OCP\Files\FileNameTooLongException;
  21. use OCP\Files\ForbiddenException;
  22. use OCP\Files\InvalidCharacterInPathException;
  23. use OCP\Files\InvalidDirectoryException;
  24. use OCP\Files\InvalidPathException;
  25. use OCP\Files\Mount\IMountPoint;
  26. use OCP\Files\NotFoundException;
  27. use OCP\Files\ReservedWordException;
  28. use OCP\IUser;
  29. use OCP\Lock\ILockingProvider;
  30. use OCP\Lock\LockedException;
  31. use OCP\Server;
  32. use OCP\Share\IManager;
  33. use OCP\Share\IShare;
  34. use Psr\Log\LoggerInterface;
  35. /**
  36. * Class to provide access to ownCloud filesystem via a "view", and methods for
  37. * working with files within that view (e.g. read, write, delete, etc.). Each
  38. * view is restricted to a set of directories via a virtual root. The default view
  39. * uses the currently logged in user's data directory as root (parts of
  40. * OC_Filesystem are merely a wrapper for OC\Files\View).
  41. *
  42. * Apps that need to access files outside of the user data folders (to modify files
  43. * belonging to a user other than the one currently logged in, for example) should
  44. * use this class directly rather than using OC_Filesystem, or making use of PHP's
  45. * built-in file manipulation functions. This will ensure all hooks and proxies
  46. * are triggered correctly.
  47. *
  48. * Filesystem functions are not called directly; they are passed to the correct
  49. * \OC\Files\Storage\Storage object
  50. */
  51. class View {
  52. private string $fakeRoot = '';
  53. private ILockingProvider $lockingProvider;
  54. private bool $lockingEnabled;
  55. private bool $updaterEnabled = true;
  56. private UserManager $userManager;
  57. private LoggerInterface $logger;
  58. /**
  59. * @throws \Exception If $root contains an invalid path
  60. */
  61. public function __construct(string $root = '') {
  62. if (!Filesystem::isValidPath($root)) {
  63. throw new \Exception();
  64. }
  65. $this->fakeRoot = $root;
  66. $this->lockingProvider = \OC::$server->get(ILockingProvider::class);
  67. $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
  68. $this->userManager = \OC::$server->getUserManager();
  69. $this->logger = \OC::$server->get(LoggerInterface::class);
  70. }
  71. /**
  72. * @param ?string $path
  73. * @psalm-template S as string|null
  74. * @psalm-param S $path
  75. * @psalm-return (S is string ? string : null)
  76. */
  77. public function getAbsolutePath($path = '/'): ?string {
  78. if ($path === null) {
  79. return null;
  80. }
  81. $this->assertPathLength($path);
  82. if ($path === '') {
  83. $path = '/';
  84. }
  85. if ($path[0] !== '/') {
  86. $path = '/' . $path;
  87. }
  88. return $this->fakeRoot . $path;
  89. }
  90. /**
  91. * Change the root to a fake root
  92. *
  93. * @param string $fakeRoot
  94. */
  95. public function chroot($fakeRoot): void {
  96. if (!$fakeRoot == '') {
  97. if ($fakeRoot[0] !== '/') {
  98. $fakeRoot = '/' . $fakeRoot;
  99. }
  100. }
  101. $this->fakeRoot = $fakeRoot;
  102. }
  103. /**
  104. * Get the fake root
  105. */
  106. public function getRoot(): string {
  107. return $this->fakeRoot;
  108. }
  109. /**
  110. * get path relative to the root of the view
  111. *
  112. * @param string $path
  113. */
  114. public function getRelativePath($path): ?string {
  115. $this->assertPathLength($path);
  116. if ($this->fakeRoot == '') {
  117. return $path;
  118. }
  119. if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
  120. return '/';
  121. }
  122. // missing slashes can cause wrong matches!
  123. $root = rtrim($this->fakeRoot, '/') . '/';
  124. if (!str_starts_with($path, $root)) {
  125. return null;
  126. } else {
  127. $path = substr($path, strlen($this->fakeRoot));
  128. if (strlen($path) === 0) {
  129. return '/';
  130. } else {
  131. return $path;
  132. }
  133. }
  134. }
  135. /**
  136. * Get the mountpoint of the storage object for a path
  137. * ( note: because a storage is not always mounted inside the fakeroot, the
  138. * returned mountpoint is relative to the absolute root of the filesystem
  139. * and does not take the chroot into account )
  140. *
  141. * @param string $path
  142. */
  143. public function getMountPoint($path): string {
  144. return Filesystem::getMountPoint($this->getAbsolutePath($path));
  145. }
  146. /**
  147. * Get the mountpoint of the storage object for a path
  148. * ( note: because a storage is not always mounted inside the fakeroot, the
  149. * returned mountpoint is relative to the absolute root of the filesystem
  150. * and does not take the chroot into account )
  151. *
  152. * @param string $path
  153. */
  154. public function getMount($path): IMountPoint {
  155. return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
  156. }
  157. /**
  158. * Resolve a path to a storage and internal path
  159. *
  160. * @param string $path
  161. * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
  162. */
  163. public function resolvePath($path): array {
  164. $a = $this->getAbsolutePath($path);
  165. $p = Filesystem::normalizePath($a);
  166. return Filesystem::resolvePath($p);
  167. }
  168. /**
  169. * Return the path to a local version of the file
  170. * we need this because we can't know if a file is stored local or not from
  171. * outside the filestorage and for some purposes a local file is needed
  172. *
  173. * @param string $path
  174. */
  175. public function getLocalFile($path): string|false {
  176. $parent = substr($path, 0, strrpos($path, '/') ?: 0);
  177. $path = $this->getAbsolutePath($path);
  178. [$storage, $internalPath] = Filesystem::resolvePath($path);
  179. if (Filesystem::isValidPath($parent) && $storage) {
  180. return $storage->getLocalFile($internalPath);
  181. } else {
  182. return false;
  183. }
  184. }
  185. /**
  186. * the following functions operate with arguments and return values identical
  187. * to those of their PHP built-in equivalents. Mostly they are merely wrappers
  188. * for \OC\Files\Storage\Storage via basicOperation().
  189. */
  190. public function mkdir($path) {
  191. return $this->basicOperation('mkdir', $path, ['create', 'write']);
  192. }
  193. /**
  194. * remove mount point
  195. *
  196. * @param IMountPoint $mount
  197. * @param string $path relative to data/
  198. */
  199. protected function removeMount($mount, $path): bool {
  200. if ($mount instanceof MoveableMount) {
  201. // cut of /user/files to get the relative path to data/user/files
  202. $pathParts = explode('/', $path, 4);
  203. $relPath = '/' . $pathParts[3];
  204. $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  205. \OC_Hook::emit(
  206. Filesystem::CLASSNAME, "umount",
  207. [Filesystem::signal_param_path => $relPath]
  208. );
  209. $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
  210. $result = $mount->removeMount();
  211. $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
  212. if ($result) {
  213. \OC_Hook::emit(
  214. Filesystem::CLASSNAME, "post_umount",
  215. [Filesystem::signal_param_path => $relPath]
  216. );
  217. }
  218. $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  219. return $result;
  220. } else {
  221. // do not allow deleting the storage's root / the mount point
  222. // because for some storages it might delete the whole contents
  223. // but isn't supposed to work that way
  224. return false;
  225. }
  226. }
  227. public function disableCacheUpdate(): void {
  228. $this->updaterEnabled = false;
  229. }
  230. public function enableCacheUpdate(): void {
  231. $this->updaterEnabled = true;
  232. }
  233. protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
  234. if ($this->updaterEnabled) {
  235. if (is_null($time)) {
  236. $time = time();
  237. }
  238. $storage->getUpdater()->update($internalPath, $time, $sizeDifference);
  239. }
  240. }
  241. protected function removeUpdate(Storage $storage, string $internalPath): void {
  242. if ($this->updaterEnabled) {
  243. $storage->getUpdater()->remove($internalPath);
  244. }
  245. }
  246. protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
  247. if ($this->updaterEnabled) {
  248. $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  249. }
  250. }
  251. /**
  252. * @param string $path
  253. * @return bool|mixed
  254. */
  255. public function rmdir($path) {
  256. $absolutePath = $this->getAbsolutePath($path);
  257. $mount = Filesystem::getMountManager()->find($absolutePath);
  258. if ($mount->getInternalPath($absolutePath) === '') {
  259. return $this->removeMount($mount, $absolutePath);
  260. }
  261. if ($this->is_dir($path)) {
  262. $result = $this->basicOperation('rmdir', $path, ['delete']);
  263. } else {
  264. $result = false;
  265. }
  266. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  267. $storage = $mount->getStorage();
  268. $internalPath = $mount->getInternalPath($absolutePath);
  269. $storage->getUpdater()->remove($internalPath);
  270. }
  271. return $result;
  272. }
  273. /**
  274. * @param string $path
  275. * @return resource|false
  276. */
  277. public function opendir($path) {
  278. return $this->basicOperation('opendir', $path, ['read']);
  279. }
  280. /**
  281. * @param string $path
  282. * @return bool|mixed
  283. */
  284. public function is_dir($path) {
  285. if ($path == '/') {
  286. return true;
  287. }
  288. return $this->basicOperation('is_dir', $path);
  289. }
  290. /**
  291. * @param string $path
  292. * @return bool|mixed
  293. */
  294. public function is_file($path) {
  295. if ($path == '/') {
  296. return false;
  297. }
  298. return $this->basicOperation('is_file', $path);
  299. }
  300. /**
  301. * @param string $path
  302. * @return mixed
  303. */
  304. public function stat($path) {
  305. return $this->basicOperation('stat', $path);
  306. }
  307. /**
  308. * @param string $path
  309. * @return mixed
  310. */
  311. public function filetype($path) {
  312. return $this->basicOperation('filetype', $path);
  313. }
  314. /**
  315. * @param string $path
  316. * @return mixed
  317. */
  318. public function filesize(string $path) {
  319. return $this->basicOperation('filesize', $path);
  320. }
  321. /**
  322. * @param string $path
  323. * @return bool|mixed
  324. * @throws InvalidPathException
  325. */
  326. public function readfile($path) {
  327. $this->assertPathLength($path);
  328. if (ob_get_level()) {
  329. ob_end_clean();
  330. }
  331. $handle = $this->fopen($path, 'rb');
  332. if ($handle) {
  333. $chunkSize = 524288; // 512 kiB chunks
  334. while (!feof($handle)) {
  335. echo fread($handle, $chunkSize);
  336. flush();
  337. $this->checkConnectionStatus();
  338. }
  339. fclose($handle);
  340. return $this->filesize($path);
  341. }
  342. return false;
  343. }
  344. /**
  345. * @param string $path
  346. * @param int $from
  347. * @param int $to
  348. * @return bool|mixed
  349. * @throws InvalidPathException
  350. * @throws \OCP\Files\UnseekableException
  351. */
  352. public function readfilePart($path, $from, $to) {
  353. $this->assertPathLength($path);
  354. if (ob_get_level()) {
  355. ob_end_clean();
  356. }
  357. $handle = $this->fopen($path, 'rb');
  358. if ($handle) {
  359. $chunkSize = 524288; // 512 kiB chunks
  360. $startReading = true;
  361. if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
  362. // forward file handle via chunked fread because fseek seem to have failed
  363. $end = $from + 1;
  364. while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
  365. $len = $from - ftell($handle);
  366. if ($len > $chunkSize) {
  367. $len = $chunkSize;
  368. }
  369. $result = fread($handle, $len);
  370. if ($result === false) {
  371. $startReading = false;
  372. break;
  373. }
  374. }
  375. }
  376. if ($startReading) {
  377. $end = $to + 1;
  378. while (!feof($handle) && ftell($handle) < $end) {
  379. $len = $end - ftell($handle);
  380. if ($len > $chunkSize) {
  381. $len = $chunkSize;
  382. }
  383. echo fread($handle, $len);
  384. flush();
  385. $this->checkConnectionStatus();
  386. }
  387. return ftell($handle) - $from;
  388. }
  389. throw new \OCP\Files\UnseekableException('fseek error');
  390. }
  391. return false;
  392. }
  393. private function checkConnectionStatus(): void {
  394. $connectionStatus = \connection_status();
  395. if ($connectionStatus !== CONNECTION_NORMAL) {
  396. throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
  397. }
  398. }
  399. /**
  400. * @param string $path
  401. * @return mixed
  402. */
  403. public function isCreatable($path) {
  404. return $this->basicOperation('isCreatable', $path);
  405. }
  406. /**
  407. * @param string $path
  408. * @return mixed
  409. */
  410. public function isReadable($path) {
  411. return $this->basicOperation('isReadable', $path);
  412. }
  413. /**
  414. * @param string $path
  415. * @return mixed
  416. */
  417. public function isUpdatable($path) {
  418. return $this->basicOperation('isUpdatable', $path);
  419. }
  420. /**
  421. * @param string $path
  422. * @return bool|mixed
  423. */
  424. public function isDeletable($path) {
  425. $absolutePath = $this->getAbsolutePath($path);
  426. $mount = Filesystem::getMountManager()->find($absolutePath);
  427. if ($mount->getInternalPath($absolutePath) === '') {
  428. return $mount instanceof MoveableMount;
  429. }
  430. return $this->basicOperation('isDeletable', $path);
  431. }
  432. /**
  433. * @param string $path
  434. * @return mixed
  435. */
  436. public function isSharable($path) {
  437. return $this->basicOperation('isSharable', $path);
  438. }
  439. /**
  440. * @param string $path
  441. * @return bool|mixed
  442. */
  443. public function file_exists($path) {
  444. if ($path == '/') {
  445. return true;
  446. }
  447. return $this->basicOperation('file_exists', $path);
  448. }
  449. /**
  450. * @param string $path
  451. * @return mixed
  452. */
  453. public function filemtime($path) {
  454. return $this->basicOperation('filemtime', $path);
  455. }
  456. /**
  457. * @param string $path
  458. * @param int|string $mtime
  459. */
  460. public function touch($path, $mtime = null): bool {
  461. if (!is_null($mtime) && !is_numeric($mtime)) {
  462. $mtime = strtotime($mtime);
  463. }
  464. $hooks = ['touch'];
  465. if (!$this->file_exists($path)) {
  466. $hooks[] = 'create';
  467. $hooks[] = 'write';
  468. }
  469. try {
  470. $result = $this->basicOperation('touch', $path, $hooks, $mtime);
  471. } catch (\Exception $e) {
  472. $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
  473. $result = false;
  474. }
  475. if (!$result) {
  476. // If create file fails because of permissions on external storage like SMB folders,
  477. // check file exists and return false if not.
  478. if (!$this->file_exists($path)) {
  479. return false;
  480. }
  481. if (is_null($mtime)) {
  482. $mtime = time();
  483. }
  484. //if native touch fails, we emulate it by changing the mtime in the cache
  485. $this->putFileInfo($path, ['mtime' => floor($mtime)]);
  486. }
  487. return true;
  488. }
  489. /**
  490. * @param string $path
  491. * @return string|false
  492. * @throws LockedException
  493. */
  494. public function file_get_contents($path) {
  495. return $this->basicOperation('file_get_contents', $path, ['read']);
  496. }
  497. protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
  498. if (!$exists) {
  499. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
  500. Filesystem::signal_param_path => $this->getHookPath($path),
  501. Filesystem::signal_param_run => &$run,
  502. ]);
  503. } else {
  504. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
  505. Filesystem::signal_param_path => $this->getHookPath($path),
  506. Filesystem::signal_param_run => &$run,
  507. ]);
  508. }
  509. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
  510. Filesystem::signal_param_path => $this->getHookPath($path),
  511. Filesystem::signal_param_run => &$run,
  512. ]);
  513. }
  514. protected function emit_file_hooks_post(bool $exists, string $path): void {
  515. if (!$exists) {
  516. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
  517. Filesystem::signal_param_path => $this->getHookPath($path),
  518. ]);
  519. } else {
  520. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
  521. Filesystem::signal_param_path => $this->getHookPath($path),
  522. ]);
  523. }
  524. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
  525. Filesystem::signal_param_path => $this->getHookPath($path),
  526. ]);
  527. }
  528. /**
  529. * @param string $path
  530. * @param string|resource $data
  531. * @return bool|mixed
  532. * @throws LockedException
  533. */
  534. public function file_put_contents($path, $data) {
  535. if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
  536. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  537. if (Filesystem::isValidPath($path)
  538. && !Filesystem::isFileBlacklisted($path)
  539. ) {
  540. $path = $this->getRelativePath($absolutePath);
  541. if ($path === null) {
  542. throw new InvalidPathException("Path $absolutePath is not in the expected root");
  543. }
  544. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  545. $exists = $this->file_exists($path);
  546. $run = true;
  547. if ($this->shouldEmitHooks($path)) {
  548. $this->emit_file_hooks_pre($exists, $path, $run);
  549. }
  550. if (!$run) {
  551. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  552. return false;
  553. }
  554. try {
  555. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  556. } catch (\Exception $e) {
  557. // Release the shared lock before throwing.
  558. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  559. throw $e;
  560. }
  561. /** @var Storage $storage */
  562. [$storage, $internalPath] = $this->resolvePath($path);
  563. $target = $storage->fopen($internalPath, 'w');
  564. if ($target) {
  565. [, $result] = \OC_Helper::streamCopy($data, $target);
  566. fclose($target);
  567. fclose($data);
  568. $this->writeUpdate($storage, $internalPath);
  569. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  570. if ($this->shouldEmitHooks($path) && $result !== false) {
  571. $this->emit_file_hooks_post($exists, $path);
  572. }
  573. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  574. return $result;
  575. } else {
  576. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  577. return false;
  578. }
  579. } else {
  580. return false;
  581. }
  582. } else {
  583. $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
  584. return $this->basicOperation('file_put_contents', $path, $hooks, $data);
  585. }
  586. }
  587. /**
  588. * @param string $path
  589. * @return bool|mixed
  590. */
  591. public function unlink($path) {
  592. if ($path === '' || $path === '/') {
  593. // do not allow deleting the root
  594. return false;
  595. }
  596. $postFix = (substr($path, -1) === '/') ? '/' : '';
  597. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  598. $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
  599. if ($mount->getInternalPath($absolutePath) === '') {
  600. return $this->removeMount($mount, $absolutePath);
  601. }
  602. if ($this->is_dir($path)) {
  603. $result = $this->basicOperation('rmdir', $path, ['delete']);
  604. } else {
  605. $result = $this->basicOperation('unlink', $path, ['delete']);
  606. }
  607. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  608. $storage = $mount->getStorage();
  609. $internalPath = $mount->getInternalPath($absolutePath);
  610. $storage->getUpdater()->remove($internalPath);
  611. return true;
  612. } else {
  613. return $result;
  614. }
  615. }
  616. /**
  617. * @param string $directory
  618. * @return bool|mixed
  619. */
  620. public function deleteAll($directory) {
  621. return $this->rmdir($directory);
  622. }
  623. /**
  624. * Rename/move a file or folder from the source path to target path.
  625. *
  626. * @param string $source source path
  627. * @param string $target target path
  628. *
  629. * @return bool|mixed
  630. * @throws LockedException
  631. */
  632. public function rename($source, $target) {
  633. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
  634. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
  635. if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
  636. throw new ForbiddenException("Moving a folder into a child folder is forbidden", false);
  637. }
  638. $targetParts = explode('/', $absolutePath2);
  639. $targetUser = $targetParts[1] ?? null;
  640. $result = false;
  641. if (
  642. Filesystem::isValidPath($target)
  643. && Filesystem::isValidPath($source)
  644. && !Filesystem::isFileBlacklisted($target)
  645. ) {
  646. $source = $this->getRelativePath($absolutePath1);
  647. $target = $this->getRelativePath($absolutePath2);
  648. $exists = $this->file_exists($target);
  649. if ($source == null || $target == null) {
  650. return false;
  651. }
  652. try {
  653. $this->verifyPath(dirname($target), basename($target));
  654. } catch (InvalidPathException) {
  655. return false;
  656. }
  657. $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
  658. try {
  659. $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
  660. $run = true;
  661. if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
  662. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  663. $this->emit_file_hooks_pre($exists, $target, $run);
  664. } elseif ($this->shouldEmitHooks($source)) {
  665. $sourcePath = $this->getHookPath($source);
  666. $targetPath = $this->getHookPath($target);
  667. if ($sourcePath !== null && $targetPath !== null) {
  668. \OC_Hook::emit(
  669. Filesystem::CLASSNAME, Filesystem::signal_rename,
  670. [
  671. Filesystem::signal_param_oldpath => $sourcePath,
  672. Filesystem::signal_param_newpath => $targetPath,
  673. Filesystem::signal_param_run => &$run
  674. ]
  675. );
  676. }
  677. }
  678. if ($run) {
  679. $manager = Filesystem::getMountManager();
  680. $mount1 = $this->getMount($source);
  681. $mount2 = $this->getMount($target);
  682. $storage1 = $mount1->getStorage();
  683. $storage2 = $mount2->getStorage();
  684. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  685. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  686. $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
  687. try {
  688. $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
  689. if ($internalPath1 === '') {
  690. if ($mount1 instanceof MoveableMount) {
  691. $sourceParentMount = $this->getMount(dirname($source));
  692. if ($sourceParentMount === $mount2 && $this->targetIsNotShared($targetUser, $absolutePath2)) {
  693. /**
  694. * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
  695. */
  696. $sourceMountPoint = $mount1->getMountPoint();
  697. $result = $mount1->moveMount($absolutePath2);
  698. $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
  699. } else {
  700. $result = false;
  701. }
  702. } else {
  703. $result = false;
  704. }
  705. // moving a file/folder within the same mount point
  706. } elseif ($storage1 === $storage2) {
  707. if ($storage1) {
  708. $result = $storage1->rename($internalPath1, $internalPath2);
  709. } else {
  710. $result = false;
  711. }
  712. // moving a file/folder between storages (from $storage1 to $storage2)
  713. } else {
  714. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  715. }
  716. if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
  717. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  718. $this->writeUpdate($storage2, $internalPath2);
  719. } elseif ($result) {
  720. if ($internalPath1 !== '') { // don't do a cache update for moved mounts
  721. $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
  722. }
  723. }
  724. } catch (\Exception $e) {
  725. throw $e;
  726. } finally {
  727. $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
  728. $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
  729. }
  730. if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
  731. if ($this->shouldEmitHooks()) {
  732. $this->emit_file_hooks_post($exists, $target);
  733. }
  734. } elseif ($result) {
  735. if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
  736. $sourcePath = $this->getHookPath($source);
  737. $targetPath = $this->getHookPath($target);
  738. if ($sourcePath !== null && $targetPath !== null) {
  739. \OC_Hook::emit(
  740. Filesystem::CLASSNAME,
  741. Filesystem::signal_post_rename,
  742. [
  743. Filesystem::signal_param_oldpath => $sourcePath,
  744. Filesystem::signal_param_newpath => $targetPath,
  745. ]
  746. );
  747. }
  748. }
  749. }
  750. }
  751. } catch (\Exception $e) {
  752. throw $e;
  753. } finally {
  754. $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
  755. $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
  756. }
  757. }
  758. return $result;
  759. }
  760. /**
  761. * Copy a file/folder from the source path to target path
  762. *
  763. * @param string $source source path
  764. * @param string $target target path
  765. * @param bool $preserveMtime whether to preserve mtime on the copy
  766. *
  767. * @return bool|mixed
  768. */
  769. public function copy($source, $target, $preserveMtime = false) {
  770. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
  771. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
  772. $result = false;
  773. if (
  774. Filesystem::isValidPath($target)
  775. && Filesystem::isValidPath($source)
  776. && !Filesystem::isFileBlacklisted($target)
  777. ) {
  778. $source = $this->getRelativePath($absolutePath1);
  779. $target = $this->getRelativePath($absolutePath2);
  780. if ($source == null || $target == null) {
  781. return false;
  782. }
  783. $run = true;
  784. $this->lockFile($target, ILockingProvider::LOCK_SHARED);
  785. $this->lockFile($source, ILockingProvider::LOCK_SHARED);
  786. $lockTypePath1 = ILockingProvider::LOCK_SHARED;
  787. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  788. try {
  789. $exists = $this->file_exists($target);
  790. if ($this->shouldEmitHooks()) {
  791. \OC_Hook::emit(
  792. Filesystem::CLASSNAME,
  793. Filesystem::signal_copy,
  794. [
  795. Filesystem::signal_param_oldpath => $this->getHookPath($source),
  796. Filesystem::signal_param_newpath => $this->getHookPath($target),
  797. Filesystem::signal_param_run => &$run
  798. ]
  799. );
  800. $this->emit_file_hooks_pre($exists, $target, $run);
  801. }
  802. if ($run) {
  803. $mount1 = $this->getMount($source);
  804. $mount2 = $this->getMount($target);
  805. $storage1 = $mount1->getStorage();
  806. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  807. $storage2 = $mount2->getStorage();
  808. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  809. $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
  810. $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
  811. if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
  812. if ($storage1) {
  813. $result = $storage1->copy($internalPath1, $internalPath2);
  814. } else {
  815. $result = false;
  816. }
  817. } else {
  818. $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
  819. }
  820. $this->writeUpdate($storage2, $internalPath2);
  821. $this->changeLock($target, ILockingProvider::LOCK_SHARED);
  822. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  823. if ($this->shouldEmitHooks() && $result !== false) {
  824. \OC_Hook::emit(
  825. Filesystem::CLASSNAME,
  826. Filesystem::signal_post_copy,
  827. [
  828. Filesystem::signal_param_oldpath => $this->getHookPath($source),
  829. Filesystem::signal_param_newpath => $this->getHookPath($target)
  830. ]
  831. );
  832. $this->emit_file_hooks_post($exists, $target);
  833. }
  834. }
  835. } catch (\Exception $e) {
  836. $this->unlockFile($target, $lockTypePath2);
  837. $this->unlockFile($source, $lockTypePath1);
  838. throw $e;
  839. }
  840. $this->unlockFile($target, $lockTypePath2);
  841. $this->unlockFile($source, $lockTypePath1);
  842. }
  843. return $result;
  844. }
  845. /**
  846. * @param string $path
  847. * @param string $mode 'r' or 'w'
  848. * @return resource|false
  849. * @throws LockedException
  850. */
  851. public function fopen($path, $mode) {
  852. $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
  853. $hooks = [];
  854. switch ($mode) {
  855. case 'r':
  856. $hooks[] = 'read';
  857. break;
  858. case 'r+':
  859. case 'w+':
  860. case 'x+':
  861. case 'a+':
  862. $hooks[] = 'read';
  863. $hooks[] = 'write';
  864. break;
  865. case 'w':
  866. case 'x':
  867. case 'a':
  868. $hooks[] = 'write';
  869. break;
  870. default:
  871. $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
  872. }
  873. if ($mode !== 'r' && $mode !== 'w') {
  874. $this->logger->info('Trying to open a file with a mode other than "r" or "w" can cause severe performance issues with some backends', ['app' => 'core']);
  875. }
  876. $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
  877. if (!is_resource($handle) && $mode === 'r') {
  878. // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
  879. $mount = $this->getMount($path);
  880. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  881. $storage = $mount->getStorage();
  882. if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
  883. $this->writeUpdate($storage, $internalPath);
  884. }
  885. }
  886. return $handle;
  887. }
  888. /**
  889. * @param string $path
  890. * @throws InvalidPathException
  891. */
  892. public function toTmpFile($path): string|false {
  893. $this->assertPathLength($path);
  894. if (Filesystem::isValidPath($path)) {
  895. $source = $this->fopen($path, 'r');
  896. if ($source) {
  897. $extension = pathinfo($path, PATHINFO_EXTENSION);
  898. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
  899. file_put_contents($tmpFile, $source);
  900. return $tmpFile;
  901. } else {
  902. return false;
  903. }
  904. } else {
  905. return false;
  906. }
  907. }
  908. /**
  909. * @param string $tmpFile
  910. * @param string $path
  911. * @return bool|mixed
  912. * @throws InvalidPathException
  913. */
  914. public function fromTmpFile($tmpFile, $path) {
  915. $this->assertPathLength($path);
  916. if (Filesystem::isValidPath($path)) {
  917. // Get directory that the file is going into
  918. $filePath = dirname($path);
  919. // Create the directories if any
  920. if (!$this->file_exists($filePath)) {
  921. $result = $this->createParentDirectories($filePath);
  922. if ($result === false) {
  923. return false;
  924. }
  925. }
  926. $source = fopen($tmpFile, 'r');
  927. if ($source) {
  928. $result = $this->file_put_contents($path, $source);
  929. /**
  930. * $this->file_put_contents() might have already closed
  931. * the resource, so we check it, before trying to close it
  932. * to avoid messages in the error log.
  933. * @psalm-suppress RedundantCondition false-positive
  934. */
  935. if (is_resource($source)) {
  936. fclose($source);
  937. }
  938. unlink($tmpFile);
  939. return $result;
  940. } else {
  941. return false;
  942. }
  943. } else {
  944. return false;
  945. }
  946. }
  947. /**
  948. * @param string $path
  949. * @return mixed
  950. * @throws InvalidPathException
  951. */
  952. public function getMimeType($path) {
  953. $this->assertPathLength($path);
  954. return $this->basicOperation('getMimeType', $path);
  955. }
  956. /**
  957. * @param string $type
  958. * @param string $path
  959. * @param bool $raw
  960. */
  961. public function hash($type, $path, $raw = false): string|bool {
  962. $postFix = (substr($path, -1) === '/') ? '/' : '';
  963. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  964. if (Filesystem::isValidPath($path)) {
  965. $path = $this->getRelativePath($absolutePath);
  966. if ($path == null) {
  967. return false;
  968. }
  969. if ($this->shouldEmitHooks($path)) {
  970. \OC_Hook::emit(
  971. Filesystem::CLASSNAME,
  972. Filesystem::signal_read,
  973. [Filesystem::signal_param_path => $this->getHookPath($path)]
  974. );
  975. }
  976. /** @var Storage|null $storage */
  977. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  978. if ($storage) {
  979. return $storage->hash($type, $internalPath, $raw);
  980. }
  981. }
  982. return false;
  983. }
  984. /**
  985. * @param string $path
  986. * @return mixed
  987. * @throws InvalidPathException
  988. */
  989. public function free_space($path = '/') {
  990. $this->assertPathLength($path);
  991. $result = $this->basicOperation('free_space', $path);
  992. if ($result === null) {
  993. throw new InvalidPathException();
  994. }
  995. return $result;
  996. }
  997. /**
  998. * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
  999. *
  1000. * @param mixed $extraParam (optional)
  1001. * @return mixed
  1002. * @throws LockedException
  1003. *
  1004. * This method takes requests for basic filesystem functions (e.g. reading & writing
  1005. * files), processes hooks and proxies, sanitises paths, and finally passes them on to
  1006. * \OC\Files\Storage\Storage for delegation to a storage backend for execution
  1007. */
  1008. private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
  1009. $postFix = (substr($path, -1) === '/') ? '/' : '';
  1010. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  1011. if (Filesystem::isValidPath($path)
  1012. && !Filesystem::isFileBlacklisted($path)
  1013. ) {
  1014. $path = $this->getRelativePath($absolutePath);
  1015. if ($path == null) {
  1016. return false;
  1017. }
  1018. if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
  1019. // always a shared lock during pre-hooks so the hook can read the file
  1020. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  1021. }
  1022. $run = $this->runHooks($hooks, $path);
  1023. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  1024. if ($run && $storage) {
  1025. /** @var Storage $storage */
  1026. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1027. try {
  1028. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  1029. } catch (LockedException $e) {
  1030. // release the shared lock we acquired before quitting
  1031. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1032. throw $e;
  1033. }
  1034. }
  1035. try {
  1036. if (!is_null($extraParam)) {
  1037. $result = $storage->$operation($internalPath, $extraParam);
  1038. } else {
  1039. $result = $storage->$operation($internalPath);
  1040. }
  1041. } catch (\Exception $e) {
  1042. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1043. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1044. } elseif (in_array('read', $hooks)) {
  1045. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1046. }
  1047. throw $e;
  1048. }
  1049. if ($result !== false && in_array('delete', $hooks)) {
  1050. $this->removeUpdate($storage, $internalPath);
  1051. }
  1052. if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
  1053. $isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
  1054. $sizeDifference = $operation === 'mkdir' ? 0 : $result;
  1055. $this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
  1056. }
  1057. if ($result !== false && in_array('touch', $hooks)) {
  1058. $this->writeUpdate($storage, $internalPath, $extraParam, 0);
  1059. }
  1060. if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
  1061. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  1062. }
  1063. $unlockLater = false;
  1064. if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
  1065. $unlockLater = true;
  1066. // make sure our unlocking callback will still be called if connection is aborted
  1067. ignore_user_abort(true);
  1068. $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
  1069. if (in_array('write', $hooks)) {
  1070. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1071. } elseif (in_array('read', $hooks)) {
  1072. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1073. }
  1074. });
  1075. }
  1076. if ($this->shouldEmitHooks($path) && $result !== false) {
  1077. if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
  1078. $this->runHooks($hooks, $path, true);
  1079. }
  1080. }
  1081. if (!$unlockLater
  1082. && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
  1083. ) {
  1084. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1085. }
  1086. return $result;
  1087. } else {
  1088. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1089. }
  1090. }
  1091. return null;
  1092. }
  1093. /**
  1094. * get the path relative to the default root for hook usage
  1095. *
  1096. * @param string $path
  1097. * @return ?string
  1098. */
  1099. private function getHookPath($path): ?string {
  1100. $view = Filesystem::getView();
  1101. if (!$view) {
  1102. return $path;
  1103. }
  1104. return $view->getRelativePath($this->getAbsolutePath($path));
  1105. }
  1106. private function shouldEmitHooks(string $path = ''): bool {
  1107. if ($path && Cache\Scanner::isPartialFile($path)) {
  1108. return false;
  1109. }
  1110. if (!Filesystem::$loaded) {
  1111. return false;
  1112. }
  1113. $defaultRoot = Filesystem::getRoot();
  1114. if ($defaultRoot === null) {
  1115. return false;
  1116. }
  1117. if ($this->fakeRoot === $defaultRoot) {
  1118. return true;
  1119. }
  1120. $fullPath = $this->getAbsolutePath($path);
  1121. if ($fullPath === $defaultRoot) {
  1122. return true;
  1123. }
  1124. return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
  1125. }
  1126. /**
  1127. * @param string[] $hooks
  1128. * @param string $path
  1129. * @param bool $post
  1130. * @return bool
  1131. */
  1132. private function runHooks($hooks, $path, $post = false) {
  1133. $relativePath = $path;
  1134. $path = $this->getHookPath($path);
  1135. $prefix = $post ? 'post_' : '';
  1136. $run = true;
  1137. if ($this->shouldEmitHooks($relativePath)) {
  1138. foreach ($hooks as $hook) {
  1139. if ($hook != 'read') {
  1140. \OC_Hook::emit(
  1141. Filesystem::CLASSNAME,
  1142. $prefix . $hook,
  1143. [
  1144. Filesystem::signal_param_run => &$run,
  1145. Filesystem::signal_param_path => $path
  1146. ]
  1147. );
  1148. } elseif (!$post) {
  1149. \OC_Hook::emit(
  1150. Filesystem::CLASSNAME,
  1151. $prefix . $hook,
  1152. [
  1153. Filesystem::signal_param_path => $path
  1154. ]
  1155. );
  1156. }
  1157. }
  1158. }
  1159. return $run;
  1160. }
  1161. /**
  1162. * check if a file or folder has been updated since $time
  1163. *
  1164. * @param string $path
  1165. * @param int $time
  1166. * @return bool
  1167. */
  1168. public function hasUpdated($path, $time) {
  1169. return $this->basicOperation('hasUpdated', $path, [], $time);
  1170. }
  1171. /**
  1172. * @param string $ownerId
  1173. * @return IUser
  1174. */
  1175. private function getUserObjectForOwner(string $ownerId) {
  1176. return new LazyUser($ownerId, $this->userManager);
  1177. }
  1178. /**
  1179. * Get file info from cache
  1180. *
  1181. * If the file is not in cached it will be scanned
  1182. * If the file has changed on storage the cache will be updated
  1183. *
  1184. * @param Storage $storage
  1185. * @param string $internalPath
  1186. * @param string $relativePath
  1187. * @return ICacheEntry|bool
  1188. */
  1189. private function getCacheEntry($storage, $internalPath, $relativePath) {
  1190. $cache = $storage->getCache($internalPath);
  1191. $data = $cache->get($internalPath);
  1192. $watcher = $storage->getWatcher($internalPath);
  1193. try {
  1194. // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
  1195. if (!$data || (isset($data['size']) && $data['size'] === -1)) {
  1196. if (!$storage->file_exists($internalPath)) {
  1197. return false;
  1198. }
  1199. // don't need to get a lock here since the scanner does it's own locking
  1200. $scanner = $storage->getScanner($internalPath);
  1201. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1202. $data = $cache->get($internalPath);
  1203. } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
  1204. $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1205. $watcher->update($internalPath, $data);
  1206. $storage->getPropagator()->propagateChange($internalPath, time());
  1207. $data = $cache->get($internalPath);
  1208. $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1209. }
  1210. } catch (LockedException $e) {
  1211. // if the file is locked we just use the old cache info
  1212. }
  1213. return $data;
  1214. }
  1215. /**
  1216. * get the filesystem info
  1217. *
  1218. * @param string $path
  1219. * @param bool|string $includeMountPoints true to add mountpoint sizes,
  1220. * 'ext' to add only ext storage mount point sizes. Defaults to true.
  1221. * @return \OC\Files\FileInfo|false False if file does not exist
  1222. */
  1223. public function getFileInfo($path, $includeMountPoints = true) {
  1224. $this->assertPathLength($path);
  1225. if (!Filesystem::isValidPath($path)) {
  1226. return false;
  1227. }
  1228. $relativePath = $path;
  1229. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1230. $mount = Filesystem::getMountManager()->find($path);
  1231. $storage = $mount->getStorage();
  1232. $internalPath = $mount->getInternalPath($path);
  1233. if ($storage) {
  1234. $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
  1235. if (!$data instanceof ICacheEntry) {
  1236. if (Cache\Scanner::isPartialFile($relativePath)) {
  1237. return $this->getPartFileInfo($relativePath);
  1238. }
  1239. return false;
  1240. }
  1241. if ($mount instanceof MoveableMount && $internalPath === '') {
  1242. $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
  1243. }
  1244. if ($internalPath === '' && $data['name']) {
  1245. $data['name'] = basename($path);
  1246. }
  1247. $ownerId = $storage->getOwner($internalPath);
  1248. $owner = null;
  1249. if ($ownerId !== null && $ownerId !== false) {
  1250. // ownerId might be null if files are accessed with an access token without file system access
  1251. $owner = $this->getUserObjectForOwner($ownerId);
  1252. }
  1253. $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
  1254. if (isset($data['fileid'])) {
  1255. if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
  1256. //add the sizes of other mount points to the folder
  1257. $extOnly = ($includeMountPoints === 'ext');
  1258. $this->addSubMounts($info, $extOnly);
  1259. }
  1260. }
  1261. return $info;
  1262. } else {
  1263. $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
  1264. }
  1265. return false;
  1266. }
  1267. /**
  1268. * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
  1269. */
  1270. public function addSubMounts(FileInfo $info, $extOnly = false): void {
  1271. $mounts = Filesystem::getMountManager()->findIn($info->getPath());
  1272. $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
  1273. $subStorage = $mount->getStorage();
  1274. return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
  1275. }));
  1276. }
  1277. /**
  1278. * get the content of a directory
  1279. *
  1280. * @param string $directory path under datadirectory
  1281. * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  1282. * @return FileInfo[]
  1283. */
  1284. public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
  1285. $this->assertPathLength($directory);
  1286. if (!Filesystem::isValidPath($directory)) {
  1287. return [];
  1288. }
  1289. $path = $this->getAbsolutePath($directory);
  1290. $path = Filesystem::normalizePath($path);
  1291. $mount = $this->getMount($directory);
  1292. $storage = $mount->getStorage();
  1293. $internalPath = $mount->getInternalPath($path);
  1294. if (!$storage) {
  1295. return [];
  1296. }
  1297. $cache = $storage->getCache($internalPath);
  1298. $user = \OC_User::getUser();
  1299. if (!$directoryInfo) {
  1300. $data = $this->getCacheEntry($storage, $internalPath, $directory);
  1301. if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
  1302. return [];
  1303. }
  1304. } else {
  1305. $data = $directoryInfo;
  1306. }
  1307. if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
  1308. return [];
  1309. }
  1310. $folderId = $data->getId();
  1311. $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
  1312. $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
  1313. $fileNames = array_map(function (ICacheEntry $content) {
  1314. return $content->getName();
  1315. }, $contents);
  1316. /**
  1317. * @var \OC\Files\FileInfo[] $fileInfos
  1318. */
  1319. $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
  1320. if ($sharingDisabled) {
  1321. $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1322. }
  1323. $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
  1324. return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
  1325. }, $contents);
  1326. $files = array_combine($fileNames, $fileInfos);
  1327. //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
  1328. $mounts = Filesystem::getMountManager()->findIn($path);
  1329. // make sure nested mounts are sorted after their parent mounts
  1330. // otherwise doesn't propagate the etag across storage boundaries correctly
  1331. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1332. return $a->getMountPoint() <=> $b->getMountPoint();
  1333. });
  1334. $dirLength = strlen($path);
  1335. foreach ($mounts as $mount) {
  1336. $mountPoint = $mount->getMountPoint();
  1337. $subStorage = $mount->getStorage();
  1338. if ($subStorage) {
  1339. $subCache = $subStorage->getCache('');
  1340. $rootEntry = $subCache->get('');
  1341. if (!$rootEntry) {
  1342. $subScanner = $subStorage->getScanner();
  1343. try {
  1344. $subScanner->scanFile('');
  1345. } catch (\OCP\Files\StorageNotAvailableException $e) {
  1346. continue;
  1347. } catch (\OCP\Files\StorageInvalidException $e) {
  1348. continue;
  1349. } catch (\Exception $e) {
  1350. // sometimes when the storage is not available it can be any exception
  1351. $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
  1352. 'exception' => $e,
  1353. 'app' => 'core',
  1354. ]);
  1355. continue;
  1356. }
  1357. $rootEntry = $subCache->get('');
  1358. }
  1359. if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
  1360. $relativePath = trim(substr($mountPoint, $dirLength), '/');
  1361. if ($pos = strpos($relativePath, '/')) {
  1362. //mountpoint inside subfolder add size to the correct folder
  1363. $entryName = substr($relativePath, 0, $pos);
  1364. if (isset($files[$entryName])) {
  1365. $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
  1366. }
  1367. } else { //mountpoint in this folder, add an entry for it
  1368. $rootEntry['name'] = $relativePath;
  1369. $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
  1370. $permissions = $rootEntry['permissions'];
  1371. // do not allow renaming/deleting the mount point if they are not shared files/folders
  1372. // for shared files/folders we use the permissions given by the owner
  1373. if ($mount instanceof MoveableMount) {
  1374. $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
  1375. } else {
  1376. $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
  1377. }
  1378. $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
  1379. // if sharing was disabled for the user we remove the share permissions
  1380. if ($sharingDisabled) {
  1381. $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1382. }
  1383. $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
  1384. $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
  1385. }
  1386. }
  1387. }
  1388. }
  1389. if ($mimetype_filter) {
  1390. $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
  1391. if (strpos($mimetype_filter, '/')) {
  1392. return $file->getMimetype() === $mimetype_filter;
  1393. } else {
  1394. return $file->getMimePart() === $mimetype_filter;
  1395. }
  1396. });
  1397. }
  1398. return array_values($files);
  1399. }
  1400. /**
  1401. * change file metadata
  1402. *
  1403. * @param string $path
  1404. * @param array|\OCP\Files\FileInfo $data
  1405. * @return int
  1406. *
  1407. * returns the fileid of the updated file
  1408. */
  1409. public function putFileInfo($path, $data) {
  1410. $this->assertPathLength($path);
  1411. if ($data instanceof FileInfo) {
  1412. $data = $data->getData();
  1413. }
  1414. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1415. /**
  1416. * @var Storage $storage
  1417. * @var string $internalPath
  1418. */
  1419. [$storage, $internalPath] = Filesystem::resolvePath($path);
  1420. if ($storage) {
  1421. $cache = $storage->getCache($path);
  1422. if (!$cache->inCache($internalPath)) {
  1423. $scanner = $storage->getScanner($internalPath);
  1424. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1425. }
  1426. return $cache->put($internalPath, $data);
  1427. } else {
  1428. return -1;
  1429. }
  1430. }
  1431. /**
  1432. * search for files with the name matching $query
  1433. *
  1434. * @param string $query
  1435. * @return FileInfo[]
  1436. */
  1437. public function search($query) {
  1438. return $this->searchCommon('search', ['%' . $query . '%']);
  1439. }
  1440. /**
  1441. * search for files with the name matching $query
  1442. *
  1443. * @param string $query
  1444. * @return FileInfo[]
  1445. */
  1446. public function searchRaw($query) {
  1447. return $this->searchCommon('search', [$query]);
  1448. }
  1449. /**
  1450. * search for files by mimetype
  1451. *
  1452. * @param string $mimetype
  1453. * @return FileInfo[]
  1454. */
  1455. public function searchByMime($mimetype) {
  1456. return $this->searchCommon('searchByMime', [$mimetype]);
  1457. }
  1458. /**
  1459. * search for files by tag
  1460. *
  1461. * @param string|int $tag name or tag id
  1462. * @param string $userId owner of the tags
  1463. * @return FileInfo[]
  1464. */
  1465. public function searchByTag($tag, $userId) {
  1466. return $this->searchCommon('searchByTag', [$tag, $userId]);
  1467. }
  1468. /**
  1469. * @param string $method cache method
  1470. * @param array $args
  1471. * @return FileInfo[]
  1472. */
  1473. private function searchCommon($method, $args) {
  1474. $files = [];
  1475. $rootLength = strlen($this->fakeRoot);
  1476. $mount = $this->getMount('');
  1477. $mountPoint = $mount->getMountPoint();
  1478. $storage = $mount->getStorage();
  1479. $userManager = \OC::$server->getUserManager();
  1480. if ($storage) {
  1481. $cache = $storage->getCache('');
  1482. $results = call_user_func_array([$cache, $method], $args);
  1483. foreach ($results as $result) {
  1484. if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
  1485. $internalPath = $result['path'];
  1486. $path = $mountPoint . $result['path'];
  1487. $result['path'] = substr($mountPoint . $result['path'], $rootLength);
  1488. $owner = $userManager->get($storage->getOwner($internalPath));
  1489. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1490. }
  1491. }
  1492. $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
  1493. foreach ($mounts as $mount) {
  1494. $mountPoint = $mount->getMountPoint();
  1495. $storage = $mount->getStorage();
  1496. if ($storage) {
  1497. $cache = $storage->getCache('');
  1498. $relativeMountPoint = substr($mountPoint, $rootLength);
  1499. $results = call_user_func_array([$cache, $method], $args);
  1500. if ($results) {
  1501. foreach ($results as $result) {
  1502. $internalPath = $result['path'];
  1503. $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
  1504. $path = rtrim($mountPoint . $internalPath, '/');
  1505. $owner = $userManager->get($storage->getOwner($internalPath));
  1506. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1507. }
  1508. }
  1509. }
  1510. }
  1511. }
  1512. return $files;
  1513. }
  1514. /**
  1515. * Get the owner for a file or folder
  1516. *
  1517. * @param string $path
  1518. * @return string the user id of the owner
  1519. * @throws NotFoundException
  1520. */
  1521. public function getOwner($path) {
  1522. $info = $this->getFileInfo($path);
  1523. if (!$info) {
  1524. throw new NotFoundException($path . ' not found while trying to get owner');
  1525. }
  1526. if ($info->getOwner() === null) {
  1527. throw new NotFoundException($path . ' has no owner');
  1528. }
  1529. return $info->getOwner()->getUID();
  1530. }
  1531. /**
  1532. * get the ETag for a file or folder
  1533. *
  1534. * @param string $path
  1535. * @return string|false
  1536. */
  1537. public function getETag($path) {
  1538. [$storage, $internalPath] = $this->resolvePath($path);
  1539. if ($storage) {
  1540. return $storage->getETag($internalPath);
  1541. } else {
  1542. return false;
  1543. }
  1544. }
  1545. /**
  1546. * Get the path of a file by id, relative to the view
  1547. *
  1548. * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
  1549. *
  1550. * @param int $id
  1551. * @param int|null $storageId
  1552. * @return string
  1553. * @throws NotFoundException
  1554. */
  1555. public function getPath($id, ?int $storageId = null) {
  1556. $id = (int)$id;
  1557. $manager = Filesystem::getMountManager();
  1558. $mounts = $manager->findIn($this->fakeRoot);
  1559. $mounts[] = $manager->find($this->fakeRoot);
  1560. $mounts = array_filter($mounts);
  1561. // reverse the array, so we start with the storage this view is in
  1562. // which is the most likely to contain the file we're looking for
  1563. $mounts = array_reverse($mounts);
  1564. // put non-shared mounts in front of the shared mount
  1565. // this prevents unneeded recursion into shares
  1566. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1567. return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
  1568. });
  1569. if (!is_null($storageId)) {
  1570. $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
  1571. return $mount->getNumericStorageId() === $storageId;
  1572. });
  1573. }
  1574. foreach ($mounts as $mount) {
  1575. /**
  1576. * @var \OC\Files\Mount\MountPoint $mount
  1577. */
  1578. if ($mount->getStorage()) {
  1579. $cache = $mount->getStorage()->getCache();
  1580. $internalPath = $cache->getPathById($id);
  1581. if (is_string($internalPath)) {
  1582. $fullPath = $mount->getMountPoint() . $internalPath;
  1583. if (!is_null($path = $this->getRelativePath($fullPath))) {
  1584. return $path;
  1585. }
  1586. }
  1587. }
  1588. }
  1589. throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
  1590. }
  1591. /**
  1592. * @param string $path
  1593. * @throws InvalidPathException
  1594. */
  1595. private function assertPathLength($path): void {
  1596. $maxLen = min(PHP_MAXPATHLEN, 4000);
  1597. // Check for the string length - performed using isset() instead of strlen()
  1598. // because isset() is about 5x-40x faster.
  1599. if (isset($path[$maxLen])) {
  1600. $pathLen = strlen($path);
  1601. throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
  1602. }
  1603. }
  1604. /**
  1605. * check if it is allowed to move a mount point to a given target.
  1606. * It is not allowed to move a mount point into a different mount point or
  1607. * into an already shared folder
  1608. */
  1609. private function targetIsNotShared(string $user, string $targetPath): bool {
  1610. $providers = [
  1611. IShare::TYPE_USER,
  1612. IShare::TYPE_GROUP,
  1613. IShare::TYPE_EMAIL,
  1614. IShare::TYPE_CIRCLE,
  1615. IShare::TYPE_ROOM,
  1616. IShare::TYPE_DECK,
  1617. IShare::TYPE_SCIENCEMESH
  1618. ];
  1619. $shareManager = Server::get(IManager::class);
  1620. /** @var IShare[] $shares */
  1621. $shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
  1622. return $shareManager->getSharesBy($user, $type);
  1623. }, $providers));
  1624. foreach ($shares as $share) {
  1625. if (str_starts_with($targetPath, $share->getNode()->getPath())) {
  1626. $this->logger->debug(
  1627. 'It is not allowed to move one mount point into a shared folder',
  1628. ['app' => 'files']);
  1629. return false;
  1630. }
  1631. }
  1632. return true;
  1633. }
  1634. /**
  1635. * Get a fileinfo object for files that are ignored in the cache (part files)
  1636. */
  1637. private function getPartFileInfo(string $path): \OC\Files\FileInfo {
  1638. $mount = $this->getMount($path);
  1639. $storage = $mount->getStorage();
  1640. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  1641. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1642. return new FileInfo(
  1643. $this->getAbsolutePath($path),
  1644. $storage,
  1645. $internalPath,
  1646. [
  1647. 'fileid' => null,
  1648. 'mimetype' => $storage->getMimeType($internalPath),
  1649. 'name' => basename($path),
  1650. 'etag' => null,
  1651. 'size' => $storage->filesize($internalPath),
  1652. 'mtime' => $storage->filemtime($internalPath),
  1653. 'encrypted' => false,
  1654. 'permissions' => \OCP\Constants::PERMISSION_ALL
  1655. ],
  1656. $mount,
  1657. $owner
  1658. );
  1659. }
  1660. /**
  1661. * @param string $path
  1662. * @param string $fileName
  1663. * @throws InvalidPathException
  1664. */
  1665. public function verifyPath($path, $fileName): void {
  1666. // All of the view's functions disallow '..' in the path so we can short cut if the path is invalid
  1667. if (!Filesystem::isValidPath($path ?: '/')) {
  1668. $l = \OCP\Util::getL10N('lib');
  1669. throw new InvalidPathException($l->t('Path contains invalid segments'));
  1670. }
  1671. try {
  1672. /** @type \OCP\Files\Storage $storage */
  1673. [$storage, $internalPath] = $this->resolvePath($path);
  1674. $storage->verifyPath($internalPath, $fileName);
  1675. } catch (ReservedWordException $ex) {
  1676. $l = \OCP\Util::getL10N('lib');
  1677. throw new InvalidPathException($l->t('File name is a reserved word'));
  1678. } catch (InvalidCharacterInPathException $ex) {
  1679. $l = \OCP\Util::getL10N('lib');
  1680. throw new InvalidPathException($l->t('File name contains at least one invalid character'));
  1681. } catch (FileNameTooLongException $ex) {
  1682. $l = \OCP\Util::getL10N('lib');
  1683. throw new InvalidPathException($l->t('File name is too long'));
  1684. } catch (InvalidDirectoryException $ex) {
  1685. $l = \OCP\Util::getL10N('lib');
  1686. throw new InvalidPathException($l->t('Dot files are not allowed'));
  1687. } catch (EmptyFileNameException $ex) {
  1688. $l = \OCP\Util::getL10N('lib');
  1689. throw new InvalidPathException($l->t('Empty filename is not allowed'));
  1690. }
  1691. }
  1692. /**
  1693. * get all parent folders of $path
  1694. *
  1695. * @param string $path
  1696. * @return string[]
  1697. */
  1698. private function getParents($path) {
  1699. $path = trim($path, '/');
  1700. if (!$path) {
  1701. return [];
  1702. }
  1703. $parts = explode('/', $path);
  1704. // remove the single file
  1705. array_pop($parts);
  1706. $result = ['/'];
  1707. $resultPath = '';
  1708. foreach ($parts as $part) {
  1709. if ($part) {
  1710. $resultPath .= '/' . $part;
  1711. $result[] = $resultPath;
  1712. }
  1713. }
  1714. return $result;
  1715. }
  1716. /**
  1717. * Returns the mount point for which to lock
  1718. *
  1719. * @param string $absolutePath absolute path
  1720. * @param bool $useParentMount true to return parent mount instead of whatever
  1721. * is mounted directly on the given path, false otherwise
  1722. * @return IMountPoint mount point for which to apply locks
  1723. */
  1724. private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
  1725. $mount = Filesystem::getMountManager()->find($absolutePath);
  1726. if ($useParentMount) {
  1727. // find out if something is mounted directly on the path
  1728. $internalPath = $mount->getInternalPath($absolutePath);
  1729. if ($internalPath === '') {
  1730. // resolve the parent mount instead
  1731. $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
  1732. }
  1733. }
  1734. return $mount;
  1735. }
  1736. /**
  1737. * Lock the given path
  1738. *
  1739. * @param string $path the path of the file to lock, relative to the view
  1740. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1741. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1742. *
  1743. * @return bool False if the path is excluded from locking, true otherwise
  1744. * @throws LockedException if the path is already locked
  1745. */
  1746. private function lockPath($path, $type, $lockMountPoint = false) {
  1747. $absolutePath = $this->getAbsolutePath($path);
  1748. $absolutePath = Filesystem::normalizePath($absolutePath);
  1749. if (!$this->shouldLockFile($absolutePath)) {
  1750. return false;
  1751. }
  1752. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1753. try {
  1754. $storage = $mount->getStorage();
  1755. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1756. $storage->acquireLock(
  1757. $mount->getInternalPath($absolutePath),
  1758. $type,
  1759. $this->lockingProvider
  1760. );
  1761. }
  1762. } catch (LockedException $e) {
  1763. // rethrow with the a human-readable path
  1764. throw new LockedException(
  1765. $this->getPathRelativeToFiles($absolutePath),
  1766. $e,
  1767. $e->getExistingLock()
  1768. );
  1769. }
  1770. return true;
  1771. }
  1772. /**
  1773. * Change the lock type
  1774. *
  1775. * @param string $path the path of the file to lock, relative to the view
  1776. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1777. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1778. *
  1779. * @return bool False if the path is excluded from locking, true otherwise
  1780. * @throws LockedException if the path is already locked
  1781. */
  1782. public function changeLock($path, $type, $lockMountPoint = false) {
  1783. $path = Filesystem::normalizePath($path);
  1784. $absolutePath = $this->getAbsolutePath($path);
  1785. $absolutePath = Filesystem::normalizePath($absolutePath);
  1786. if (!$this->shouldLockFile($absolutePath)) {
  1787. return false;
  1788. }
  1789. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1790. try {
  1791. $storage = $mount->getStorage();
  1792. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1793. $storage->changeLock(
  1794. $mount->getInternalPath($absolutePath),
  1795. $type,
  1796. $this->lockingProvider
  1797. );
  1798. }
  1799. } catch (LockedException $e) {
  1800. try {
  1801. // rethrow with the a human-readable path
  1802. throw new LockedException(
  1803. $this->getPathRelativeToFiles($absolutePath),
  1804. $e,
  1805. $e->getExistingLock()
  1806. );
  1807. } catch (\InvalidArgumentException $ex) {
  1808. throw new LockedException(
  1809. $absolutePath,
  1810. $ex,
  1811. $e->getExistingLock()
  1812. );
  1813. }
  1814. }
  1815. return true;
  1816. }
  1817. /**
  1818. * Unlock the given path
  1819. *
  1820. * @param string $path the path of the file to unlock, relative to the view
  1821. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1822. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1823. *
  1824. * @return bool False if the path is excluded from locking, true otherwise
  1825. * @throws LockedException
  1826. */
  1827. private function unlockPath($path, $type, $lockMountPoint = false) {
  1828. $absolutePath = $this->getAbsolutePath($path);
  1829. $absolutePath = Filesystem::normalizePath($absolutePath);
  1830. if (!$this->shouldLockFile($absolutePath)) {
  1831. return false;
  1832. }
  1833. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1834. $storage = $mount->getStorage();
  1835. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1836. $storage->releaseLock(
  1837. $mount->getInternalPath($absolutePath),
  1838. $type,
  1839. $this->lockingProvider
  1840. );
  1841. }
  1842. return true;
  1843. }
  1844. /**
  1845. * Lock a path and all its parents up to the root of the view
  1846. *
  1847. * @param string $path the path of the file to lock relative to the view
  1848. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1849. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1850. *
  1851. * @return bool False if the path is excluded from locking, true otherwise
  1852. * @throws LockedException
  1853. */
  1854. public function lockFile($path, $type, $lockMountPoint = false) {
  1855. $absolutePath = $this->getAbsolutePath($path);
  1856. $absolutePath = Filesystem::normalizePath($absolutePath);
  1857. if (!$this->shouldLockFile($absolutePath)) {
  1858. return false;
  1859. }
  1860. $this->lockPath($path, $type, $lockMountPoint);
  1861. $parents = $this->getParents($path);
  1862. foreach ($parents as $parent) {
  1863. $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
  1864. }
  1865. return true;
  1866. }
  1867. /**
  1868. * Unlock a path and all its parents up to the root of the view
  1869. *
  1870. * @param string $path the path of the file to lock relative to the view
  1871. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1872. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1873. *
  1874. * @return bool False if the path is excluded from locking, true otherwise
  1875. * @throws LockedException
  1876. */
  1877. public function unlockFile($path, $type, $lockMountPoint = false) {
  1878. $absolutePath = $this->getAbsolutePath($path);
  1879. $absolutePath = Filesystem::normalizePath($absolutePath);
  1880. if (!$this->shouldLockFile($absolutePath)) {
  1881. return false;
  1882. }
  1883. $this->unlockPath($path, $type, $lockMountPoint);
  1884. $parents = $this->getParents($path);
  1885. foreach ($parents as $parent) {
  1886. $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
  1887. }
  1888. return true;
  1889. }
  1890. /**
  1891. * Only lock files in data/user/files/
  1892. *
  1893. * @param string $path Absolute path to the file/folder we try to (un)lock
  1894. * @return bool
  1895. */
  1896. protected function shouldLockFile($path) {
  1897. $path = Filesystem::normalizePath($path);
  1898. $pathSegments = explode('/', $path);
  1899. if (isset($pathSegments[2])) {
  1900. // E.g.: /username/files/path-to-file
  1901. return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
  1902. }
  1903. return !str_starts_with($path, '/appdata_');
  1904. }
  1905. /**
  1906. * Shortens the given absolute path to be relative to
  1907. * "$user/files".
  1908. *
  1909. * @param string $absolutePath absolute path which is under "files"
  1910. *
  1911. * @return string path relative to "files" with trimmed slashes or null
  1912. * if the path was NOT relative to files
  1913. *
  1914. * @throws \InvalidArgumentException if the given path was not under "files"
  1915. * @since 8.1.0
  1916. */
  1917. public function getPathRelativeToFiles($absolutePath) {
  1918. $path = Filesystem::normalizePath($absolutePath);
  1919. $parts = explode('/', trim($path, '/'), 3);
  1920. // "$user", "files", "path/to/dir"
  1921. if (!isset($parts[1]) || $parts[1] !== 'files') {
  1922. $this->logger->error(
  1923. '$absolutePath must be relative to "files", value is "{absolutePath}"',
  1924. [
  1925. 'absolutePath' => $absolutePath,
  1926. ]
  1927. );
  1928. throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
  1929. }
  1930. if (isset($parts[2])) {
  1931. return $parts[2];
  1932. }
  1933. return '';
  1934. }
  1935. /**
  1936. * @param string $filename
  1937. * @return array
  1938. * @throws \OC\User\NoUserException
  1939. * @throws NotFoundException
  1940. */
  1941. public function getUidAndFilename($filename) {
  1942. $info = $this->getFileInfo($filename);
  1943. if (!$info instanceof \OCP\Files\FileInfo) {
  1944. throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
  1945. }
  1946. $uid = $info->getOwner()->getUID();
  1947. if ($uid != \OC_User::getUser()) {
  1948. Filesystem::initMountPoints($uid);
  1949. $ownerView = new View('/' . $uid . '/files');
  1950. try {
  1951. $filename = $ownerView->getPath($info['fileid']);
  1952. } catch (NotFoundException $e) {
  1953. throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
  1954. }
  1955. }
  1956. return [$uid, $filename];
  1957. }
  1958. /**
  1959. * Creates parent non-existing folders
  1960. *
  1961. * @param string $filePath
  1962. * @return bool
  1963. */
  1964. private function createParentDirectories($filePath) {
  1965. $directoryParts = explode('/', $filePath);
  1966. $directoryParts = array_filter($directoryParts);
  1967. foreach ($directoryParts as $key => $part) {
  1968. $currentPathElements = array_slice($directoryParts, 0, $key);
  1969. $currentPath = '/' . implode('/', $currentPathElements);
  1970. if ($this->is_file($currentPath)) {
  1971. return false;
  1972. }
  1973. if (!$this->file_exists($currentPath)) {
  1974. $this->mkdir($currentPath);
  1975. }
  1976. }
  1977. return true;
  1978. }
  1979. }