You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

View.php 65KB

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