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

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