View.php 63 KB

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