View.php 65 KB

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