View.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163
  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. // For S3 we could actually get the file info here already
  1632. // $storage->getCache()->get($internalPath);
  1633. $mount = $this->getMount($path);
  1634. $storage = $mount->getStorage();
  1635. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  1636. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1637. return new FileInfo(
  1638. $this->getAbsolutePath($path),
  1639. $storage,
  1640. $internalPath,
  1641. [
  1642. 'fileid' => null,
  1643. 'mimetype' => $storage->getMimeType($internalPath),
  1644. 'name' => basename($path),
  1645. 'etag' => null,
  1646. 'size' => $storage->filesize($internalPath),
  1647. 'mtime' => $storage->filemtime($internalPath),
  1648. 'encrypted' => false,
  1649. 'permissions' => \OCP\Constants::PERMISSION_ALL
  1650. ],
  1651. $mount,
  1652. $owner
  1653. );
  1654. }
  1655. /**
  1656. * @param string $path
  1657. * @param string $fileName
  1658. * @throws InvalidPathException
  1659. */
  1660. public function verifyPath($path, $fileName): void {
  1661. try {
  1662. /** @type \OCP\Files\Storage $storage */
  1663. [$storage, $internalPath] = $this->resolvePath($path);
  1664. $storage->verifyPath($internalPath, $fileName);
  1665. } catch (ReservedWordException $ex) {
  1666. $l = \OCP\Util::getL10N('lib');
  1667. throw new InvalidPathException($l->t('File name is a reserved word'));
  1668. } catch (InvalidCharacterInPathException $ex) {
  1669. $l = \OCP\Util::getL10N('lib');
  1670. throw new InvalidPathException($l->t('File name contains at least one invalid character'));
  1671. } catch (FileNameTooLongException $ex) {
  1672. $l = \OCP\Util::getL10N('lib');
  1673. throw new InvalidPathException($l->t('File name is too long'));
  1674. } catch (InvalidDirectoryException $ex) {
  1675. $l = \OCP\Util::getL10N('lib');
  1676. throw new InvalidPathException($l->t('Dot files are not allowed'));
  1677. } catch (EmptyFileNameException $ex) {
  1678. $l = \OCP\Util::getL10N('lib');
  1679. throw new InvalidPathException($l->t('Empty filename is not allowed'));
  1680. }
  1681. }
  1682. /**
  1683. * get all parent folders of $path
  1684. *
  1685. * @param string $path
  1686. * @return string[]
  1687. */
  1688. private function getParents($path) {
  1689. $path = trim($path, '/');
  1690. if (!$path) {
  1691. return [];
  1692. }
  1693. $parts = explode('/', $path);
  1694. // remove the single file
  1695. array_pop($parts);
  1696. $result = ['/'];
  1697. $resultPath = '';
  1698. foreach ($parts as $part) {
  1699. if ($part) {
  1700. $resultPath .= '/' . $part;
  1701. $result[] = $resultPath;
  1702. }
  1703. }
  1704. return $result;
  1705. }
  1706. /**
  1707. * Returns the mount point for which to lock
  1708. *
  1709. * @param string $absolutePath absolute path
  1710. * @param bool $useParentMount true to return parent mount instead of whatever
  1711. * is mounted directly on the given path, false otherwise
  1712. * @return IMountPoint mount point for which to apply locks
  1713. */
  1714. private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
  1715. $mount = Filesystem::getMountManager()->find($absolutePath);
  1716. if ($useParentMount) {
  1717. // find out if something is mounted directly on the path
  1718. $internalPath = $mount->getInternalPath($absolutePath);
  1719. if ($internalPath === '') {
  1720. // resolve the parent mount instead
  1721. $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
  1722. }
  1723. }
  1724. return $mount;
  1725. }
  1726. /**
  1727. * Lock the given path
  1728. *
  1729. * @param string $path the path of the file to lock, relative to the view
  1730. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1731. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1732. *
  1733. * @return bool False if the path is excluded from locking, true otherwise
  1734. * @throws LockedException if the path is already locked
  1735. */
  1736. private function lockPath($path, $type, $lockMountPoint = false) {
  1737. $absolutePath = $this->getAbsolutePath($path);
  1738. $absolutePath = Filesystem::normalizePath($absolutePath);
  1739. if (!$this->shouldLockFile($absolutePath)) {
  1740. return false;
  1741. }
  1742. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1743. try {
  1744. $storage = $mount->getStorage();
  1745. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1746. $storage->acquireLock(
  1747. $mount->getInternalPath($absolutePath),
  1748. $type,
  1749. $this->lockingProvider
  1750. );
  1751. }
  1752. } catch (LockedException $e) {
  1753. // rethrow with the a human-readable path
  1754. throw new LockedException(
  1755. $this->getPathRelativeToFiles($absolutePath),
  1756. $e,
  1757. $e->getExistingLock()
  1758. );
  1759. }
  1760. return true;
  1761. }
  1762. /**
  1763. * Change the lock type
  1764. *
  1765. * @param string $path the path of the file to lock, relative to the view
  1766. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1767. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1768. *
  1769. * @return bool False if the path is excluded from locking, true otherwise
  1770. * @throws LockedException if the path is already locked
  1771. */
  1772. public function changeLock($path, $type, $lockMountPoint = false) {
  1773. $path = Filesystem::normalizePath($path);
  1774. $absolutePath = $this->getAbsolutePath($path);
  1775. $absolutePath = Filesystem::normalizePath($absolutePath);
  1776. if (!$this->shouldLockFile($absolutePath)) {
  1777. return false;
  1778. }
  1779. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1780. try {
  1781. $storage = $mount->getStorage();
  1782. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1783. $storage->changeLock(
  1784. $mount->getInternalPath($absolutePath),
  1785. $type,
  1786. $this->lockingProvider
  1787. );
  1788. }
  1789. } catch (LockedException $e) {
  1790. try {
  1791. // rethrow with the a human-readable path
  1792. throw new LockedException(
  1793. $this->getPathRelativeToFiles($absolutePath),
  1794. $e,
  1795. $e->getExistingLock()
  1796. );
  1797. } catch (\InvalidArgumentException $ex) {
  1798. throw new LockedException(
  1799. $absolutePath,
  1800. $ex,
  1801. $e->getExistingLock()
  1802. );
  1803. }
  1804. }
  1805. return true;
  1806. }
  1807. /**
  1808. * Unlock the given path
  1809. *
  1810. * @param string $path the path of the file to unlock, relative to the view
  1811. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1812. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1813. *
  1814. * @return bool False if the path is excluded from locking, true otherwise
  1815. * @throws LockedException
  1816. */
  1817. private function unlockPath($path, $type, $lockMountPoint = false) {
  1818. $absolutePath = $this->getAbsolutePath($path);
  1819. $absolutePath = Filesystem::normalizePath($absolutePath);
  1820. if (!$this->shouldLockFile($absolutePath)) {
  1821. return false;
  1822. }
  1823. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1824. $storage = $mount->getStorage();
  1825. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1826. $storage->releaseLock(
  1827. $mount->getInternalPath($absolutePath),
  1828. $type,
  1829. $this->lockingProvider
  1830. );
  1831. }
  1832. return true;
  1833. }
  1834. /**
  1835. * Lock a path and all its parents up to the root of the view
  1836. *
  1837. * @param string $path the path of the file to lock relative to the view
  1838. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1839. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1840. *
  1841. * @return bool False if the path is excluded from locking, true otherwise
  1842. * @throws LockedException
  1843. */
  1844. public function lockFile($path, $type, $lockMountPoint = false) {
  1845. $absolutePath = $this->getAbsolutePath($path);
  1846. $absolutePath = Filesystem::normalizePath($absolutePath);
  1847. if (!$this->shouldLockFile($absolutePath)) {
  1848. return false;
  1849. }
  1850. $this->lockPath($path, $type, $lockMountPoint);
  1851. $parents = $this->getParents($path);
  1852. foreach ($parents as $parent) {
  1853. $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
  1854. }
  1855. return true;
  1856. }
  1857. /**
  1858. * Unlock a path and all its parents up to the root of the view
  1859. *
  1860. * @param string $path the path of the file to lock relative to the view
  1861. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1862. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1863. *
  1864. * @return bool False if the path is excluded from locking, true otherwise
  1865. * @throws LockedException
  1866. */
  1867. public function unlockFile($path, $type, $lockMountPoint = false) {
  1868. $absolutePath = $this->getAbsolutePath($path);
  1869. $absolutePath = Filesystem::normalizePath($absolutePath);
  1870. if (!$this->shouldLockFile($absolutePath)) {
  1871. return false;
  1872. }
  1873. $this->unlockPath($path, $type, $lockMountPoint);
  1874. $parents = $this->getParents($path);
  1875. foreach ($parents as $parent) {
  1876. $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
  1877. }
  1878. return true;
  1879. }
  1880. /**
  1881. * Only lock files in data/user/files/
  1882. *
  1883. * @param string $path Absolute path to the file/folder we try to (un)lock
  1884. * @return bool
  1885. */
  1886. protected function shouldLockFile($path) {
  1887. $path = Filesystem::normalizePath($path);
  1888. $pathSegments = explode('/', $path);
  1889. if (isset($pathSegments[2])) {
  1890. // E.g.: /username/files/path-to-file
  1891. return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
  1892. }
  1893. return !str_starts_with($path, '/appdata_');
  1894. }
  1895. /**
  1896. * Shortens the given absolute path to be relative to
  1897. * "$user/files".
  1898. *
  1899. * @param string $absolutePath absolute path which is under "files"
  1900. *
  1901. * @return string path relative to "files" with trimmed slashes or null
  1902. * if the path was NOT relative to files
  1903. *
  1904. * @throws \InvalidArgumentException if the given path was not under "files"
  1905. * @since 8.1.0
  1906. */
  1907. public function getPathRelativeToFiles($absolutePath) {
  1908. $path = Filesystem::normalizePath($absolutePath);
  1909. $parts = explode('/', trim($path, '/'), 3);
  1910. // "$user", "files", "path/to/dir"
  1911. if (!isset($parts[1]) || $parts[1] !== 'files') {
  1912. $this->logger->error(
  1913. '$absolutePath must be relative to "files", value is "{absolutePath}"',
  1914. [
  1915. 'absolutePath' => $absolutePath,
  1916. ]
  1917. );
  1918. throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
  1919. }
  1920. if (isset($parts[2])) {
  1921. return $parts[2];
  1922. }
  1923. return '';
  1924. }
  1925. /**
  1926. * @param string $filename
  1927. * @return array
  1928. * @throws \OC\User\NoUserException
  1929. * @throws NotFoundException
  1930. */
  1931. public function getUidAndFilename($filename) {
  1932. $info = $this->getFileInfo($filename);
  1933. if (!$info instanceof \OCP\Files\FileInfo) {
  1934. throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
  1935. }
  1936. $uid = $info->getOwner()->getUID();
  1937. if ($uid != \OC_User::getUser()) {
  1938. Filesystem::initMountPoints($uid);
  1939. $ownerView = new View('/' . $uid . '/files');
  1940. try {
  1941. $filename = $ownerView->getPath($info['fileid']);
  1942. } catch (NotFoundException $e) {
  1943. throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
  1944. }
  1945. }
  1946. return [$uid, $filename];
  1947. }
  1948. /**
  1949. * Creates parent non-existing folders
  1950. *
  1951. * @param string $filePath
  1952. * @return bool
  1953. */
  1954. private function createParentDirectories($filePath) {
  1955. $directoryParts = explode('/', $filePath);
  1956. $directoryParts = array_filter($directoryParts);
  1957. foreach ($directoryParts as $key => $part) {
  1958. $currentPathElements = array_slice($directoryParts, 0, $key);
  1959. $currentPath = '/' . implode('/', $currentPathElements);
  1960. if ($this->is_file($currentPath)) {
  1961. return false;
  1962. }
  1963. if (!$this->file_exists($currentPath)) {
  1964. $this->mkdir($currentPath);
  1965. }
  1966. }
  1967. return true;
  1968. }
  1969. }