View.php 66 KB

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