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

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