View.php 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161
  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. $this->lockFile($source, ILockingProvider::LOCK_SHARED, true);
  653. try {
  654. $this->lockFile($target, ILockingProvider::LOCK_SHARED, true);
  655. $run = true;
  656. if ($this->shouldEmitHooks($source) && (Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target))) {
  657. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  658. $this->emit_file_hooks_pre($exists, $target, $run);
  659. } elseif ($this->shouldEmitHooks($source)) {
  660. $sourcePath = $this->getHookPath($source);
  661. $targetPath = $this->getHookPath($target);
  662. if ($sourcePath !== null && $targetPath !== null) {
  663. \OC_Hook::emit(
  664. Filesystem::CLASSNAME, Filesystem::signal_rename,
  665. [
  666. Filesystem::signal_param_oldpath => $sourcePath,
  667. Filesystem::signal_param_newpath => $targetPath,
  668. Filesystem::signal_param_run => &$run
  669. ]
  670. );
  671. }
  672. }
  673. if ($run) {
  674. $this->verifyPath(dirname($target), basename($target));
  675. $manager = Filesystem::getMountManager();
  676. $mount1 = $this->getMount($source);
  677. $mount2 = $this->getMount($target);
  678. $storage1 = $mount1->getStorage();
  679. $storage2 = $mount2->getStorage();
  680. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  681. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  682. $this->changeLock($source, ILockingProvider::LOCK_EXCLUSIVE, true);
  683. try {
  684. $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE, true);
  685. if ($internalPath1 === '') {
  686. if ($mount1 instanceof MoveableMount) {
  687. $sourceParentMount = $this->getMount(dirname($source));
  688. if ($sourceParentMount === $mount2 && $this->targetIsNotShared($targetUser, $absolutePath2)) {
  689. /**
  690. * @var \OC\Files\Mount\MountPoint | \OC\Files\Mount\MoveableMount $mount1
  691. */
  692. $sourceMountPoint = $mount1->getMountPoint();
  693. $result = $mount1->moveMount($absolutePath2);
  694. $manager->moveMount($sourceMountPoint, $mount1->getMountPoint());
  695. } else {
  696. $result = false;
  697. }
  698. } else {
  699. $result = false;
  700. }
  701. // moving a file/folder within the same mount point
  702. } elseif ($storage1 === $storage2) {
  703. if ($storage1) {
  704. $result = $storage1->rename($internalPath1, $internalPath2);
  705. } else {
  706. $result = false;
  707. }
  708. // moving a file/folder between storages (from $storage1 to $storage2)
  709. } else {
  710. $result = $storage2->moveFromStorage($storage1, $internalPath1, $internalPath2);
  711. }
  712. if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
  713. // if it was a rename from a part file to a regular file it was a write and not a rename operation
  714. $this->writeUpdate($storage2, $internalPath2);
  715. } elseif ($result) {
  716. if ($internalPath1 !== '') { // don't do a cache update for moved mounts
  717. $this->renameUpdate($storage1, $storage2, $internalPath1, $internalPath2);
  718. }
  719. }
  720. } catch (\Exception $e) {
  721. throw $e;
  722. } finally {
  723. $this->changeLock($source, ILockingProvider::LOCK_SHARED, true);
  724. $this->changeLock($target, ILockingProvider::LOCK_SHARED, true);
  725. }
  726. if ((Cache\Scanner::isPartialFile($source) && !Cache\Scanner::isPartialFile($target)) && $result !== false) {
  727. if ($this->shouldEmitHooks()) {
  728. $this->emit_file_hooks_post($exists, $target);
  729. }
  730. } elseif ($result) {
  731. if ($this->shouldEmitHooks($source) && $this->shouldEmitHooks($target)) {
  732. $sourcePath = $this->getHookPath($source);
  733. $targetPath = $this->getHookPath($target);
  734. if ($sourcePath !== null && $targetPath !== null) {
  735. \OC_Hook::emit(
  736. Filesystem::CLASSNAME,
  737. Filesystem::signal_post_rename,
  738. [
  739. Filesystem::signal_param_oldpath => $sourcePath,
  740. Filesystem::signal_param_newpath => $targetPath,
  741. ]
  742. );
  743. }
  744. }
  745. }
  746. }
  747. } catch (\Exception $e) {
  748. throw $e;
  749. } finally {
  750. $this->unlockFile($source, ILockingProvider::LOCK_SHARED, true);
  751. $this->unlockFile($target, ILockingProvider::LOCK_SHARED, true);
  752. }
  753. }
  754. return $result;
  755. }
  756. /**
  757. * Copy a file/folder from the source path to target path
  758. *
  759. * @param string $source source path
  760. * @param string $target target path
  761. * @param bool $preserveMtime whether to preserve mtime on the copy
  762. *
  763. * @return bool|mixed
  764. */
  765. public function copy($source, $target, $preserveMtime = false) {
  766. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
  767. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
  768. $result = false;
  769. if (
  770. Filesystem::isValidPath($target)
  771. && Filesystem::isValidPath($source)
  772. && !Filesystem::isFileBlacklisted($target)
  773. ) {
  774. $source = $this->getRelativePath($absolutePath1);
  775. $target = $this->getRelativePath($absolutePath2);
  776. if ($source == null || $target == null) {
  777. return false;
  778. }
  779. $run = true;
  780. $this->lockFile($target, ILockingProvider::LOCK_SHARED);
  781. $this->lockFile($source, ILockingProvider::LOCK_SHARED);
  782. $lockTypePath1 = ILockingProvider::LOCK_SHARED;
  783. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  784. try {
  785. $exists = $this->file_exists($target);
  786. if ($this->shouldEmitHooks()) {
  787. \OC_Hook::emit(
  788. Filesystem::CLASSNAME,
  789. Filesystem::signal_copy,
  790. [
  791. Filesystem::signal_param_oldpath => $this->getHookPath($source),
  792. Filesystem::signal_param_newpath => $this->getHookPath($target),
  793. Filesystem::signal_param_run => &$run
  794. ]
  795. );
  796. $this->emit_file_hooks_pre($exists, $target, $run);
  797. }
  798. if ($run) {
  799. $mount1 = $this->getMount($source);
  800. $mount2 = $this->getMount($target);
  801. $storage1 = $mount1->getStorage();
  802. $internalPath1 = $mount1->getInternalPath($absolutePath1);
  803. $storage2 = $mount2->getStorage();
  804. $internalPath2 = $mount2->getInternalPath($absolutePath2);
  805. $this->changeLock($target, ILockingProvider::LOCK_EXCLUSIVE);
  806. $lockTypePath2 = ILockingProvider::LOCK_EXCLUSIVE;
  807. if ($mount1->getMountPoint() == $mount2->getMountPoint()) {
  808. if ($storage1) {
  809. $result = $storage1->copy($internalPath1, $internalPath2);
  810. } else {
  811. $result = false;
  812. }
  813. } else {
  814. $result = $storage2->copyFromStorage($storage1, $internalPath1, $internalPath2);
  815. }
  816. $this->writeUpdate($storage2, $internalPath2);
  817. $this->changeLock($target, ILockingProvider::LOCK_SHARED);
  818. $lockTypePath2 = ILockingProvider::LOCK_SHARED;
  819. if ($this->shouldEmitHooks() && $result !== false) {
  820. \OC_Hook::emit(
  821. Filesystem::CLASSNAME,
  822. Filesystem::signal_post_copy,
  823. [
  824. Filesystem::signal_param_oldpath => $this->getHookPath($source),
  825. Filesystem::signal_param_newpath => $this->getHookPath($target)
  826. ]
  827. );
  828. $this->emit_file_hooks_post($exists, $target);
  829. }
  830. }
  831. } catch (\Exception $e) {
  832. $this->unlockFile($target, $lockTypePath2);
  833. $this->unlockFile($source, $lockTypePath1);
  834. throw $e;
  835. }
  836. $this->unlockFile($target, $lockTypePath2);
  837. $this->unlockFile($source, $lockTypePath1);
  838. }
  839. return $result;
  840. }
  841. /**
  842. * @param string $path
  843. * @param string $mode 'r' or 'w'
  844. * @return resource|false
  845. * @throws LockedException
  846. */
  847. public function fopen($path, $mode) {
  848. $mode = str_replace('b', '', $mode); // the binary flag is a windows only feature which we do not support
  849. $hooks = [];
  850. switch ($mode) {
  851. case 'r':
  852. $hooks[] = 'read';
  853. break;
  854. case 'r+':
  855. case 'w+':
  856. case 'x+':
  857. case 'a+':
  858. $hooks[] = 'read';
  859. $hooks[] = 'write';
  860. break;
  861. case 'w':
  862. case 'x':
  863. case 'a':
  864. $hooks[] = 'write';
  865. break;
  866. default:
  867. $this->logger->error('invalid mode (' . $mode . ') for ' . $path, ['app' => 'core']);
  868. }
  869. if ($mode !== 'r' && $mode !== 'w') {
  870. $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']);
  871. }
  872. $handle = $this->basicOperation('fopen', $path, $hooks, $mode);
  873. if (!is_resource($handle) && $mode === 'r') {
  874. // trying to read a file that isn't on disk, check if the cache is out of sync and rescan if needed
  875. $mount = $this->getMount($path);
  876. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  877. $storage = $mount->getStorage();
  878. if ($storage->getCache()->inCache($internalPath) && !$storage->file_exists($path)) {
  879. $this->writeUpdate($storage, $internalPath);
  880. }
  881. }
  882. return $handle;
  883. }
  884. /**
  885. * @param string $path
  886. * @throws InvalidPathException
  887. */
  888. public function toTmpFile($path): string|false {
  889. $this->assertPathLength($path);
  890. if (Filesystem::isValidPath($path)) {
  891. $source = $this->fopen($path, 'r');
  892. if ($source) {
  893. $extension = pathinfo($path, PATHINFO_EXTENSION);
  894. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($extension);
  895. file_put_contents($tmpFile, $source);
  896. return $tmpFile;
  897. } else {
  898. return false;
  899. }
  900. } else {
  901. return false;
  902. }
  903. }
  904. /**
  905. * @param string $tmpFile
  906. * @param string $path
  907. * @return bool|mixed
  908. * @throws InvalidPathException
  909. */
  910. public function fromTmpFile($tmpFile, $path) {
  911. $this->assertPathLength($path);
  912. if (Filesystem::isValidPath($path)) {
  913. // Get directory that the file is going into
  914. $filePath = dirname($path);
  915. // Create the directories if any
  916. if (!$this->file_exists($filePath)) {
  917. $result = $this->createParentDirectories($filePath);
  918. if ($result === false) {
  919. return false;
  920. }
  921. }
  922. $source = fopen($tmpFile, 'r');
  923. if ($source) {
  924. $result = $this->file_put_contents($path, $source);
  925. /**
  926. * $this->file_put_contents() might have already closed
  927. * the resource, so we check it, before trying to close it
  928. * to avoid messages in the error log.
  929. * @psalm-suppress RedundantCondition false-positive
  930. */
  931. if (is_resource($source)) {
  932. fclose($source);
  933. }
  934. unlink($tmpFile);
  935. return $result;
  936. } else {
  937. return false;
  938. }
  939. } else {
  940. return false;
  941. }
  942. }
  943. /**
  944. * @param string $path
  945. * @return mixed
  946. * @throws InvalidPathException
  947. */
  948. public function getMimeType($path) {
  949. $this->assertPathLength($path);
  950. return $this->basicOperation('getMimeType', $path);
  951. }
  952. /**
  953. * @param string $type
  954. * @param string $path
  955. * @param bool $raw
  956. */
  957. public function hash($type, $path, $raw = false): string|bool {
  958. $postFix = (substr($path, -1) === '/') ? '/' : '';
  959. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  960. if (Filesystem::isValidPath($path)) {
  961. $path = $this->getRelativePath($absolutePath);
  962. if ($path == null) {
  963. return false;
  964. }
  965. if ($this->shouldEmitHooks($path)) {
  966. \OC_Hook::emit(
  967. Filesystem::CLASSNAME,
  968. Filesystem::signal_read,
  969. [Filesystem::signal_param_path => $this->getHookPath($path)]
  970. );
  971. }
  972. /** @var Storage|null $storage */
  973. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  974. if ($storage) {
  975. return $storage->hash($type, $internalPath, $raw);
  976. }
  977. }
  978. return false;
  979. }
  980. /**
  981. * @param string $path
  982. * @return mixed
  983. * @throws InvalidPathException
  984. */
  985. public function free_space($path = '/') {
  986. $this->assertPathLength($path);
  987. $result = $this->basicOperation('free_space', $path);
  988. if ($result === null) {
  989. throw new InvalidPathException();
  990. }
  991. return $result;
  992. }
  993. /**
  994. * abstraction layer for basic filesystem functions: wrapper for \OC\Files\Storage\Storage
  995. *
  996. * @param mixed $extraParam (optional)
  997. * @return mixed
  998. * @throws LockedException
  999. *
  1000. * This method takes requests for basic filesystem functions (e.g. reading & writing
  1001. * files), processes hooks and proxies, sanitises paths, and finally passes them on to
  1002. * \OC\Files\Storage\Storage for delegation to a storage backend for execution
  1003. */
  1004. private function basicOperation(string $operation, string $path, array $hooks = [], $extraParam = null) {
  1005. $postFix = (substr($path, -1) === '/') ? '/' : '';
  1006. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  1007. if (Filesystem::isValidPath($path)
  1008. && !Filesystem::isFileBlacklisted($path)
  1009. ) {
  1010. $path = $this->getRelativePath($absolutePath);
  1011. if ($path == null) {
  1012. return false;
  1013. }
  1014. if (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks)) {
  1015. // always a shared lock during pre-hooks so the hook can read the file
  1016. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  1017. }
  1018. $run = $this->runHooks($hooks, $path);
  1019. [$storage, $internalPath] = Filesystem::resolvePath($absolutePath . $postFix);
  1020. if ($run && $storage) {
  1021. /** @var Storage $storage */
  1022. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1023. try {
  1024. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  1025. } catch (LockedException $e) {
  1026. // release the shared lock we acquired before quitting
  1027. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1028. throw $e;
  1029. }
  1030. }
  1031. try {
  1032. if (!is_null($extraParam)) {
  1033. $result = $storage->$operation($internalPath, $extraParam);
  1034. } else {
  1035. $result = $storage->$operation($internalPath);
  1036. }
  1037. } catch (\Exception $e) {
  1038. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1039. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1040. } elseif (in_array('read', $hooks)) {
  1041. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1042. }
  1043. throw $e;
  1044. }
  1045. if ($result !== false && in_array('delete', $hooks)) {
  1046. $this->removeUpdate($storage, $internalPath);
  1047. }
  1048. if ($result !== false && in_array('write', $hooks, true) && $operation !== 'fopen' && $operation !== 'touch') {
  1049. $isCreateOperation = $operation === 'mkdir' || ($operation === 'file_put_contents' && in_array('create', $hooks, true));
  1050. $sizeDifference = $operation === 'mkdir' ? 0 : $result;
  1051. $this->writeUpdate($storage, $internalPath, null, $isCreateOperation ? $sizeDifference : null);
  1052. }
  1053. if ($result !== false && in_array('touch', $hooks)) {
  1054. $this->writeUpdate($storage, $internalPath, $extraParam, 0);
  1055. }
  1056. if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
  1057. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  1058. }
  1059. $unlockLater = false;
  1060. if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
  1061. $unlockLater = true;
  1062. // make sure our unlocking callback will still be called if connection is aborted
  1063. ignore_user_abort(true);
  1064. $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
  1065. if (in_array('write', $hooks)) {
  1066. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1067. } elseif (in_array('read', $hooks)) {
  1068. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1069. }
  1070. });
  1071. }
  1072. if ($this->shouldEmitHooks($path) && $result !== false) {
  1073. if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
  1074. $this->runHooks($hooks, $path, true);
  1075. }
  1076. }
  1077. if (!$unlockLater
  1078. && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
  1079. ) {
  1080. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1081. }
  1082. return $result;
  1083. } else {
  1084. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1085. }
  1086. }
  1087. return null;
  1088. }
  1089. /**
  1090. * get the path relative to the default root for hook usage
  1091. *
  1092. * @param string $path
  1093. * @return ?string
  1094. */
  1095. private function getHookPath($path): ?string {
  1096. $view = Filesystem::getView();
  1097. if (!$view) {
  1098. return $path;
  1099. }
  1100. return $view->getRelativePath($this->getAbsolutePath($path));
  1101. }
  1102. private function shouldEmitHooks(string $path = ''): bool {
  1103. if ($path && Cache\Scanner::isPartialFile($path)) {
  1104. return false;
  1105. }
  1106. if (!Filesystem::$loaded) {
  1107. return false;
  1108. }
  1109. $defaultRoot = Filesystem::getRoot();
  1110. if ($defaultRoot === null) {
  1111. return false;
  1112. }
  1113. if ($this->fakeRoot === $defaultRoot) {
  1114. return true;
  1115. }
  1116. $fullPath = $this->getAbsolutePath($path);
  1117. if ($fullPath === $defaultRoot) {
  1118. return true;
  1119. }
  1120. return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
  1121. }
  1122. /**
  1123. * @param string[] $hooks
  1124. * @param string $path
  1125. * @param bool $post
  1126. * @return bool
  1127. */
  1128. private function runHooks($hooks, $path, $post = false) {
  1129. $relativePath = $path;
  1130. $path = $this->getHookPath($path);
  1131. $prefix = $post ? 'post_' : '';
  1132. $run = true;
  1133. if ($this->shouldEmitHooks($relativePath)) {
  1134. foreach ($hooks as $hook) {
  1135. if ($hook != 'read') {
  1136. \OC_Hook::emit(
  1137. Filesystem::CLASSNAME,
  1138. $prefix . $hook,
  1139. [
  1140. Filesystem::signal_param_run => &$run,
  1141. Filesystem::signal_param_path => $path
  1142. ]
  1143. );
  1144. } elseif (!$post) {
  1145. \OC_Hook::emit(
  1146. Filesystem::CLASSNAME,
  1147. $prefix . $hook,
  1148. [
  1149. Filesystem::signal_param_path => $path
  1150. ]
  1151. );
  1152. }
  1153. }
  1154. }
  1155. return $run;
  1156. }
  1157. /**
  1158. * check if a file or folder has been updated since $time
  1159. *
  1160. * @param string $path
  1161. * @param int $time
  1162. * @return bool
  1163. */
  1164. public function hasUpdated($path, $time) {
  1165. return $this->basicOperation('hasUpdated', $path, [], $time);
  1166. }
  1167. /**
  1168. * @param string $ownerId
  1169. * @return IUser
  1170. */
  1171. private function getUserObjectForOwner(string $ownerId) {
  1172. return new LazyUser($ownerId, $this->userManager);
  1173. }
  1174. /**
  1175. * Get file info from cache
  1176. *
  1177. * If the file is not in cached it will be scanned
  1178. * If the file has changed on storage the cache will be updated
  1179. *
  1180. * @param Storage $storage
  1181. * @param string $internalPath
  1182. * @param string $relativePath
  1183. * @return ICacheEntry|bool
  1184. */
  1185. private function getCacheEntry($storage, $internalPath, $relativePath) {
  1186. $cache = $storage->getCache($internalPath);
  1187. $data = $cache->get($internalPath);
  1188. $watcher = $storage->getWatcher($internalPath);
  1189. try {
  1190. // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
  1191. if (!$data || (isset($data['size']) && $data['size'] === -1)) {
  1192. if (!$storage->file_exists($internalPath)) {
  1193. return false;
  1194. }
  1195. // don't need to get a lock here since the scanner does it's own locking
  1196. $scanner = $storage->getScanner($internalPath);
  1197. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1198. $data = $cache->get($internalPath);
  1199. } elseif (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
  1200. $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1201. $watcher->update($internalPath, $data);
  1202. $storage->getPropagator()->propagateChange($internalPath, time());
  1203. $data = $cache->get($internalPath);
  1204. $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1205. }
  1206. } catch (LockedException $e) {
  1207. // if the file is locked we just use the old cache info
  1208. }
  1209. return $data;
  1210. }
  1211. /**
  1212. * get the filesystem info
  1213. *
  1214. * @param string $path
  1215. * @param bool|string $includeMountPoints true to add mountpoint sizes,
  1216. * 'ext' to add only ext storage mount point sizes. Defaults to true.
  1217. * @return \OC\Files\FileInfo|false False if file does not exist
  1218. */
  1219. public function getFileInfo($path, $includeMountPoints = true) {
  1220. $this->assertPathLength($path);
  1221. if (!Filesystem::isValidPath($path)) {
  1222. return false;
  1223. }
  1224. if (Cache\Scanner::isPartialFile($path)) {
  1225. return $this->getPartFileInfo($path);
  1226. }
  1227. $relativePath = $path;
  1228. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1229. $mount = Filesystem::getMountManager()->find($path);
  1230. $storage = $mount->getStorage();
  1231. $internalPath = $mount->getInternalPath($path);
  1232. if ($storage) {
  1233. $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
  1234. if (!$data instanceof ICacheEntry) {
  1235. return false;
  1236. }
  1237. if ($mount instanceof MoveableMount && $internalPath === '') {
  1238. $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
  1239. }
  1240. $ownerId = $storage->getOwner($internalPath);
  1241. $owner = null;
  1242. if ($ownerId !== null && $ownerId !== false) {
  1243. // ownerId might be null if files are accessed with an access token without file system access
  1244. $owner = $this->getUserObjectForOwner($ownerId);
  1245. }
  1246. $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
  1247. if (isset($data['fileid'])) {
  1248. if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
  1249. //add the sizes of other mount points to the folder
  1250. $extOnly = ($includeMountPoints === 'ext');
  1251. $this->addSubMounts($info, $extOnly);
  1252. }
  1253. }
  1254. return $info;
  1255. } else {
  1256. $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
  1257. }
  1258. return false;
  1259. }
  1260. /**
  1261. * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
  1262. */
  1263. public function addSubMounts(FileInfo $info, $extOnly = false): void {
  1264. $mounts = Filesystem::getMountManager()->findIn($info->getPath());
  1265. $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
  1266. $subStorage = $mount->getStorage();
  1267. return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
  1268. }));
  1269. }
  1270. /**
  1271. * get the content of a directory
  1272. *
  1273. * @param string $directory path under datadirectory
  1274. * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  1275. * @return FileInfo[]
  1276. */
  1277. public function getDirectoryContent($directory, $mimetype_filter = '', ?\OCP\Files\FileInfo $directoryInfo = null) {
  1278. $this->assertPathLength($directory);
  1279. if (!Filesystem::isValidPath($directory)) {
  1280. return [];
  1281. }
  1282. $path = $this->getAbsolutePath($directory);
  1283. $path = Filesystem::normalizePath($path);
  1284. $mount = $this->getMount($directory);
  1285. $storage = $mount->getStorage();
  1286. $internalPath = $mount->getInternalPath($path);
  1287. if (!$storage) {
  1288. return [];
  1289. }
  1290. $cache = $storage->getCache($internalPath);
  1291. $user = \OC_User::getUser();
  1292. if (!$directoryInfo) {
  1293. $data = $this->getCacheEntry($storage, $internalPath, $directory);
  1294. if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
  1295. return [];
  1296. }
  1297. } else {
  1298. $data = $directoryInfo;
  1299. }
  1300. if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
  1301. return [];
  1302. }
  1303. $folderId = $data->getId();
  1304. $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
  1305. $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
  1306. $fileNames = array_map(function (ICacheEntry $content) {
  1307. return $content->getName();
  1308. }, $contents);
  1309. /**
  1310. * @var \OC\Files\FileInfo[] $fileInfos
  1311. */
  1312. $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
  1313. if ($sharingDisabled) {
  1314. $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1315. }
  1316. $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
  1317. return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
  1318. }, $contents);
  1319. $files = array_combine($fileNames, $fileInfos);
  1320. //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
  1321. $mounts = Filesystem::getMountManager()->findIn($path);
  1322. // make sure nested mounts are sorted after their parent mounts
  1323. // otherwise doesn't propagate the etag across storage boundaries correctly
  1324. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1325. return $a->getMountPoint() <=> $b->getMountPoint();
  1326. });
  1327. $dirLength = strlen($path);
  1328. foreach ($mounts as $mount) {
  1329. $mountPoint = $mount->getMountPoint();
  1330. $subStorage = $mount->getStorage();
  1331. if ($subStorage) {
  1332. $subCache = $subStorage->getCache('');
  1333. $rootEntry = $subCache->get('');
  1334. if (!$rootEntry) {
  1335. $subScanner = $subStorage->getScanner();
  1336. try {
  1337. $subScanner->scanFile('');
  1338. } catch (\OCP\Files\StorageNotAvailableException $e) {
  1339. continue;
  1340. } catch (\OCP\Files\StorageInvalidException $e) {
  1341. continue;
  1342. } catch (\Exception $e) {
  1343. // sometimes when the storage is not available it can be any exception
  1344. $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
  1345. 'exception' => $e,
  1346. 'app' => 'core',
  1347. ]);
  1348. continue;
  1349. }
  1350. $rootEntry = $subCache->get('');
  1351. }
  1352. if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
  1353. $relativePath = trim(substr($mountPoint, $dirLength), '/');
  1354. if ($pos = strpos($relativePath, '/')) {
  1355. //mountpoint inside subfolder add size to the correct folder
  1356. $entryName = substr($relativePath, 0, $pos);
  1357. if (isset($files[$entryName])) {
  1358. $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
  1359. }
  1360. } else { //mountpoint in this folder, add an entry for it
  1361. $rootEntry['name'] = $relativePath;
  1362. $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
  1363. $permissions = $rootEntry['permissions'];
  1364. // do not allow renaming/deleting the mount point if they are not shared files/folders
  1365. // for shared files/folders we use the permissions given by the owner
  1366. if ($mount instanceof MoveableMount) {
  1367. $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
  1368. } else {
  1369. $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
  1370. }
  1371. $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
  1372. // if sharing was disabled for the user we remove the share permissions
  1373. if ($sharingDisabled) {
  1374. $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1375. }
  1376. $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
  1377. $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. if ($mimetype_filter) {
  1383. $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
  1384. if (strpos($mimetype_filter, '/')) {
  1385. return $file->getMimetype() === $mimetype_filter;
  1386. } else {
  1387. return $file->getMimePart() === $mimetype_filter;
  1388. }
  1389. });
  1390. }
  1391. return array_values($files);
  1392. }
  1393. /**
  1394. * change file metadata
  1395. *
  1396. * @param string $path
  1397. * @param array|\OCP\Files\FileInfo $data
  1398. * @return int
  1399. *
  1400. * returns the fileid of the updated file
  1401. */
  1402. public function putFileInfo($path, $data) {
  1403. $this->assertPathLength($path);
  1404. if ($data instanceof FileInfo) {
  1405. $data = $data->getData();
  1406. }
  1407. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1408. /**
  1409. * @var Storage $storage
  1410. * @var string $internalPath
  1411. */
  1412. [$storage, $internalPath] = Filesystem::resolvePath($path);
  1413. if ($storage) {
  1414. $cache = $storage->getCache($path);
  1415. if (!$cache->inCache($internalPath)) {
  1416. $scanner = $storage->getScanner($internalPath);
  1417. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1418. }
  1419. return $cache->put($internalPath, $data);
  1420. } else {
  1421. return -1;
  1422. }
  1423. }
  1424. /**
  1425. * search for files with the name matching $query
  1426. *
  1427. * @param string $query
  1428. * @return FileInfo[]
  1429. */
  1430. public function search($query) {
  1431. return $this->searchCommon('search', ['%' . $query . '%']);
  1432. }
  1433. /**
  1434. * search for files with the name matching $query
  1435. *
  1436. * @param string $query
  1437. * @return FileInfo[]
  1438. */
  1439. public function searchRaw($query) {
  1440. return $this->searchCommon('search', [$query]);
  1441. }
  1442. /**
  1443. * search for files by mimetype
  1444. *
  1445. * @param string $mimetype
  1446. * @return FileInfo[]
  1447. */
  1448. public function searchByMime($mimetype) {
  1449. return $this->searchCommon('searchByMime', [$mimetype]);
  1450. }
  1451. /**
  1452. * search for files by tag
  1453. *
  1454. * @param string|int $tag name or tag id
  1455. * @param string $userId owner of the tags
  1456. * @return FileInfo[]
  1457. */
  1458. public function searchByTag($tag, $userId) {
  1459. return $this->searchCommon('searchByTag', [$tag, $userId]);
  1460. }
  1461. /**
  1462. * @param string $method cache method
  1463. * @param array $args
  1464. * @return FileInfo[]
  1465. */
  1466. private function searchCommon($method, $args) {
  1467. $files = [];
  1468. $rootLength = strlen($this->fakeRoot);
  1469. $mount = $this->getMount('');
  1470. $mountPoint = $mount->getMountPoint();
  1471. $storage = $mount->getStorage();
  1472. $userManager = \OC::$server->getUserManager();
  1473. if ($storage) {
  1474. $cache = $storage->getCache('');
  1475. $results = call_user_func_array([$cache, $method], $args);
  1476. foreach ($results as $result) {
  1477. if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
  1478. $internalPath = $result['path'];
  1479. $path = $mountPoint . $result['path'];
  1480. $result['path'] = substr($mountPoint . $result['path'], $rootLength);
  1481. $owner = $userManager->get($storage->getOwner($internalPath));
  1482. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1483. }
  1484. }
  1485. $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
  1486. foreach ($mounts as $mount) {
  1487. $mountPoint = $mount->getMountPoint();
  1488. $storage = $mount->getStorage();
  1489. if ($storage) {
  1490. $cache = $storage->getCache('');
  1491. $relativeMountPoint = substr($mountPoint, $rootLength);
  1492. $results = call_user_func_array([$cache, $method], $args);
  1493. if ($results) {
  1494. foreach ($results as $result) {
  1495. $internalPath = $result['path'];
  1496. $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
  1497. $path = rtrim($mountPoint . $internalPath, '/');
  1498. $owner = $userManager->get($storage->getOwner($internalPath));
  1499. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1500. }
  1501. }
  1502. }
  1503. }
  1504. }
  1505. return $files;
  1506. }
  1507. /**
  1508. * Get the owner for a file or folder
  1509. *
  1510. * @param string $path
  1511. * @return string the user id of the owner
  1512. * @throws NotFoundException
  1513. */
  1514. public function getOwner($path) {
  1515. $info = $this->getFileInfo($path);
  1516. if (!$info) {
  1517. throw new NotFoundException($path . ' not found while trying to get owner');
  1518. }
  1519. if ($info->getOwner() === null) {
  1520. throw new NotFoundException($path . ' has no owner');
  1521. }
  1522. return $info->getOwner()->getUID();
  1523. }
  1524. /**
  1525. * get the ETag for a file or folder
  1526. *
  1527. * @param string $path
  1528. * @return string|false
  1529. */
  1530. public function getETag($path) {
  1531. [$storage, $internalPath] = $this->resolvePath($path);
  1532. if ($storage) {
  1533. return $storage->getETag($internalPath);
  1534. } else {
  1535. return false;
  1536. }
  1537. }
  1538. /**
  1539. * Get the path of a file by id, relative to the view
  1540. *
  1541. * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
  1542. *
  1543. * @param int $id
  1544. * @param int|null $storageId
  1545. * @return string
  1546. * @throws NotFoundException
  1547. */
  1548. public function getPath($id, ?int $storageId = null) {
  1549. $id = (int)$id;
  1550. $manager = Filesystem::getMountManager();
  1551. $mounts = $manager->findIn($this->fakeRoot);
  1552. $mounts[] = $manager->find($this->fakeRoot);
  1553. $mounts = array_filter($mounts);
  1554. // reverse the array, so we start with the storage this view is in
  1555. // which is the most likely to contain the file we're looking for
  1556. $mounts = array_reverse($mounts);
  1557. // put non-shared mounts in front of the shared mount
  1558. // this prevents unneeded recursion into shares
  1559. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1560. return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
  1561. });
  1562. if (!is_null($storageId)) {
  1563. $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
  1564. return $mount->getNumericStorageId() === $storageId;
  1565. });
  1566. }
  1567. foreach ($mounts as $mount) {
  1568. /**
  1569. * @var \OC\Files\Mount\MountPoint $mount
  1570. */
  1571. if ($mount->getStorage()) {
  1572. $cache = $mount->getStorage()->getCache();
  1573. $internalPath = $cache->getPathById($id);
  1574. if (is_string($internalPath)) {
  1575. $fullPath = $mount->getMountPoint() . $internalPath;
  1576. if (!is_null($path = $this->getRelativePath($fullPath))) {
  1577. return $path;
  1578. }
  1579. }
  1580. }
  1581. }
  1582. throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
  1583. }
  1584. /**
  1585. * @param string $path
  1586. * @throws InvalidPathException
  1587. */
  1588. private function assertPathLength($path): void {
  1589. $maxLen = min(PHP_MAXPATHLEN, 4000);
  1590. // Check for the string length - performed using isset() instead of strlen()
  1591. // because isset() is about 5x-40x faster.
  1592. if (isset($path[$maxLen])) {
  1593. $pathLen = strlen($path);
  1594. throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
  1595. }
  1596. }
  1597. /**
  1598. * check if it is allowed to move a mount point to a given target.
  1599. * It is not allowed to move a mount point into a different mount point or
  1600. * into an already shared folder
  1601. */
  1602. private function targetIsNotShared(string $user, string $targetPath): bool {
  1603. $providers = [
  1604. IShare::TYPE_USER,
  1605. IShare::TYPE_GROUP,
  1606. IShare::TYPE_EMAIL,
  1607. IShare::TYPE_CIRCLE,
  1608. IShare::TYPE_ROOM,
  1609. IShare::TYPE_DECK,
  1610. IShare::TYPE_SCIENCEMESH
  1611. ];
  1612. $shareManager = Server::get(IManager::class);
  1613. /** @var IShare[] $shares */
  1614. $shares = array_merge(...array_map(function (int $type) use ($shareManager, $user) {
  1615. return $shareManager->getSharesBy($user, $type);
  1616. }, $providers));
  1617. foreach ($shares as $share) {
  1618. if (str_starts_with($targetPath, $share->getNode()->getPath())) {
  1619. $this->logger->debug(
  1620. 'It is not allowed to move one mount point into a shared folder',
  1621. ['app' => 'files']);
  1622. return false;
  1623. }
  1624. }
  1625. return true;
  1626. }
  1627. /**
  1628. * Get a fileinfo object for files that are ignored in the cache (part files)
  1629. */
  1630. private function getPartFileInfo(string $path): \OC\Files\FileInfo {
  1631. $mount = $this->getMount($path);
  1632. $storage = $mount->getStorage();
  1633. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  1634. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1635. return new FileInfo(
  1636. $this->getAbsolutePath($path),
  1637. $storage,
  1638. $internalPath,
  1639. [
  1640. 'fileid' => null,
  1641. 'mimetype' => $storage->getMimeType($internalPath),
  1642. 'name' => basename($path),
  1643. 'etag' => null,
  1644. 'size' => $storage->filesize($internalPath),
  1645. 'mtime' => $storage->filemtime($internalPath),
  1646. 'encrypted' => false,
  1647. 'permissions' => \OCP\Constants::PERMISSION_ALL
  1648. ],
  1649. $mount,
  1650. $owner
  1651. );
  1652. }
  1653. /**
  1654. * @param string $path
  1655. * @param string $fileName
  1656. * @throws InvalidPathException
  1657. */
  1658. public function verifyPath($path, $fileName): void {
  1659. try {
  1660. /** @type \OCP\Files\Storage $storage */
  1661. [$storage, $internalPath] = $this->resolvePath($path);
  1662. $storage->verifyPath($internalPath, $fileName);
  1663. } catch (ReservedWordException $ex) {
  1664. $l = \OCP\Util::getL10N('lib');
  1665. throw new InvalidPathException($l->t('File name is a reserved word'));
  1666. } catch (InvalidCharacterInPathException $ex) {
  1667. $l = \OCP\Util::getL10N('lib');
  1668. throw new InvalidPathException($l->t('File name contains at least one invalid character'));
  1669. } catch (FileNameTooLongException $ex) {
  1670. $l = \OCP\Util::getL10N('lib');
  1671. throw new InvalidPathException($l->t('File name is too long'));
  1672. } catch (InvalidDirectoryException $ex) {
  1673. $l = \OCP\Util::getL10N('lib');
  1674. throw new InvalidPathException($l->t('Dot files are not allowed'));
  1675. } catch (EmptyFileNameException $ex) {
  1676. $l = \OCP\Util::getL10N('lib');
  1677. throw new InvalidPathException($l->t('Empty filename is not allowed'));
  1678. }
  1679. }
  1680. /**
  1681. * get all parent folders of $path
  1682. *
  1683. * @param string $path
  1684. * @return string[]
  1685. */
  1686. private function getParents($path) {
  1687. $path = trim($path, '/');
  1688. if (!$path) {
  1689. return [];
  1690. }
  1691. $parts = explode('/', $path);
  1692. // remove the single file
  1693. array_pop($parts);
  1694. $result = ['/'];
  1695. $resultPath = '';
  1696. foreach ($parts as $part) {
  1697. if ($part) {
  1698. $resultPath .= '/' . $part;
  1699. $result[] = $resultPath;
  1700. }
  1701. }
  1702. return $result;
  1703. }
  1704. /**
  1705. * Returns the mount point for which to lock
  1706. *
  1707. * @param string $absolutePath absolute path
  1708. * @param bool $useParentMount true to return parent mount instead of whatever
  1709. * is mounted directly on the given path, false otherwise
  1710. * @return IMountPoint mount point for which to apply locks
  1711. */
  1712. private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
  1713. $mount = Filesystem::getMountManager()->find($absolutePath);
  1714. if ($useParentMount) {
  1715. // find out if something is mounted directly on the path
  1716. $internalPath = $mount->getInternalPath($absolutePath);
  1717. if ($internalPath === '') {
  1718. // resolve the parent mount instead
  1719. $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
  1720. }
  1721. }
  1722. return $mount;
  1723. }
  1724. /**
  1725. * Lock the given path
  1726. *
  1727. * @param string $path the path of the file to lock, relative to the view
  1728. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1729. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1730. *
  1731. * @return bool False if the path is excluded from locking, true otherwise
  1732. * @throws LockedException if the path is already locked
  1733. */
  1734. private function lockPath($path, $type, $lockMountPoint = false) {
  1735. $absolutePath = $this->getAbsolutePath($path);
  1736. $absolutePath = Filesystem::normalizePath($absolutePath);
  1737. if (!$this->shouldLockFile($absolutePath)) {
  1738. return false;
  1739. }
  1740. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1741. try {
  1742. $storage = $mount->getStorage();
  1743. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1744. $storage->acquireLock(
  1745. $mount->getInternalPath($absolutePath),
  1746. $type,
  1747. $this->lockingProvider
  1748. );
  1749. }
  1750. } catch (LockedException $e) {
  1751. // rethrow with the a human-readable path
  1752. throw new LockedException(
  1753. $this->getPathRelativeToFiles($absolutePath),
  1754. $e,
  1755. $e->getExistingLock()
  1756. );
  1757. }
  1758. return true;
  1759. }
  1760. /**
  1761. * Change the lock type
  1762. *
  1763. * @param string $path the path of the file to lock, relative to the view
  1764. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1765. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1766. *
  1767. * @return bool False if the path is excluded from locking, true otherwise
  1768. * @throws LockedException if the path is already locked
  1769. */
  1770. public function changeLock($path, $type, $lockMountPoint = false) {
  1771. $path = Filesystem::normalizePath($path);
  1772. $absolutePath = $this->getAbsolutePath($path);
  1773. $absolutePath = Filesystem::normalizePath($absolutePath);
  1774. if (!$this->shouldLockFile($absolutePath)) {
  1775. return false;
  1776. }
  1777. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1778. try {
  1779. $storage = $mount->getStorage();
  1780. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1781. $storage->changeLock(
  1782. $mount->getInternalPath($absolutePath),
  1783. $type,
  1784. $this->lockingProvider
  1785. );
  1786. }
  1787. } catch (LockedException $e) {
  1788. try {
  1789. // rethrow with the a human-readable path
  1790. throw new LockedException(
  1791. $this->getPathRelativeToFiles($absolutePath),
  1792. $e,
  1793. $e->getExistingLock()
  1794. );
  1795. } catch (\InvalidArgumentException $ex) {
  1796. throw new LockedException(
  1797. $absolutePath,
  1798. $ex,
  1799. $e->getExistingLock()
  1800. );
  1801. }
  1802. }
  1803. return true;
  1804. }
  1805. /**
  1806. * Unlock the given path
  1807. *
  1808. * @param string $path the path of the file to unlock, relative to the view
  1809. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1810. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1811. *
  1812. * @return bool False if the path is excluded from locking, true otherwise
  1813. * @throws LockedException
  1814. */
  1815. private function unlockPath($path, $type, $lockMountPoint = false) {
  1816. $absolutePath = $this->getAbsolutePath($path);
  1817. $absolutePath = Filesystem::normalizePath($absolutePath);
  1818. if (!$this->shouldLockFile($absolutePath)) {
  1819. return false;
  1820. }
  1821. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1822. $storage = $mount->getStorage();
  1823. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1824. $storage->releaseLock(
  1825. $mount->getInternalPath($absolutePath),
  1826. $type,
  1827. $this->lockingProvider
  1828. );
  1829. }
  1830. return true;
  1831. }
  1832. /**
  1833. * Lock a path and all its parents up to the root of the view
  1834. *
  1835. * @param string $path the path of the file to lock relative to the view
  1836. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1837. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1838. *
  1839. * @return bool False if the path is excluded from locking, true otherwise
  1840. * @throws LockedException
  1841. */
  1842. public function lockFile($path, $type, $lockMountPoint = false) {
  1843. $absolutePath = $this->getAbsolutePath($path);
  1844. $absolutePath = Filesystem::normalizePath($absolutePath);
  1845. if (!$this->shouldLockFile($absolutePath)) {
  1846. return false;
  1847. }
  1848. $this->lockPath($path, $type, $lockMountPoint);
  1849. $parents = $this->getParents($path);
  1850. foreach ($parents as $parent) {
  1851. $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
  1852. }
  1853. return true;
  1854. }
  1855. /**
  1856. * Unlock a path and all its parents up to the root of the view
  1857. *
  1858. * @param string $path the path of the file to lock relative to the view
  1859. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1860. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1861. *
  1862. * @return bool False if the path is excluded from locking, true otherwise
  1863. * @throws LockedException
  1864. */
  1865. public function unlockFile($path, $type, $lockMountPoint = false) {
  1866. $absolutePath = $this->getAbsolutePath($path);
  1867. $absolutePath = Filesystem::normalizePath($absolutePath);
  1868. if (!$this->shouldLockFile($absolutePath)) {
  1869. return false;
  1870. }
  1871. $this->unlockPath($path, $type, $lockMountPoint);
  1872. $parents = $this->getParents($path);
  1873. foreach ($parents as $parent) {
  1874. $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
  1875. }
  1876. return true;
  1877. }
  1878. /**
  1879. * Only lock files in data/user/files/
  1880. *
  1881. * @param string $path Absolute path to the file/folder we try to (un)lock
  1882. * @return bool
  1883. */
  1884. protected function shouldLockFile($path) {
  1885. $path = Filesystem::normalizePath($path);
  1886. $pathSegments = explode('/', $path);
  1887. if (isset($pathSegments[2])) {
  1888. // E.g.: /username/files/path-to-file
  1889. return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
  1890. }
  1891. return !str_starts_with($path, '/appdata_');
  1892. }
  1893. /**
  1894. * Shortens the given absolute path to be relative to
  1895. * "$user/files".
  1896. *
  1897. * @param string $absolutePath absolute path which is under "files"
  1898. *
  1899. * @return string path relative to "files" with trimmed slashes or null
  1900. * if the path was NOT relative to files
  1901. *
  1902. * @throws \InvalidArgumentException if the given path was not under "files"
  1903. * @since 8.1.0
  1904. */
  1905. public function getPathRelativeToFiles($absolutePath) {
  1906. $path = Filesystem::normalizePath($absolutePath);
  1907. $parts = explode('/', trim($path, '/'), 3);
  1908. // "$user", "files", "path/to/dir"
  1909. if (!isset($parts[1]) || $parts[1] !== 'files') {
  1910. $this->logger->error(
  1911. '$absolutePath must be relative to "files", value is "{absolutePath}"',
  1912. [
  1913. 'absolutePath' => $absolutePath,
  1914. ]
  1915. );
  1916. throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
  1917. }
  1918. if (isset($parts[2])) {
  1919. return $parts[2];
  1920. }
  1921. return '';
  1922. }
  1923. /**
  1924. * @param string $filename
  1925. * @return array
  1926. * @throws \OC\User\NoUserException
  1927. * @throws NotFoundException
  1928. */
  1929. public function getUidAndFilename($filename) {
  1930. $info = $this->getFileInfo($filename);
  1931. if (!$info instanceof \OCP\Files\FileInfo) {
  1932. throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
  1933. }
  1934. $uid = $info->getOwner()->getUID();
  1935. if ($uid != \OC_User::getUser()) {
  1936. Filesystem::initMountPoints($uid);
  1937. $ownerView = new View('/' . $uid . '/files');
  1938. try {
  1939. $filename = $ownerView->getPath($info['fileid']);
  1940. } catch (NotFoundException $e) {
  1941. throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
  1942. }
  1943. }
  1944. return [$uid, $filename];
  1945. }
  1946. /**
  1947. * Creates parent non-existing folders
  1948. *
  1949. * @param string $filePath
  1950. * @return bool
  1951. */
  1952. private function createParentDirectories($filePath) {
  1953. $directoryParts = explode('/', $filePath);
  1954. $directoryParts = array_filter($directoryParts);
  1955. foreach ($directoryParts as $key => $part) {
  1956. $currentPathElements = array_slice($directoryParts, 0, $key);
  1957. $currentPath = '/' . implode('/', $currentPathElements);
  1958. if ($this->is_file($currentPath)) {
  1959. return false;
  1960. }
  1961. if (!$this->file_exists($currentPath)) {
  1962. $this->mkdir($currentPath);
  1963. }
  1964. }
  1965. return true;
  1966. }
  1967. }