View.php 64 KB

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