View.php 62 KB

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