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 64KB

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