View.php 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216
  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\Files\Storage\IStorage;
  69. use OCP\IUser;
  70. use OCP\Lock\ILockingProvider;
  71. use OCP\Lock\LockedException;
  72. use Psr\Log\LoggerInterface;
  73. /**
  74. * Class to provide access to ownCloud filesystem via a "view", and methods for
  75. * working with files within that view (e.g. read, write, delete, etc.). Each
  76. * view is restricted to a set of directories via a virtual root. The default view
  77. * uses the currently logged in user's data directory as root (parts of
  78. * OC_Filesystem are merely a wrapper for OC\Files\View).
  79. *
  80. * Apps that need to access files outside of the user data folders (to modify files
  81. * belonging to a user other than the one currently logged in, for example) should
  82. * use this class directly rather than using OC_Filesystem, or making use of PHP's
  83. * built-in file manipulation functions. This will ensure all hooks and proxies
  84. * are triggered correctly.
  85. *
  86. * Filesystem functions are not called directly; they are passed to the correct
  87. * \OC\Files\Storage\Storage object
  88. */
  89. class View {
  90. private string $fakeRoot = '';
  91. private ILockingProvider $lockingProvider;
  92. private bool $lockingEnabled;
  93. private bool $updaterEnabled = true;
  94. private UserManager $userManager;
  95. private LoggerInterface $logger;
  96. /**
  97. * @throws \Exception If $root contains an invalid path
  98. */
  99. public function __construct(string $root = '') {
  100. if (!Filesystem::isValidPath($root)) {
  101. throw new \Exception();
  102. }
  103. $this->fakeRoot = $root;
  104. $this->lockingProvider = \OC::$server->getLockingProvider();
  105. $this->lockingEnabled = !($this->lockingProvider instanceof \OC\Lock\NoopLockingProvider);
  106. $this->userManager = \OC::$server->getUserManager();
  107. $this->logger = \OC::$server->get(LoggerInterface::class);
  108. }
  109. /**
  110. * @param ?string $path
  111. * @psalm-template S as string|null
  112. * @psalm-param S $path
  113. * @psalm-return (S is string ? string : null)
  114. */
  115. public function getAbsolutePath($path = '/'): ?string {
  116. if ($path === null) {
  117. return null;
  118. }
  119. $this->assertPathLength($path);
  120. if ($path === '') {
  121. $path = '/';
  122. }
  123. if ($path[0] !== '/') {
  124. $path = '/' . $path;
  125. }
  126. return $this->fakeRoot . $path;
  127. }
  128. /**
  129. * Change the root to a fake root
  130. *
  131. * @param string $fakeRoot
  132. */
  133. public function chroot($fakeRoot): void {
  134. if (!$fakeRoot == '') {
  135. if ($fakeRoot[0] !== '/') {
  136. $fakeRoot = '/' . $fakeRoot;
  137. }
  138. }
  139. $this->fakeRoot = $fakeRoot;
  140. }
  141. /**
  142. * Get the fake root
  143. */
  144. public function getRoot(): string {
  145. return $this->fakeRoot;
  146. }
  147. /**
  148. * get path relative to the root of the view
  149. *
  150. * @param string $path
  151. */
  152. public function getRelativePath($path): ?string {
  153. $this->assertPathLength($path);
  154. if ($this->fakeRoot == '') {
  155. return $path;
  156. }
  157. if (rtrim($path, '/') === rtrim($this->fakeRoot, '/')) {
  158. return '/';
  159. }
  160. // missing slashes can cause wrong matches!
  161. $root = rtrim($this->fakeRoot, '/') . '/';
  162. if (!str_starts_with($path, $root)) {
  163. return null;
  164. } else {
  165. $path = substr($path, strlen($this->fakeRoot));
  166. if (strlen($path) === 0) {
  167. return '/';
  168. } else {
  169. return $path;
  170. }
  171. }
  172. }
  173. /**
  174. * Get the mountpoint of the storage object for a path
  175. * ( note: because a storage is not always mounted inside the fakeroot, the
  176. * returned mountpoint is relative to the absolute root of the filesystem
  177. * and does not take the chroot into account )
  178. *
  179. * @param string $path
  180. */
  181. public function getMountPoint($path): string {
  182. return Filesystem::getMountPoint($this->getAbsolutePath($path));
  183. }
  184. /**
  185. * Get the mountpoint of the storage object for a path
  186. * ( note: because a storage is not always mounted inside the fakeroot, the
  187. * returned mountpoint is relative to the absolute root of the filesystem
  188. * and does not take the chroot into account )
  189. *
  190. * @param string $path
  191. */
  192. public function getMount($path): IMountPoint {
  193. return Filesystem::getMountManager()->find($this->getAbsolutePath($path));
  194. }
  195. /**
  196. * Resolve a path to a storage and internal path
  197. *
  198. * @param string $path
  199. * @return array{?\OCP\Files\Storage\IStorage, string} an array consisting of the storage and the internal path
  200. */
  201. public function resolvePath($path): array {
  202. $a = $this->getAbsolutePath($path);
  203. $p = Filesystem::normalizePath($a);
  204. return Filesystem::resolvePath($p);
  205. }
  206. /**
  207. * Return the path to a local version of the file
  208. * we need this because we can't know if a file is stored local or not from
  209. * outside the filestorage and for some purposes a local file is needed
  210. *
  211. * @param string $path
  212. */
  213. public function getLocalFile($path): string|false {
  214. $parent = substr($path, 0, strrpos($path, '/') ?: 0);
  215. $path = $this->getAbsolutePath($path);
  216. [$storage, $internalPath] = Filesystem::resolvePath($path);
  217. if (Filesystem::isValidPath($parent) && $storage) {
  218. return $storage->getLocalFile($internalPath);
  219. } else {
  220. return false;
  221. }
  222. }
  223. /**
  224. * the following functions operate with arguments and return values identical
  225. * to those of their PHP built-in equivalents. Mostly they are merely wrappers
  226. * for \OC\Files\Storage\Storage via basicOperation().
  227. */
  228. public function mkdir($path) {
  229. return $this->basicOperation('mkdir', $path, ['create', 'write']);
  230. }
  231. /**
  232. * remove mount point
  233. *
  234. * @param IMountPoint $mount
  235. * @param string $path relative to data/
  236. */
  237. protected function removeMount($mount, $path): bool {
  238. if ($mount instanceof MoveableMount) {
  239. // cut of /user/files to get the relative path to data/user/files
  240. $pathParts = explode('/', $path, 4);
  241. $relPath = '/' . $pathParts[3];
  242. $this->lockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  243. \OC_Hook::emit(
  244. Filesystem::CLASSNAME, "umount",
  245. [Filesystem::signal_param_path => $relPath]
  246. );
  247. $this->changeLock($relPath, ILockingProvider::LOCK_EXCLUSIVE, true);
  248. $result = $mount->removeMount();
  249. $this->changeLock($relPath, ILockingProvider::LOCK_SHARED, true);
  250. if ($result) {
  251. \OC_Hook::emit(
  252. Filesystem::CLASSNAME, "post_umount",
  253. [Filesystem::signal_param_path => $relPath]
  254. );
  255. }
  256. $this->unlockFile($relPath, ILockingProvider::LOCK_SHARED, true);
  257. return $result;
  258. } else {
  259. // do not allow deleting the storage's root / the mount point
  260. // because for some storages it might delete the whole contents
  261. // but isn't supposed to work that way
  262. return false;
  263. }
  264. }
  265. public function disableCacheUpdate(): void {
  266. $this->updaterEnabled = false;
  267. }
  268. public function enableCacheUpdate(): void {
  269. $this->updaterEnabled = true;
  270. }
  271. protected function writeUpdate(Storage $storage, string $internalPath, ?int $time = null, ?int $sizeDifference = null): void {
  272. if ($this->updaterEnabled) {
  273. if (is_null($time)) {
  274. $time = time();
  275. }
  276. $storage->getUpdater()->update($internalPath, $time, $sizeDifference);
  277. }
  278. }
  279. protected function removeUpdate(Storage $storage, string $internalPath): void {
  280. if ($this->updaterEnabled) {
  281. $storage->getUpdater()->remove($internalPath);
  282. }
  283. }
  284. protected function renameUpdate(Storage $sourceStorage, Storage $targetStorage, string $sourceInternalPath, string $targetInternalPath): void {
  285. if ($this->updaterEnabled) {
  286. $targetStorage->getUpdater()->renameFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  287. }
  288. }
  289. /**
  290. * @param string $path
  291. * @return bool|mixed
  292. */
  293. public function rmdir($path) {
  294. $absolutePath = $this->getAbsolutePath($path);
  295. $mount = Filesystem::getMountManager()->find($absolutePath);
  296. if ($mount->getInternalPath($absolutePath) === '') {
  297. return $this->removeMount($mount, $absolutePath);
  298. }
  299. if ($this->is_dir($path)) {
  300. $result = $this->basicOperation('rmdir', $path, ['delete']);
  301. } else {
  302. $result = false;
  303. }
  304. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  305. $storage = $mount->getStorage();
  306. $internalPath = $mount->getInternalPath($absolutePath);
  307. $storage->getUpdater()->remove($internalPath);
  308. }
  309. return $result;
  310. }
  311. /**
  312. * @param string $path
  313. * @return resource|false
  314. */
  315. public function opendir($path) {
  316. return $this->basicOperation('opendir', $path, ['read']);
  317. }
  318. /**
  319. * @param string $path
  320. * @return bool|mixed
  321. */
  322. public function is_dir($path) {
  323. if ($path == '/') {
  324. return true;
  325. }
  326. return $this->basicOperation('is_dir', $path);
  327. }
  328. /**
  329. * @param string $path
  330. * @return bool|mixed
  331. */
  332. public function is_file($path) {
  333. if ($path == '/') {
  334. return false;
  335. }
  336. return $this->basicOperation('is_file', $path);
  337. }
  338. /**
  339. * @param string $path
  340. * @return mixed
  341. */
  342. public function stat($path) {
  343. return $this->basicOperation('stat', $path);
  344. }
  345. /**
  346. * @param string $path
  347. * @return mixed
  348. */
  349. public function filetype($path) {
  350. return $this->basicOperation('filetype', $path);
  351. }
  352. /**
  353. * @param string $path
  354. * @return mixed
  355. */
  356. public function filesize(string $path) {
  357. return $this->basicOperation('filesize', $path);
  358. }
  359. /**
  360. * @param string $path
  361. * @return bool|mixed
  362. * @throws InvalidPathException
  363. */
  364. public function readfile($path) {
  365. $this->assertPathLength($path);
  366. if (ob_get_level()) {
  367. ob_end_clean();
  368. }
  369. $handle = $this->fopen($path, 'rb');
  370. if ($handle) {
  371. $chunkSize = 524288; // 512 kiB chunks
  372. while (!feof($handle)) {
  373. echo fread($handle, $chunkSize);
  374. flush();
  375. $this->checkConnectionStatus();
  376. }
  377. fclose($handle);
  378. return $this->filesize($path);
  379. }
  380. return false;
  381. }
  382. /**
  383. * @param string $path
  384. * @param int $from
  385. * @param int $to
  386. * @return bool|mixed
  387. * @throws InvalidPathException
  388. * @throws \OCP\Files\UnseekableException
  389. */
  390. public function readfilePart($path, $from, $to) {
  391. $this->assertPathLength($path);
  392. if (ob_get_level()) {
  393. ob_end_clean();
  394. }
  395. $handle = $this->fopen($path, 'rb');
  396. if ($handle) {
  397. $chunkSize = 524288; // 512 kiB chunks
  398. $startReading = true;
  399. if ($from !== 0 && $from !== '0' && fseek($handle, $from) !== 0) {
  400. // forward file handle via chunked fread because fseek seem to have failed
  401. $end = $from + 1;
  402. while (!feof($handle) && ftell($handle) < $end && ftell($handle) !== $from) {
  403. $len = $from - ftell($handle);
  404. if ($len > $chunkSize) {
  405. $len = $chunkSize;
  406. }
  407. $result = fread($handle, $len);
  408. if ($result === false) {
  409. $startReading = false;
  410. break;
  411. }
  412. }
  413. }
  414. if ($startReading) {
  415. $end = $to + 1;
  416. while (!feof($handle) && ftell($handle) < $end) {
  417. $len = $end - ftell($handle);
  418. if ($len > $chunkSize) {
  419. $len = $chunkSize;
  420. }
  421. echo fread($handle, $len);
  422. flush();
  423. $this->checkConnectionStatus();
  424. }
  425. return ftell($handle) - $from;
  426. }
  427. throw new \OCP\Files\UnseekableException('fseek error');
  428. }
  429. return false;
  430. }
  431. private function checkConnectionStatus(): void {
  432. $connectionStatus = \connection_status();
  433. if ($connectionStatus !== CONNECTION_NORMAL) {
  434. throw new ConnectionLostException("Connection lost. Status: $connectionStatus");
  435. }
  436. }
  437. /**
  438. * @param string $path
  439. * @return mixed
  440. */
  441. public function isCreatable($path) {
  442. return $this->basicOperation('isCreatable', $path);
  443. }
  444. /**
  445. * @param string $path
  446. * @return mixed
  447. */
  448. public function isReadable($path) {
  449. return $this->basicOperation('isReadable', $path);
  450. }
  451. /**
  452. * @param string $path
  453. * @return mixed
  454. */
  455. public function isUpdatable($path) {
  456. return $this->basicOperation('isUpdatable', $path);
  457. }
  458. /**
  459. * @param string $path
  460. * @return bool|mixed
  461. */
  462. public function isDeletable($path) {
  463. $absolutePath = $this->getAbsolutePath($path);
  464. $mount = Filesystem::getMountManager()->find($absolutePath);
  465. if ($mount->getInternalPath($absolutePath) === '') {
  466. return $mount instanceof MoveableMount;
  467. }
  468. return $this->basicOperation('isDeletable', $path);
  469. }
  470. /**
  471. * @param string $path
  472. * @return mixed
  473. */
  474. public function isSharable($path) {
  475. return $this->basicOperation('isSharable', $path);
  476. }
  477. /**
  478. * @param string $path
  479. * @return bool|mixed
  480. */
  481. public function file_exists($path) {
  482. if ($path == '/') {
  483. return true;
  484. }
  485. return $this->basicOperation('file_exists', $path);
  486. }
  487. /**
  488. * @param string $path
  489. * @return mixed
  490. */
  491. public function filemtime($path) {
  492. return $this->basicOperation('filemtime', $path);
  493. }
  494. /**
  495. * @param string $path
  496. * @param int|string $mtime
  497. */
  498. public function touch($path, $mtime = null): bool {
  499. if (!is_null($mtime) && !is_numeric($mtime)) {
  500. $mtime = strtotime($mtime);
  501. }
  502. $hooks = ['touch'];
  503. if (!$this->file_exists($path)) {
  504. $hooks[] = 'create';
  505. $hooks[] = 'write';
  506. }
  507. try {
  508. $result = $this->basicOperation('touch', $path, $hooks, $mtime);
  509. } catch (\Exception $e) {
  510. $this->logger->info('Error while setting modified time', ['app' => 'core', 'exception' => $e]);
  511. $result = false;
  512. }
  513. if (!$result) {
  514. // If create file fails because of permissions on external storage like SMB folders,
  515. // check file exists and return false if not.
  516. if (!$this->file_exists($path)) {
  517. return false;
  518. }
  519. if (is_null($mtime)) {
  520. $mtime = time();
  521. }
  522. //if native touch fails, we emulate it by changing the mtime in the cache
  523. $this->putFileInfo($path, ['mtime' => floor($mtime)]);
  524. }
  525. return true;
  526. }
  527. /**
  528. * @param string $path
  529. * @return string|false
  530. * @throws LockedException
  531. */
  532. public function file_get_contents($path) {
  533. return $this->basicOperation('file_get_contents', $path, ['read']);
  534. }
  535. protected function emit_file_hooks_pre(bool $exists, string $path, bool &$run): void {
  536. if (!$exists) {
  537. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [
  538. Filesystem::signal_param_path => $this->getHookPath($path),
  539. Filesystem::signal_param_run => &$run,
  540. ]);
  541. } else {
  542. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [
  543. Filesystem::signal_param_path => $this->getHookPath($path),
  544. Filesystem::signal_param_run => &$run,
  545. ]);
  546. }
  547. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [
  548. Filesystem::signal_param_path => $this->getHookPath($path),
  549. Filesystem::signal_param_run => &$run,
  550. ]);
  551. }
  552. protected function emit_file_hooks_post(bool $exists, string $path): void {
  553. if (!$exists) {
  554. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [
  555. Filesystem::signal_param_path => $this->getHookPath($path),
  556. ]);
  557. } else {
  558. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [
  559. Filesystem::signal_param_path => $this->getHookPath($path),
  560. ]);
  561. }
  562. \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [
  563. Filesystem::signal_param_path => $this->getHookPath($path),
  564. ]);
  565. }
  566. /**
  567. * @param string $path
  568. * @param string|resource $data
  569. * @return bool|mixed
  570. * @throws LockedException
  571. */
  572. public function file_put_contents($path, $data) {
  573. if (is_resource($data)) { //not having to deal with streams in file_put_contents makes life easier
  574. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  575. if (Filesystem::isValidPath($path)
  576. && !Filesystem::isFileBlacklisted($path)
  577. ) {
  578. $path = $this->getRelativePath($absolutePath);
  579. if ($path === null) {
  580. throw new InvalidPathException("Path $absolutePath is not in the expected root");
  581. }
  582. $this->lockFile($path, ILockingProvider::LOCK_SHARED);
  583. $exists = $this->file_exists($path);
  584. $run = true;
  585. if ($this->shouldEmitHooks($path)) {
  586. $this->emit_file_hooks_pre($exists, $path, $run);
  587. }
  588. if (!$run) {
  589. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  590. return false;
  591. }
  592. try {
  593. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  594. } catch (\Exception $e) {
  595. // Release the shared lock before throwing.
  596. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  597. throw $e;
  598. }
  599. /** @var Storage $storage */
  600. [$storage, $internalPath] = $this->resolvePath($path);
  601. $target = $storage->fopen($internalPath, 'w');
  602. if ($target) {
  603. [, $result] = \OC_Helper::streamCopy($data, $target);
  604. fclose($target);
  605. fclose($data);
  606. $this->writeUpdate($storage, $internalPath);
  607. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  608. if ($this->shouldEmitHooks($path) && $result !== false) {
  609. $this->emit_file_hooks_post($exists, $path);
  610. }
  611. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  612. return $result;
  613. } else {
  614. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  615. return false;
  616. }
  617. } else {
  618. return false;
  619. }
  620. } else {
  621. $hooks = $this->file_exists($path) ? ['update', 'write'] : ['create', 'write'];
  622. return $this->basicOperation('file_put_contents', $path, $hooks, $data);
  623. }
  624. }
  625. /**
  626. * @param string $path
  627. * @return bool|mixed
  628. */
  629. public function unlink($path) {
  630. if ($path === '' || $path === '/') {
  631. // do not allow deleting the root
  632. return false;
  633. }
  634. $postFix = (substr($path, -1) === '/') ? '/' : '';
  635. $absolutePath = Filesystem::normalizePath($this->getAbsolutePath($path));
  636. $mount = Filesystem::getMountManager()->find($absolutePath . $postFix);
  637. if ($mount->getInternalPath($absolutePath) === '') {
  638. return $this->removeMount($mount, $absolutePath);
  639. }
  640. if ($this->is_dir($path)) {
  641. $result = $this->basicOperation('rmdir', $path, ['delete']);
  642. } else {
  643. $result = $this->basicOperation('unlink', $path, ['delete']);
  644. }
  645. if (!$result && !$this->file_exists($path)) { //clear ghost files from the cache on delete
  646. $storage = $mount->getStorage();
  647. $internalPath = $mount->getInternalPath($absolutePath);
  648. $storage->getUpdater()->remove($internalPath);
  649. return true;
  650. } else {
  651. return $result;
  652. }
  653. }
  654. /**
  655. * @param string $directory
  656. * @return bool|mixed
  657. */
  658. public function deleteAll($directory) {
  659. return $this->rmdir($directory);
  660. }
  661. /**
  662. * Rename/move a file or folder from the source path to target path.
  663. *
  664. * @param string $source source path
  665. * @param string $target target path
  666. *
  667. * @return bool|mixed
  668. * @throws LockedException
  669. */
  670. public function rename($source, $target) {
  671. $absolutePath1 = Filesystem::normalizePath($this->getAbsolutePath($source));
  672. $absolutePath2 = Filesystem::normalizePath($this->getAbsolutePath($target));
  673. if (str_starts_with($absolutePath2, $absolutePath1 . '/')) {
  674. throw new ForbiddenException("Moving a folder into a child folder is forbidden", false);
  675. }
  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($storage2, $internalPath2)) {
  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. $relativePath = $path;
  1261. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1262. $mount = Filesystem::getMountManager()->find($path);
  1263. $storage = $mount->getStorage();
  1264. $internalPath = $mount->getInternalPath($path);
  1265. if ($storage) {
  1266. $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
  1267. if (!$data instanceof ICacheEntry) {
  1268. if (Cache\Scanner::isPartialFile($relativePath)) {
  1269. return $this->getPartFileInfo($relativePath);
  1270. }
  1271. return false;
  1272. }
  1273. if ($mount instanceof MoveableMount && $internalPath === '') {
  1274. $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
  1275. }
  1276. if ($internalPath === '' && $data['name']) {
  1277. $data['name'] = basename($path);
  1278. }
  1279. $ownerId = $storage->getOwner($internalPath);
  1280. $owner = null;
  1281. if ($ownerId !== null && $ownerId !== false) {
  1282. // ownerId might be null if files are accessed with an access token without file system access
  1283. $owner = $this->getUserObjectForOwner($ownerId);
  1284. }
  1285. $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
  1286. if (isset($data['fileid'])) {
  1287. if ($includeMountPoints && $data['mimetype'] === 'httpd/unix-directory') {
  1288. //add the sizes of other mount points to the folder
  1289. $extOnly = ($includeMountPoints === 'ext');
  1290. $this->addSubMounts($info, $extOnly);
  1291. }
  1292. }
  1293. return $info;
  1294. } else {
  1295. $this->logger->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint(), ['app' => 'core']);
  1296. }
  1297. return false;
  1298. }
  1299. /**
  1300. * Extend a FileInfo that was previously requested with `$includeMountPoints = false` to include the sub mounts
  1301. */
  1302. public function addSubMounts(FileInfo $info, $extOnly = false): void {
  1303. $mounts = Filesystem::getMountManager()->findIn($info->getPath());
  1304. $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
  1305. $subStorage = $mount->getStorage();
  1306. return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
  1307. }));
  1308. }
  1309. /**
  1310. * get the content of a directory
  1311. *
  1312. * @param string $directory path under datadirectory
  1313. * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  1314. * @return FileInfo[]
  1315. */
  1316. public function getDirectoryContent($directory, $mimetype_filter = '', \OCP\Files\FileInfo $directoryInfo = null) {
  1317. $this->assertPathLength($directory);
  1318. if (!Filesystem::isValidPath($directory)) {
  1319. return [];
  1320. }
  1321. $path = $this->getAbsolutePath($directory);
  1322. $path = Filesystem::normalizePath($path);
  1323. $mount = $this->getMount($directory);
  1324. $storage = $mount->getStorage();
  1325. $internalPath = $mount->getInternalPath($path);
  1326. if (!$storage) {
  1327. return [];
  1328. }
  1329. $cache = $storage->getCache($internalPath);
  1330. $user = \OC_User::getUser();
  1331. if (!$directoryInfo) {
  1332. $data = $this->getCacheEntry($storage, $internalPath, $directory);
  1333. if (!$data instanceof ICacheEntry || !isset($data['fileid'])) {
  1334. return [];
  1335. }
  1336. } else {
  1337. $data = $directoryInfo;
  1338. }
  1339. if (!($data->getPermissions() & Constants::PERMISSION_READ)) {
  1340. return [];
  1341. }
  1342. $folderId = $data->getId();
  1343. $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
  1344. $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
  1345. $fileNames = array_map(function (ICacheEntry $content) {
  1346. return $content->getName();
  1347. }, $contents);
  1348. /**
  1349. * @var \OC\Files\FileInfo[] $fileInfos
  1350. */
  1351. $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
  1352. if ($sharingDisabled) {
  1353. $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1354. }
  1355. $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
  1356. return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
  1357. }, $contents);
  1358. $files = array_combine($fileNames, $fileInfos);
  1359. //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
  1360. $mounts = Filesystem::getMountManager()->findIn($path);
  1361. // make sure nested mounts are sorted after their parent mounts
  1362. // otherwise doesn't propagate the etag across storage boundaries correctly
  1363. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1364. return $a->getMountPoint() <=> $b->getMountPoint();
  1365. });
  1366. $dirLength = strlen($path);
  1367. foreach ($mounts as $mount) {
  1368. $mountPoint = $mount->getMountPoint();
  1369. $subStorage = $mount->getStorage();
  1370. if ($subStorage) {
  1371. $subCache = $subStorage->getCache('');
  1372. $rootEntry = $subCache->get('');
  1373. if (!$rootEntry) {
  1374. $subScanner = $subStorage->getScanner();
  1375. try {
  1376. $subScanner->scanFile('');
  1377. } catch (\OCP\Files\StorageNotAvailableException $e) {
  1378. continue;
  1379. } catch (\OCP\Files\StorageInvalidException $e) {
  1380. continue;
  1381. } catch (\Exception $e) {
  1382. // sometimes when the storage is not available it can be any exception
  1383. $this->logger->error('Exception while scanning storage "' . $subStorage->getId() . '"', [
  1384. 'exception' => $e,
  1385. 'app' => 'core',
  1386. ]);
  1387. continue;
  1388. }
  1389. $rootEntry = $subCache->get('');
  1390. }
  1391. if ($rootEntry && ($rootEntry->getPermissions() & Constants::PERMISSION_READ)) {
  1392. $relativePath = trim(substr($mountPoint, $dirLength), '/');
  1393. if ($pos = strpos($relativePath, '/')) {
  1394. //mountpoint inside subfolder add size to the correct folder
  1395. $entryName = substr($relativePath, 0, $pos);
  1396. // Create parent folders if the mountpoint is inside a subfolder that doesn't exist yet
  1397. if (!isset($files[$entryName])) {
  1398. try {
  1399. if ($this->mkdir($path . '/' . $entryName) !== false) {
  1400. $info = $this->getFileInfo($path . '/' . $entryName);
  1401. if ($info !== false) {
  1402. $files[$entryName] = $info;
  1403. }
  1404. }
  1405. } catch (\Exception $e) {
  1406. // Creating the parent folder might not be possible, for example due to a lack of permissions.
  1407. $this->logger->debug('Failed to create non-existent parent', ['exception' => $e, 'path' => $path . '/' . $entryName]);
  1408. }
  1409. }
  1410. if (isset($files[$entryName])) {
  1411. $files[$entryName]->addSubEntry($rootEntry, $mountPoint);
  1412. }
  1413. } else { //mountpoint in this folder, add an entry for it
  1414. $rootEntry['name'] = $relativePath;
  1415. $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
  1416. $permissions = $rootEntry['permissions'];
  1417. // do not allow renaming/deleting the mount point if they are not shared files/folders
  1418. // for shared files/folders we use the permissions given by the owner
  1419. if ($mount instanceof MoveableMount) {
  1420. $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
  1421. } else {
  1422. $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
  1423. }
  1424. $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
  1425. // if sharing was disabled for the user we remove the share permissions
  1426. if ($sharingDisabled) {
  1427. $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1428. }
  1429. $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
  1430. $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
  1431. }
  1432. }
  1433. }
  1434. }
  1435. if ($mimetype_filter) {
  1436. $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
  1437. if (strpos($mimetype_filter, '/')) {
  1438. return $file->getMimetype() === $mimetype_filter;
  1439. } else {
  1440. return $file->getMimePart() === $mimetype_filter;
  1441. }
  1442. });
  1443. }
  1444. return array_values($files);
  1445. }
  1446. /**
  1447. * change file metadata
  1448. *
  1449. * @param string $path
  1450. * @param array|\OCP\Files\FileInfo $data
  1451. * @return int
  1452. *
  1453. * returns the fileid of the updated file
  1454. */
  1455. public function putFileInfo($path, $data) {
  1456. $this->assertPathLength($path);
  1457. if ($data instanceof FileInfo) {
  1458. $data = $data->getData();
  1459. }
  1460. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1461. /**
  1462. * @var Storage $storage
  1463. * @var string $internalPath
  1464. */
  1465. [$storage, $internalPath] = Filesystem::resolvePath($path);
  1466. if ($storage) {
  1467. $cache = $storage->getCache($path);
  1468. if (!$cache->inCache($internalPath)) {
  1469. $scanner = $storage->getScanner($internalPath);
  1470. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1471. }
  1472. return $cache->put($internalPath, $data);
  1473. } else {
  1474. return -1;
  1475. }
  1476. }
  1477. /**
  1478. * search for files with the name matching $query
  1479. *
  1480. * @param string $query
  1481. * @return FileInfo[]
  1482. */
  1483. public function search($query) {
  1484. return $this->searchCommon('search', ['%' . $query . '%']);
  1485. }
  1486. /**
  1487. * search for files with the name matching $query
  1488. *
  1489. * @param string $query
  1490. * @return FileInfo[]
  1491. */
  1492. public function searchRaw($query) {
  1493. return $this->searchCommon('search', [$query]);
  1494. }
  1495. /**
  1496. * search for files by mimetype
  1497. *
  1498. * @param string $mimetype
  1499. * @return FileInfo[]
  1500. */
  1501. public function searchByMime($mimetype) {
  1502. return $this->searchCommon('searchByMime', [$mimetype]);
  1503. }
  1504. /**
  1505. * search for files by tag
  1506. *
  1507. * @param string|int $tag name or tag id
  1508. * @param string $userId owner of the tags
  1509. * @return FileInfo[]
  1510. */
  1511. public function searchByTag($tag, $userId) {
  1512. return $this->searchCommon('searchByTag', [$tag, $userId]);
  1513. }
  1514. /**
  1515. * @param string $method cache method
  1516. * @param array $args
  1517. * @return FileInfo[]
  1518. */
  1519. private function searchCommon($method, $args) {
  1520. $files = [];
  1521. $rootLength = strlen($this->fakeRoot);
  1522. $mount = $this->getMount('');
  1523. $mountPoint = $mount->getMountPoint();
  1524. $storage = $mount->getStorage();
  1525. $userManager = \OC::$server->getUserManager();
  1526. if ($storage) {
  1527. $cache = $storage->getCache('');
  1528. $results = call_user_func_array([$cache, $method], $args);
  1529. foreach ($results as $result) {
  1530. if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
  1531. $internalPath = $result['path'];
  1532. $path = $mountPoint . $result['path'];
  1533. $result['path'] = substr($mountPoint . $result['path'], $rootLength);
  1534. $owner = $userManager->get($storage->getOwner($internalPath));
  1535. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1536. }
  1537. }
  1538. $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
  1539. foreach ($mounts as $mount) {
  1540. $mountPoint = $mount->getMountPoint();
  1541. $storage = $mount->getStorage();
  1542. if ($storage) {
  1543. $cache = $storage->getCache('');
  1544. $relativeMountPoint = substr($mountPoint, $rootLength);
  1545. $results = call_user_func_array([$cache, $method], $args);
  1546. if ($results) {
  1547. foreach ($results as $result) {
  1548. $internalPath = $result['path'];
  1549. $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
  1550. $path = rtrim($mountPoint . $internalPath, '/');
  1551. $owner = $userManager->get($storage->getOwner($internalPath));
  1552. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1553. }
  1554. }
  1555. }
  1556. }
  1557. }
  1558. return $files;
  1559. }
  1560. /**
  1561. * Get the owner for a file or folder
  1562. *
  1563. * @param string $path
  1564. * @return string the user id of the owner
  1565. * @throws NotFoundException
  1566. */
  1567. public function getOwner($path) {
  1568. $info = $this->getFileInfo($path);
  1569. if (!$info) {
  1570. throw new NotFoundException($path . ' not found while trying to get owner');
  1571. }
  1572. if ($info->getOwner() === null) {
  1573. throw new NotFoundException($path . ' has no owner');
  1574. }
  1575. return $info->getOwner()->getUID();
  1576. }
  1577. /**
  1578. * get the ETag for a file or folder
  1579. *
  1580. * @param string $path
  1581. * @return string|false
  1582. */
  1583. public function getETag($path) {
  1584. [$storage, $internalPath] = $this->resolvePath($path);
  1585. if ($storage) {
  1586. return $storage->getETag($internalPath);
  1587. } else {
  1588. return false;
  1589. }
  1590. }
  1591. /**
  1592. * Get the path of a file by id, relative to the view
  1593. *
  1594. * Note that the resulting path is not guaranteed to be unique for the id, multiple paths can point to the same file
  1595. *
  1596. * @param int $id
  1597. * @param int|null $storageId
  1598. * @return string
  1599. * @throws NotFoundException
  1600. */
  1601. public function getPath($id, int $storageId = null) {
  1602. $id = (int)$id;
  1603. $manager = Filesystem::getMountManager();
  1604. $mounts = $manager->findIn($this->fakeRoot);
  1605. $mounts[] = $manager->find($this->fakeRoot);
  1606. $mounts = array_filter($mounts);
  1607. // reverse the array, so we start with the storage this view is in
  1608. // which is the most likely to contain the file we're looking for
  1609. $mounts = array_reverse($mounts);
  1610. // put non-shared mounts in front of the shared mount
  1611. // this prevents unneeded recursion into shares
  1612. usort($mounts, function (IMountPoint $a, IMountPoint $b) {
  1613. return $a instanceof SharedMount && (!$b instanceof SharedMount) ? 1 : -1;
  1614. });
  1615. if (!is_null($storageId)) {
  1616. $mounts = array_filter($mounts, function (IMountPoint $mount) use ($storageId) {
  1617. return $mount->getNumericStorageId() === $storageId;
  1618. });
  1619. }
  1620. foreach ($mounts as $mount) {
  1621. /**
  1622. * @var \OC\Files\Mount\MountPoint $mount
  1623. */
  1624. if ($mount->getStorage()) {
  1625. $cache = $mount->getStorage()->getCache();
  1626. $internalPath = $cache->getPathById($id);
  1627. if (is_string($internalPath)) {
  1628. $fullPath = $mount->getMountPoint() . $internalPath;
  1629. if (!is_null($path = $this->getRelativePath($fullPath))) {
  1630. return $path;
  1631. }
  1632. }
  1633. }
  1634. }
  1635. throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
  1636. }
  1637. /**
  1638. * @param string $path
  1639. * @throws InvalidPathException
  1640. */
  1641. private function assertPathLength($path): void {
  1642. $maxLen = min(PHP_MAXPATHLEN, 4000);
  1643. // Check for the string length - performed using isset() instead of strlen()
  1644. // because isset() is about 5x-40x faster.
  1645. if (isset($path[$maxLen])) {
  1646. $pathLen = strlen($path);
  1647. throw new InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
  1648. }
  1649. }
  1650. /**
  1651. * check if it is allowed to move a mount point to a given target.
  1652. * It is not allowed to move a mount point into a different mount point or
  1653. * into an already shared folder
  1654. */
  1655. private function targetIsNotShared(IStorage $targetStorage, string $targetInternalPath): bool {
  1656. // note: cannot use the view because the target is already locked
  1657. $fileId = $targetStorage->getCache()->getId($targetInternalPath);
  1658. if ($fileId === -1) {
  1659. // target might not exist, need to check parent instead
  1660. $fileId = $targetStorage->getCache()->getId(dirname($targetInternalPath));
  1661. }
  1662. // check if any of the parents were shared by the current owner (include collections)
  1663. $shares = Share::getItemShared(
  1664. 'folder',
  1665. (string)$fileId,
  1666. \OC\Share\Constants::FORMAT_NONE,
  1667. null,
  1668. true
  1669. );
  1670. if (count($shares) > 0) {
  1671. $this->logger->debug(
  1672. 'It is not allowed to move one mount point into a shared folder',
  1673. ['app' => 'files']);
  1674. return false;
  1675. }
  1676. return true;
  1677. }
  1678. /**
  1679. * Get a fileinfo object for files that are ignored in the cache (part files)
  1680. */
  1681. private function getPartFileInfo(string $path): \OC\Files\FileInfo {
  1682. $mount = $this->getMount($path);
  1683. $storage = $mount->getStorage();
  1684. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  1685. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1686. return new FileInfo(
  1687. $this->getAbsolutePath($path),
  1688. $storage,
  1689. $internalPath,
  1690. [
  1691. 'fileid' => null,
  1692. 'mimetype' => $storage->getMimeType($internalPath),
  1693. 'name' => basename($path),
  1694. 'etag' => null,
  1695. 'size' => $storage->filesize($internalPath),
  1696. 'mtime' => $storage->filemtime($internalPath),
  1697. 'encrypted' => false,
  1698. 'permissions' => \OCP\Constants::PERMISSION_ALL
  1699. ],
  1700. $mount,
  1701. $owner
  1702. );
  1703. }
  1704. /**
  1705. * @param string $path
  1706. * @param string $fileName
  1707. * @throws InvalidPathException
  1708. */
  1709. public function verifyPath($path, $fileName): void {
  1710. try {
  1711. /** @type \OCP\Files\Storage $storage */
  1712. [$storage, $internalPath] = $this->resolvePath($path);
  1713. $storage->verifyPath($internalPath, $fileName);
  1714. } catch (ReservedWordException $ex) {
  1715. $l = \OC::$server->getL10N('lib');
  1716. throw new InvalidPathException($l->t('File name is a reserved word'));
  1717. } catch (InvalidCharacterInPathException $ex) {
  1718. $l = \OC::$server->getL10N('lib');
  1719. throw new InvalidPathException($l->t('File name contains at least one invalid character'));
  1720. } catch (FileNameTooLongException $ex) {
  1721. $l = \OC::$server->getL10N('lib');
  1722. throw new InvalidPathException($l->t('File name is too long'));
  1723. } catch (InvalidDirectoryException $ex) {
  1724. $l = \OC::$server->getL10N('lib');
  1725. throw new InvalidPathException($l->t('Dot files are not allowed'));
  1726. } catch (EmptyFileNameException $ex) {
  1727. $l = \OC::$server->getL10N('lib');
  1728. throw new InvalidPathException($l->t('Empty filename is not allowed'));
  1729. }
  1730. }
  1731. /**
  1732. * get all parent folders of $path
  1733. *
  1734. * @param string $path
  1735. * @return string[]
  1736. */
  1737. private function getParents($path) {
  1738. $path = trim($path, '/');
  1739. if (!$path) {
  1740. return [];
  1741. }
  1742. $parts = explode('/', $path);
  1743. // remove the single file
  1744. array_pop($parts);
  1745. $result = ['/'];
  1746. $resultPath = '';
  1747. foreach ($parts as $part) {
  1748. if ($part) {
  1749. $resultPath .= '/' . $part;
  1750. $result[] = $resultPath;
  1751. }
  1752. }
  1753. return $result;
  1754. }
  1755. /**
  1756. * Returns the mount point for which to lock
  1757. *
  1758. * @param string $absolutePath absolute path
  1759. * @param bool $useParentMount true to return parent mount instead of whatever
  1760. * is mounted directly on the given path, false otherwise
  1761. * @return IMountPoint mount point for which to apply locks
  1762. */
  1763. private function getMountForLock(string $absolutePath, bool $useParentMount = false): IMountPoint {
  1764. $mount = Filesystem::getMountManager()->find($absolutePath);
  1765. if ($useParentMount) {
  1766. // find out if something is mounted directly on the path
  1767. $internalPath = $mount->getInternalPath($absolutePath);
  1768. if ($internalPath === '') {
  1769. // resolve the parent mount instead
  1770. $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
  1771. }
  1772. }
  1773. return $mount;
  1774. }
  1775. /**
  1776. * Lock the given path
  1777. *
  1778. * @param string $path the path of the file to lock, relative to the view
  1779. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1780. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1781. *
  1782. * @return bool False if the path is excluded from locking, true otherwise
  1783. * @throws LockedException if the path is already locked
  1784. */
  1785. private function lockPath($path, $type, $lockMountPoint = false) {
  1786. $absolutePath = $this->getAbsolutePath($path);
  1787. $absolutePath = Filesystem::normalizePath($absolutePath);
  1788. if (!$this->shouldLockFile($absolutePath)) {
  1789. return false;
  1790. }
  1791. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1792. try {
  1793. $storage = $mount->getStorage();
  1794. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1795. $storage->acquireLock(
  1796. $mount->getInternalPath($absolutePath),
  1797. $type,
  1798. $this->lockingProvider
  1799. );
  1800. }
  1801. } catch (LockedException $e) {
  1802. // rethrow with the a human-readable path
  1803. throw new LockedException(
  1804. $this->getPathRelativeToFiles($absolutePath),
  1805. $e,
  1806. $e->getExistingLock()
  1807. );
  1808. }
  1809. return true;
  1810. }
  1811. /**
  1812. * Change the lock type
  1813. *
  1814. * @param string $path the path of the file to lock, relative to the view
  1815. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1816. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1817. *
  1818. * @return bool False if the path is excluded from locking, true otherwise
  1819. * @throws LockedException if the path is already locked
  1820. */
  1821. public function changeLock($path, $type, $lockMountPoint = false) {
  1822. $path = Filesystem::normalizePath($path);
  1823. $absolutePath = $this->getAbsolutePath($path);
  1824. $absolutePath = Filesystem::normalizePath($absolutePath);
  1825. if (!$this->shouldLockFile($absolutePath)) {
  1826. return false;
  1827. }
  1828. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1829. try {
  1830. $storage = $mount->getStorage();
  1831. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1832. $storage->changeLock(
  1833. $mount->getInternalPath($absolutePath),
  1834. $type,
  1835. $this->lockingProvider
  1836. );
  1837. }
  1838. } catch (LockedException $e) {
  1839. try {
  1840. // rethrow with the a human-readable path
  1841. throw new LockedException(
  1842. $this->getPathRelativeToFiles($absolutePath),
  1843. $e,
  1844. $e->getExistingLock()
  1845. );
  1846. } catch (\InvalidArgumentException $ex) {
  1847. throw new LockedException(
  1848. $absolutePath,
  1849. $ex,
  1850. $e->getExistingLock()
  1851. );
  1852. }
  1853. }
  1854. return true;
  1855. }
  1856. /**
  1857. * Unlock the given path
  1858. *
  1859. * @param string $path the path of the file to unlock, relative to the view
  1860. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1861. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1862. *
  1863. * @return bool False if the path is excluded from locking, true otherwise
  1864. * @throws LockedException
  1865. */
  1866. private function unlockPath($path, $type, $lockMountPoint = false) {
  1867. $absolutePath = $this->getAbsolutePath($path);
  1868. $absolutePath = Filesystem::normalizePath($absolutePath);
  1869. if (!$this->shouldLockFile($absolutePath)) {
  1870. return false;
  1871. }
  1872. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1873. $storage = $mount->getStorage();
  1874. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1875. $storage->releaseLock(
  1876. $mount->getInternalPath($absolutePath),
  1877. $type,
  1878. $this->lockingProvider
  1879. );
  1880. }
  1881. return true;
  1882. }
  1883. /**
  1884. * Lock a path and all its parents up to the root of the view
  1885. *
  1886. * @param string $path the path of the file to lock relative to the view
  1887. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1888. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1889. *
  1890. * @return bool False if the path is excluded from locking, true otherwise
  1891. * @throws LockedException
  1892. */
  1893. public function lockFile($path, $type, $lockMountPoint = false) {
  1894. $absolutePath = $this->getAbsolutePath($path);
  1895. $absolutePath = Filesystem::normalizePath($absolutePath);
  1896. if (!$this->shouldLockFile($absolutePath)) {
  1897. return false;
  1898. }
  1899. $this->lockPath($path, $type, $lockMountPoint);
  1900. $parents = $this->getParents($path);
  1901. foreach ($parents as $parent) {
  1902. $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
  1903. }
  1904. return true;
  1905. }
  1906. /**
  1907. * Unlock a path and all its parents up to the root of the view
  1908. *
  1909. * @param string $path the path of the file to lock relative to the view
  1910. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1911. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1912. *
  1913. * @return bool False if the path is excluded from locking, true otherwise
  1914. * @throws LockedException
  1915. */
  1916. public function unlockFile($path, $type, $lockMountPoint = false) {
  1917. $absolutePath = $this->getAbsolutePath($path);
  1918. $absolutePath = Filesystem::normalizePath($absolutePath);
  1919. if (!$this->shouldLockFile($absolutePath)) {
  1920. return false;
  1921. }
  1922. $this->unlockPath($path, $type, $lockMountPoint);
  1923. $parents = $this->getParents($path);
  1924. foreach ($parents as $parent) {
  1925. $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
  1926. }
  1927. return true;
  1928. }
  1929. /**
  1930. * Only lock files in data/user/files/
  1931. *
  1932. * @param string $path Absolute path to the file/folder we try to (un)lock
  1933. * @return bool
  1934. */
  1935. protected function shouldLockFile($path) {
  1936. $path = Filesystem::normalizePath($path);
  1937. $pathSegments = explode('/', $path);
  1938. if (isset($pathSegments[2])) {
  1939. // E.g.: /username/files/path-to-file
  1940. return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
  1941. }
  1942. return !str_starts_with($path, '/appdata_');
  1943. }
  1944. /**
  1945. * Shortens the given absolute path to be relative to
  1946. * "$user/files".
  1947. *
  1948. * @param string $absolutePath absolute path which is under "files"
  1949. *
  1950. * @return string path relative to "files" with trimmed slashes or null
  1951. * if the path was NOT relative to files
  1952. *
  1953. * @throws \InvalidArgumentException if the given path was not under "files"
  1954. * @since 8.1.0
  1955. */
  1956. public function getPathRelativeToFiles($absolutePath) {
  1957. $path = Filesystem::normalizePath($absolutePath);
  1958. $parts = explode('/', trim($path, '/'), 3);
  1959. // "$user", "files", "path/to/dir"
  1960. if (!isset($parts[1]) || $parts[1] !== 'files') {
  1961. $this->logger->error(
  1962. '$absolutePath must be relative to "files", value is "{absolutePath}"',
  1963. [
  1964. 'absolutePath' => $absolutePath,
  1965. ]
  1966. );
  1967. throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
  1968. }
  1969. if (isset($parts[2])) {
  1970. return $parts[2];
  1971. }
  1972. return '';
  1973. }
  1974. /**
  1975. * @param string $filename
  1976. * @return array
  1977. * @throws \OC\User\NoUserException
  1978. * @throws NotFoundException
  1979. */
  1980. public function getUidAndFilename($filename) {
  1981. $info = $this->getFileInfo($filename);
  1982. if (!$info instanceof \OCP\Files\FileInfo) {
  1983. throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
  1984. }
  1985. $uid = $info->getOwner()->getUID();
  1986. if ($uid != \OC_User::getUser()) {
  1987. Filesystem::initMountPoints($uid);
  1988. $ownerView = new View('/' . $uid . '/files');
  1989. try {
  1990. $filename = $ownerView->getPath($info['fileid']);
  1991. } catch (NotFoundException $e) {
  1992. throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
  1993. }
  1994. }
  1995. return [$uid, $filename];
  1996. }
  1997. /**
  1998. * Creates parent non-existing folders
  1999. *
  2000. * @param string $filePath
  2001. * @return bool
  2002. */
  2003. private function createParentDirectories($filePath) {
  2004. $directoryParts = explode('/', $filePath);
  2005. $directoryParts = array_filter($directoryParts);
  2006. foreach ($directoryParts as $key => $part) {
  2007. $currentPathElements = array_slice($directoryParts, 0, $key);
  2008. $currentPath = '/' . implode('/', $currentPathElements);
  2009. if ($this->is_file($currentPath)) {
  2010. return false;
  2011. }
  2012. if (!$this->file_exists($currentPath)) {
  2013. $this->mkdir($currentPath);
  2014. }
  2015. }
  2016. return true;
  2017. }
  2018. }