View.php 64 KB

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