view.php 61 KB

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