View.php 66 KB

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