View.php 65 KB

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