1
0

View.php 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  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. $this->changeLock($path, ILockingProvider::LOCK_EXCLUSIVE);
  1036. }
  1037. try {
  1038. if (!is_null($extraParam)) {
  1039. $result = $storage->$operation($internalPath, $extraParam);
  1040. } else {
  1041. $result = $storage->$operation($internalPath);
  1042. }
  1043. } catch (\Exception $e) {
  1044. if (in_array('write', $hooks) || in_array('delete', $hooks)) {
  1045. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1046. } else if (in_array('read', $hooks)) {
  1047. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1048. }
  1049. throw $e;
  1050. }
  1051. if ($result && in_array('delete', $hooks) and $result) {
  1052. $this->removeUpdate($storage, $internalPath);
  1053. }
  1054. if ($result && in_array('write', $hooks) and $operation !== 'fopen') {
  1055. $this->writeUpdate($storage, $internalPath);
  1056. }
  1057. if ($result && in_array('touch', $hooks)) {
  1058. $this->writeUpdate($storage, $internalPath, $extraParam);
  1059. }
  1060. if ((in_array('write', $hooks) || in_array('delete', $hooks)) && ($operation !== 'fopen' || $result === false)) {
  1061. $this->changeLock($path, ILockingProvider::LOCK_SHARED);
  1062. }
  1063. $unlockLater = false;
  1064. if ($this->lockingEnabled && $operation === 'fopen' && is_resource($result)) {
  1065. $unlockLater = true;
  1066. // make sure our unlocking callback will still be called if connection is aborted
  1067. ignore_user_abort(true);
  1068. $result = CallbackWrapper::wrap($result, null, null, function () use ($hooks, $path) {
  1069. if (in_array('write', $hooks)) {
  1070. $this->unlockFile($path, ILockingProvider::LOCK_EXCLUSIVE);
  1071. } else if (in_array('read', $hooks)) {
  1072. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1073. }
  1074. });
  1075. }
  1076. if ($this->shouldEmitHooks($path) && $result !== false) {
  1077. if ($operation != 'fopen') { //no post hooks for fopen, the file stream is still open
  1078. $this->runHooks($hooks, $path, true);
  1079. }
  1080. }
  1081. if (!$unlockLater
  1082. && (in_array('write', $hooks) || in_array('delete', $hooks) || in_array('read', $hooks))
  1083. ) {
  1084. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1085. }
  1086. return $result;
  1087. } else {
  1088. $this->unlockFile($path, ILockingProvider::LOCK_SHARED);
  1089. }
  1090. }
  1091. return null;
  1092. }
  1093. /**
  1094. * get the path relative to the default root for hook usage
  1095. *
  1096. * @param string $path
  1097. * @return string
  1098. */
  1099. private function getHookPath($path) {
  1100. if (!Filesystem::getView()) {
  1101. return $path;
  1102. }
  1103. return Filesystem::getView()->getRelativePath($this->getAbsolutePath($path));
  1104. }
  1105. private function shouldEmitHooks($path = '') {
  1106. if ($path && Cache\Scanner::isPartialFile($path)) {
  1107. return false;
  1108. }
  1109. if (!Filesystem::$loaded) {
  1110. return false;
  1111. }
  1112. $defaultRoot = Filesystem::getRoot();
  1113. if ($defaultRoot === null) {
  1114. return false;
  1115. }
  1116. if ($this->fakeRoot === $defaultRoot) {
  1117. return true;
  1118. }
  1119. $fullPath = $this->getAbsolutePath($path);
  1120. if ($fullPath === $defaultRoot) {
  1121. return true;
  1122. }
  1123. return (strlen($fullPath) > strlen($defaultRoot)) && (substr($fullPath, 0, strlen($defaultRoot) + 1) === $defaultRoot . '/');
  1124. }
  1125. /**
  1126. * @param string[] $hooks
  1127. * @param string $path
  1128. * @param bool $post
  1129. * @return bool
  1130. */
  1131. private function runHooks($hooks, $path, $post = false) {
  1132. $relativePath = $path;
  1133. $path = $this->getHookPath($path);
  1134. $prefix = $post ? 'post_' : '';
  1135. $run = true;
  1136. if ($this->shouldEmitHooks($relativePath)) {
  1137. foreach ($hooks as $hook) {
  1138. if ($hook != 'read') {
  1139. \OC_Hook::emit(
  1140. Filesystem::CLASSNAME,
  1141. $prefix . $hook,
  1142. array(
  1143. Filesystem::signal_param_run => &$run,
  1144. Filesystem::signal_param_path => $path
  1145. )
  1146. );
  1147. } elseif (!$post) {
  1148. \OC_Hook::emit(
  1149. Filesystem::CLASSNAME,
  1150. $prefix . $hook,
  1151. array(
  1152. Filesystem::signal_param_path => $path
  1153. )
  1154. );
  1155. }
  1156. }
  1157. }
  1158. return $run;
  1159. }
  1160. /**
  1161. * check if a file or folder has been updated since $time
  1162. *
  1163. * @param string $path
  1164. * @param int $time
  1165. * @return bool
  1166. */
  1167. public function hasUpdated($path, $time) {
  1168. return $this->basicOperation('hasUpdated', $path, array(), $time);
  1169. }
  1170. /**
  1171. * @param string $ownerId
  1172. * @return \OC\User\User
  1173. */
  1174. private function getUserObjectForOwner($ownerId) {
  1175. $owner = $this->userManager->get($ownerId);
  1176. if ($owner instanceof IUser) {
  1177. return $owner;
  1178. } else {
  1179. return new User($ownerId, null);
  1180. }
  1181. }
  1182. /**
  1183. * Get file info from cache
  1184. *
  1185. * If the file is not in cached it will be scanned
  1186. * If the file has changed on storage the cache will be updated
  1187. *
  1188. * @param \OC\Files\Storage\Storage $storage
  1189. * @param string $internalPath
  1190. * @param string $relativePath
  1191. * @return ICacheEntry|bool
  1192. */
  1193. private function getCacheEntry($storage, $internalPath, $relativePath) {
  1194. $cache = $storage->getCache($internalPath);
  1195. $data = $cache->get($internalPath);
  1196. $watcher = $storage->getWatcher($internalPath);
  1197. try {
  1198. // if the file is not in the cache or needs to be updated, trigger the scanner and reload the data
  1199. if (!$data || $data['size'] === -1) {
  1200. if (!$storage->file_exists($internalPath)) {
  1201. return false;
  1202. }
  1203. // don't need to get a lock here since the scanner does it's own locking
  1204. $scanner = $storage->getScanner($internalPath);
  1205. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1206. $data = $cache->get($internalPath);
  1207. } else if (!Cache\Scanner::isPartialFile($internalPath) && $watcher->needsUpdate($internalPath, $data)) {
  1208. $this->lockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1209. $watcher->update($internalPath, $data);
  1210. $storage->getPropagator()->propagateChange($internalPath, time());
  1211. $data = $cache->get($internalPath);
  1212. $this->unlockFile($relativePath, ILockingProvider::LOCK_SHARED);
  1213. }
  1214. } catch (LockedException $e) {
  1215. // if the file is locked we just use the old cache info
  1216. }
  1217. return $data;
  1218. }
  1219. /**
  1220. * get the filesystem info
  1221. *
  1222. * @param string $path
  1223. * @param boolean|string $includeMountPoints true to add mountpoint sizes,
  1224. * 'ext' to add only ext storage mount point sizes. Defaults to true.
  1225. * defaults to true
  1226. * @return \OC\Files\FileInfo|false False if file does not exist
  1227. */
  1228. public function getFileInfo($path, $includeMountPoints = true) {
  1229. $this->assertPathLength($path);
  1230. if (!Filesystem::isValidPath($path)) {
  1231. return false;
  1232. }
  1233. if (Cache\Scanner::isPartialFile($path)) {
  1234. return $this->getPartFileInfo($path);
  1235. }
  1236. $relativePath = $path;
  1237. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1238. $mount = Filesystem::getMountManager()->find($path);
  1239. if (!$mount) {
  1240. \OC::$server->getLogger()->warning('Mountpoint not found for path: ' . $path);
  1241. return false;
  1242. }
  1243. $storage = $mount->getStorage();
  1244. $internalPath = $mount->getInternalPath($path);
  1245. if ($storage) {
  1246. $data = $this->getCacheEntry($storage, $internalPath, $relativePath);
  1247. if (!$data instanceof ICacheEntry) {
  1248. \OC::$server->getLogger()->debug('No cache entry found for ' . $path . ' (storage: ' . $storage->getId() . ', internalPath: ' . $internalPath . ')');
  1249. return false;
  1250. }
  1251. if ($mount instanceof MoveableMount && $internalPath === '') {
  1252. $data['permissions'] |= \OCP\Constants::PERMISSION_DELETE;
  1253. }
  1254. $owner = $this->getUserObjectForOwner($storage->getOwner($internalPath));
  1255. $info = new FileInfo($path, $storage, $internalPath, $data, $mount, $owner);
  1256. if ($data and isset($data['fileid'])) {
  1257. if ($includeMountPoints and $data['mimetype'] === 'httpd/unix-directory') {
  1258. //add the sizes of other mount points to the folder
  1259. $extOnly = ($includeMountPoints === 'ext');
  1260. $mounts = Filesystem::getMountManager()->findIn($path);
  1261. $info->setSubMounts(array_filter($mounts, function (IMountPoint $mount) use ($extOnly) {
  1262. $subStorage = $mount->getStorage();
  1263. return !($extOnly && $subStorage instanceof \OCA\Files_Sharing\SharedStorage);
  1264. }));
  1265. }
  1266. }
  1267. return $info;
  1268. } else {
  1269. \OC::$server->getLogger()->warning('Storage not valid for mountpoint: ' . $mount->getMountPoint());
  1270. }
  1271. return false;
  1272. }
  1273. /**
  1274. * get the content of a directory
  1275. *
  1276. * @param string $directory path under datadirectory
  1277. * @param string $mimetype_filter limit returned content to this mimetype or mimepart
  1278. * @return FileInfo[]
  1279. */
  1280. public function getDirectoryContent($directory, $mimetype_filter = '') {
  1281. $this->assertPathLength($directory);
  1282. if (!Filesystem::isValidPath($directory)) {
  1283. return [];
  1284. }
  1285. $path = $this->getAbsolutePath($directory);
  1286. $path = Filesystem::normalizePath($path);
  1287. $mount = $this->getMount($directory);
  1288. if (!$mount) {
  1289. return [];
  1290. }
  1291. $storage = $mount->getStorage();
  1292. $internalPath = $mount->getInternalPath($path);
  1293. if ($storage) {
  1294. $cache = $storage->getCache($internalPath);
  1295. $user = \OC_User::getUser();
  1296. $data = $this->getCacheEntry($storage, $internalPath, $directory);
  1297. if (!$data instanceof ICacheEntry || !isset($data['fileid']) || !($data->getPermissions() && Constants::PERMISSION_READ)) {
  1298. return [];
  1299. }
  1300. $folderId = $data['fileid'];
  1301. $contents = $cache->getFolderContentsById($folderId); //TODO: mimetype_filter
  1302. $sharingDisabled = \OCP\Util::isSharingDisabledForUser();
  1303. $fileNames = array_map(function(ICacheEntry $content) {
  1304. return $content->getName();
  1305. }, $contents);
  1306. /**
  1307. * @var \OC\Files\FileInfo[] $fileInfos
  1308. */
  1309. $fileInfos = array_map(function (ICacheEntry $content) use ($path, $storage, $mount, $sharingDisabled) {
  1310. if ($sharingDisabled) {
  1311. $content['permissions'] = $content['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1312. }
  1313. $owner = $this->getUserObjectForOwner($storage->getOwner($content['path']));
  1314. return new FileInfo($path . '/' . $content['name'], $storage, $content['path'], $content, $mount, $owner);
  1315. }, $contents);
  1316. $files = array_combine($fileNames, $fileInfos);
  1317. //add a folder for any mountpoint in this directory and add the sizes of other mountpoints to the folders
  1318. $mounts = Filesystem::getMountManager()->findIn($path);
  1319. $dirLength = strlen($path);
  1320. foreach ($mounts as $mount) {
  1321. $mountPoint = $mount->getMountPoint();
  1322. $subStorage = $mount->getStorage();
  1323. if ($subStorage) {
  1324. $subCache = $subStorage->getCache('');
  1325. $rootEntry = $subCache->get('');
  1326. if (!$rootEntry) {
  1327. $subScanner = $subStorage->getScanner('');
  1328. try {
  1329. $subScanner->scanFile('');
  1330. } catch (\OCP\Files\StorageNotAvailableException $e) {
  1331. continue;
  1332. } catch (\OCP\Files\StorageInvalidException $e) {
  1333. continue;
  1334. } catch (\Exception $e) {
  1335. // sometimes when the storage is not available it can be any exception
  1336. \OC::$server->getLogger()->logException($e, [
  1337. 'message' => 'Exception while scanning storage "' . $subStorage->getId() . '"',
  1338. 'level' => ILogger::ERROR,
  1339. 'app' => 'lib',
  1340. ]);
  1341. continue;
  1342. }
  1343. $rootEntry = $subCache->get('');
  1344. }
  1345. if ($rootEntry && ($rootEntry->getPermissions() && Constants::PERMISSION_READ)) {
  1346. $relativePath = trim(substr($mountPoint, $dirLength), '/');
  1347. if ($pos = strpos($relativePath, '/')) {
  1348. //mountpoint inside subfolder add size to the correct folder
  1349. $entryName = substr($relativePath, 0, $pos);
  1350. foreach ($files as &$entry) {
  1351. if ($entry->getName() === $entryName) {
  1352. $entry->addSubEntry($rootEntry, $mountPoint);
  1353. }
  1354. }
  1355. } else { //mountpoint in this folder, add an entry for it
  1356. $rootEntry['name'] = $relativePath;
  1357. $rootEntry['type'] = $rootEntry['mimetype'] === 'httpd/unix-directory' ? 'dir' : 'file';
  1358. $permissions = $rootEntry['permissions'];
  1359. // do not allow renaming/deleting the mount point if they are not shared files/folders
  1360. // for shared files/folders we use the permissions given by the owner
  1361. if ($mount instanceof MoveableMount) {
  1362. $rootEntry['permissions'] = $permissions | \OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE;
  1363. } else {
  1364. $rootEntry['permissions'] = $permissions & (\OCP\Constants::PERMISSION_ALL - (\OCP\Constants::PERMISSION_UPDATE | \OCP\Constants::PERMISSION_DELETE));
  1365. }
  1366. $rootEntry['path'] = substr(Filesystem::normalizePath($path . '/' . $rootEntry['name']), strlen($user) + 2); // full path without /$user/
  1367. // if sharing was disabled for the user we remove the share permissions
  1368. if (\OCP\Util::isSharingDisabledForUser()) {
  1369. $rootEntry['permissions'] = $rootEntry['permissions'] & ~\OCP\Constants::PERMISSION_SHARE;
  1370. }
  1371. $owner = $this->getUserObjectForOwner($subStorage->getOwner(''));
  1372. $files[$rootEntry->getName()] = new FileInfo($path . '/' . $rootEntry['name'], $subStorage, '', $rootEntry, $mount, $owner);
  1373. }
  1374. }
  1375. }
  1376. }
  1377. if ($mimetype_filter) {
  1378. $files = array_filter($files, function (FileInfo $file) use ($mimetype_filter) {
  1379. if (strpos($mimetype_filter, '/')) {
  1380. return $file->getMimetype() === $mimetype_filter;
  1381. } else {
  1382. return $file->getMimePart() === $mimetype_filter;
  1383. }
  1384. });
  1385. }
  1386. return array_values($files);
  1387. } else {
  1388. return [];
  1389. }
  1390. }
  1391. /**
  1392. * change file metadata
  1393. *
  1394. * @param string $path
  1395. * @param array|\OCP\Files\FileInfo $data
  1396. * @return int
  1397. *
  1398. * returns the fileid of the updated file
  1399. */
  1400. public function putFileInfo($path, $data) {
  1401. $this->assertPathLength($path);
  1402. if ($data instanceof FileInfo) {
  1403. $data = $data->getData();
  1404. }
  1405. $path = Filesystem::normalizePath($this->fakeRoot . '/' . $path);
  1406. /**
  1407. * @var \OC\Files\Storage\Storage $storage
  1408. * @var string $internalPath
  1409. */
  1410. list($storage, $internalPath) = Filesystem::resolvePath($path);
  1411. if ($storage) {
  1412. $cache = $storage->getCache($path);
  1413. if (!$cache->inCache($internalPath)) {
  1414. $scanner = $storage->getScanner($internalPath);
  1415. $scanner->scan($internalPath, Cache\Scanner::SCAN_SHALLOW);
  1416. }
  1417. return $cache->put($internalPath, $data);
  1418. } else {
  1419. return -1;
  1420. }
  1421. }
  1422. /**
  1423. * search for files with the name matching $query
  1424. *
  1425. * @param string $query
  1426. * @return FileInfo[]
  1427. */
  1428. public function search($query) {
  1429. return $this->searchCommon('search', array('%' . $query . '%'));
  1430. }
  1431. /**
  1432. * search for files with the name matching $query
  1433. *
  1434. * @param string $query
  1435. * @return FileInfo[]
  1436. */
  1437. public function searchRaw($query) {
  1438. return $this->searchCommon('search', array($query));
  1439. }
  1440. /**
  1441. * search for files by mimetype
  1442. *
  1443. * @param string $mimetype
  1444. * @return FileInfo[]
  1445. */
  1446. public function searchByMime($mimetype) {
  1447. return $this->searchCommon('searchByMime', array($mimetype));
  1448. }
  1449. /**
  1450. * search for files by tag
  1451. *
  1452. * @param string|int $tag name or tag id
  1453. * @param string $userId owner of the tags
  1454. * @return FileInfo[]
  1455. */
  1456. public function searchByTag($tag, $userId) {
  1457. return $this->searchCommon('searchByTag', array($tag, $userId));
  1458. }
  1459. /**
  1460. * @param string $method cache method
  1461. * @param array $args
  1462. * @return FileInfo[]
  1463. */
  1464. private function searchCommon($method, $args) {
  1465. $files = array();
  1466. $rootLength = strlen($this->fakeRoot);
  1467. $mount = $this->getMount('');
  1468. $mountPoint = $mount->getMountPoint();
  1469. $storage = $mount->getStorage();
  1470. if ($storage) {
  1471. $cache = $storage->getCache('');
  1472. $results = call_user_func_array(array($cache, $method), $args);
  1473. foreach ($results as $result) {
  1474. if (substr($mountPoint . $result['path'], 0, $rootLength + 1) === $this->fakeRoot . '/') {
  1475. $internalPath = $result['path'];
  1476. $path = $mountPoint . $result['path'];
  1477. $result['path'] = substr($mountPoint . $result['path'], $rootLength);
  1478. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1479. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1480. }
  1481. }
  1482. $mounts = Filesystem::getMountManager()->findIn($this->fakeRoot);
  1483. foreach ($mounts as $mount) {
  1484. $mountPoint = $mount->getMountPoint();
  1485. $storage = $mount->getStorage();
  1486. if ($storage) {
  1487. $cache = $storage->getCache('');
  1488. $relativeMountPoint = substr($mountPoint, $rootLength);
  1489. $results = call_user_func_array(array($cache, $method), $args);
  1490. if ($results) {
  1491. foreach ($results as $result) {
  1492. $internalPath = $result['path'];
  1493. $result['path'] = rtrim($relativeMountPoint . $result['path'], '/');
  1494. $path = rtrim($mountPoint . $internalPath, '/');
  1495. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1496. $files[] = new FileInfo($path, $storage, $internalPath, $result, $mount, $owner);
  1497. }
  1498. }
  1499. }
  1500. }
  1501. }
  1502. return $files;
  1503. }
  1504. /**
  1505. * Get the owner for a file or folder
  1506. *
  1507. * @param string $path
  1508. * @return string the user id of the owner
  1509. * @throws NotFoundException
  1510. */
  1511. public function getOwner($path) {
  1512. $info = $this->getFileInfo($path);
  1513. if (!$info) {
  1514. throw new NotFoundException($path . ' not found while trying to get owner');
  1515. }
  1516. return $info->getOwner()->getUID();
  1517. }
  1518. /**
  1519. * get the ETag for a file or folder
  1520. *
  1521. * @param string $path
  1522. * @return string
  1523. */
  1524. public function getETag($path) {
  1525. /**
  1526. * @var Storage\Storage $storage
  1527. * @var string $internalPath
  1528. */
  1529. list($storage, $internalPath) = $this->resolvePath($path);
  1530. if ($storage) {
  1531. return $storage->getETag($internalPath);
  1532. } else {
  1533. return null;
  1534. }
  1535. }
  1536. /**
  1537. * Get the path of a file by id, relative to the view
  1538. *
  1539. * Note that the resulting path is not guarantied to be unique for the id, multiple paths can point to the same file
  1540. *
  1541. * @param int $id
  1542. * @throws NotFoundException
  1543. * @return string
  1544. */
  1545. public function getPath($id) {
  1546. $id = (int)$id;
  1547. $manager = Filesystem::getMountManager();
  1548. $mounts = $manager->findIn($this->fakeRoot);
  1549. $mounts[] = $manager->find($this->fakeRoot);
  1550. // reverse the array so we start with the storage this view is in
  1551. // which is the most likely to contain the file we're looking for
  1552. $mounts = array_reverse($mounts);
  1553. foreach ($mounts as $mount) {
  1554. /**
  1555. * @var \OC\Files\Mount\MountPoint $mount
  1556. */
  1557. if ($mount->getStorage()) {
  1558. $cache = $mount->getStorage()->getCache();
  1559. $internalPath = $cache->getPathById($id);
  1560. if (is_string($internalPath)) {
  1561. $fullPath = $mount->getMountPoint() . $internalPath;
  1562. if (!is_null($path = $this->getRelativePath($fullPath))) {
  1563. return $path;
  1564. }
  1565. }
  1566. }
  1567. }
  1568. throw new NotFoundException(sprintf('File with id "%s" has not been found.', $id));
  1569. }
  1570. /**
  1571. * @param string $path
  1572. * @throws InvalidPathException
  1573. */
  1574. private function assertPathLength($path) {
  1575. $maxLen = min(PHP_MAXPATHLEN, 4000);
  1576. // Check for the string length - performed using isset() instead of strlen()
  1577. // because isset() is about 5x-40x faster.
  1578. if (isset($path[$maxLen])) {
  1579. $pathLen = strlen($path);
  1580. throw new \OCP\Files\InvalidPathException("Path length($pathLen) exceeds max path length($maxLen): $path");
  1581. }
  1582. }
  1583. /**
  1584. * check if it is allowed to move a mount point to a given target.
  1585. * It is not allowed to move a mount point into a different mount point or
  1586. * into an already shared folder
  1587. *
  1588. * @param string $target path
  1589. * @return boolean
  1590. */
  1591. private function isTargetAllowed($target) {
  1592. list($targetStorage, $targetInternalPath) = \OC\Files\Filesystem::resolvePath($target);
  1593. if (!$targetStorage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
  1594. \OCP\Util::writeLog('files',
  1595. 'It is not allowed to move one mount point into another one',
  1596. ILogger::DEBUG);
  1597. return false;
  1598. }
  1599. // note: cannot use the view because the target is already locked
  1600. $fileId = (int)$targetStorage->getCache()->getId($targetInternalPath);
  1601. if ($fileId === -1) {
  1602. // target might not exist, need to check parent instead
  1603. $fileId = (int)$targetStorage->getCache()->getId(dirname($targetInternalPath));
  1604. }
  1605. // check if any of the parents were shared by the current owner (include collections)
  1606. $shares = \OCP\Share::getItemShared(
  1607. 'folder',
  1608. $fileId,
  1609. \OCP\Share::FORMAT_NONE,
  1610. null,
  1611. true
  1612. );
  1613. if (count($shares) > 0) {
  1614. \OCP\Util::writeLog('files',
  1615. 'It is not allowed to move one mount point into a shared folder',
  1616. ILogger::DEBUG);
  1617. return false;
  1618. }
  1619. return true;
  1620. }
  1621. /**
  1622. * Get a fileinfo object for files that are ignored in the cache (part files)
  1623. *
  1624. * @param string $path
  1625. * @return \OCP\Files\FileInfo
  1626. */
  1627. private function getPartFileInfo($path) {
  1628. $mount = $this->getMount($path);
  1629. $storage = $mount->getStorage();
  1630. $internalPath = $mount->getInternalPath($this->getAbsolutePath($path));
  1631. $owner = \OC::$server->getUserManager()->get($storage->getOwner($internalPath));
  1632. return new FileInfo(
  1633. $this->getAbsolutePath($path),
  1634. $storage,
  1635. $internalPath,
  1636. [
  1637. 'fileid' => null,
  1638. 'mimetype' => $storage->getMimeType($internalPath),
  1639. 'name' => basename($path),
  1640. 'etag' => null,
  1641. 'size' => $storage->filesize($internalPath),
  1642. 'mtime' => $storage->filemtime($internalPath),
  1643. 'encrypted' => false,
  1644. 'permissions' => \OCP\Constants::PERMISSION_ALL
  1645. ],
  1646. $mount,
  1647. $owner
  1648. );
  1649. }
  1650. /**
  1651. * @param string $path
  1652. * @param string $fileName
  1653. * @throws InvalidPathException
  1654. */
  1655. public function verifyPath($path, $fileName) {
  1656. try {
  1657. /** @type \OCP\Files\Storage $storage */
  1658. list($storage, $internalPath) = $this->resolvePath($path);
  1659. $storage->verifyPath($internalPath, $fileName);
  1660. } catch (ReservedWordException $ex) {
  1661. $l = \OC::$server->getL10N('lib');
  1662. throw new InvalidPathException($l->t('File name is a reserved word'));
  1663. } catch (InvalidCharacterInPathException $ex) {
  1664. $l = \OC::$server->getL10N('lib');
  1665. throw new InvalidPathException($l->t('File name contains at least one invalid character'));
  1666. } catch (FileNameTooLongException $ex) {
  1667. $l = \OC::$server->getL10N('lib');
  1668. throw new InvalidPathException($l->t('File name is too long'));
  1669. } catch (InvalidDirectoryException $ex) {
  1670. $l = \OC::$server->getL10N('lib');
  1671. throw new InvalidPathException($l->t('Dot files are not allowed'));
  1672. } catch (EmptyFileNameException $ex) {
  1673. $l = \OC::$server->getL10N('lib');
  1674. throw new InvalidPathException($l->t('Empty filename is not allowed'));
  1675. }
  1676. }
  1677. /**
  1678. * get all parent folders of $path
  1679. *
  1680. * @param string $path
  1681. * @return string[]
  1682. */
  1683. private function getParents($path) {
  1684. $path = trim($path, '/');
  1685. if (!$path) {
  1686. return [];
  1687. }
  1688. $parts = explode('/', $path);
  1689. // remove the single file
  1690. array_pop($parts);
  1691. $result = array('/');
  1692. $resultPath = '';
  1693. foreach ($parts as $part) {
  1694. if ($part) {
  1695. $resultPath .= '/' . $part;
  1696. $result[] = $resultPath;
  1697. }
  1698. }
  1699. return $result;
  1700. }
  1701. /**
  1702. * Returns the mount point for which to lock
  1703. *
  1704. * @param string $absolutePath absolute path
  1705. * @param bool $useParentMount true to return parent mount instead of whatever
  1706. * is mounted directly on the given path, false otherwise
  1707. * @return \OC\Files\Mount\MountPoint mount point for which to apply locks
  1708. */
  1709. private function getMountForLock($absolutePath, $useParentMount = false) {
  1710. $results = [];
  1711. $mount = Filesystem::getMountManager()->find($absolutePath);
  1712. if (!$mount) {
  1713. return $results;
  1714. }
  1715. if ($useParentMount) {
  1716. // find out if something is mounted directly on the path
  1717. $internalPath = $mount->getInternalPath($absolutePath);
  1718. if ($internalPath === '') {
  1719. // resolve the parent mount instead
  1720. $mount = Filesystem::getMountManager()->find(dirname($absolutePath));
  1721. }
  1722. }
  1723. return $mount;
  1724. }
  1725. /**
  1726. * Lock the given path
  1727. *
  1728. * @param string $path the path of the file to lock, relative to the view
  1729. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1730. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1731. *
  1732. * @return bool False if the path is excluded from locking, true otherwise
  1733. * @throws \OCP\Lock\LockedException if the path is already locked
  1734. */
  1735. private function lockPath($path, $type, $lockMountPoint = false) {
  1736. $absolutePath = $this->getAbsolutePath($path);
  1737. $absolutePath = Filesystem::normalizePath($absolutePath);
  1738. if (!$this->shouldLockFile($absolutePath)) {
  1739. return false;
  1740. }
  1741. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1742. if ($mount) {
  1743. try {
  1744. $storage = $mount->getStorage();
  1745. if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1746. $storage->acquireLock(
  1747. $mount->getInternalPath($absolutePath),
  1748. $type,
  1749. $this->lockingProvider
  1750. );
  1751. }
  1752. } catch (\OCP\Lock\LockedException $e) {
  1753. // rethrow with the a human-readable path
  1754. throw new \OCP\Lock\LockedException(
  1755. $this->getPathRelativeToFiles($absolutePath),
  1756. $e
  1757. );
  1758. }
  1759. }
  1760. return true;
  1761. }
  1762. /**
  1763. * Change the lock type
  1764. *
  1765. * @param string $path the path of the file to lock, relative to the view
  1766. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1767. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1768. *
  1769. * @return bool False if the path is excluded from locking, true otherwise
  1770. * @throws \OCP\Lock\LockedException if the path is already locked
  1771. */
  1772. public function changeLock($path, $type, $lockMountPoint = false) {
  1773. $path = Filesystem::normalizePath($path);
  1774. $absolutePath = $this->getAbsolutePath($path);
  1775. $absolutePath = Filesystem::normalizePath($absolutePath);
  1776. if (!$this->shouldLockFile($absolutePath)) {
  1777. return false;
  1778. }
  1779. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1780. if ($mount) {
  1781. try {
  1782. $storage = $mount->getStorage();
  1783. if ($storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1784. $storage->changeLock(
  1785. $mount->getInternalPath($absolutePath),
  1786. $type,
  1787. $this->lockingProvider
  1788. );
  1789. }
  1790. } catch (\OCP\Lock\LockedException $e) {
  1791. try {
  1792. // rethrow with the a human-readable path
  1793. throw new \OCP\Lock\LockedException(
  1794. $this->getPathRelativeToFiles($absolutePath),
  1795. $e
  1796. );
  1797. } catch (\InvalidArgumentException $e) {
  1798. throw new \OCP\Lock\LockedException(
  1799. $absolutePath,
  1800. $e
  1801. );
  1802. }
  1803. }
  1804. }
  1805. return true;
  1806. }
  1807. /**
  1808. * Unlock the given path
  1809. *
  1810. * @param string $path the path of the file to unlock, relative to the view
  1811. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1812. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1813. *
  1814. * @return bool False if the path is excluded from locking, true otherwise
  1815. */
  1816. private function unlockPath($path, $type, $lockMountPoint = false) {
  1817. $absolutePath = $this->getAbsolutePath($path);
  1818. $absolutePath = Filesystem::normalizePath($absolutePath);
  1819. if (!$this->shouldLockFile($absolutePath)) {
  1820. return false;
  1821. }
  1822. $mount = $this->getMountForLock($absolutePath, $lockMountPoint);
  1823. if ($mount) {
  1824. $storage = $mount->getStorage();
  1825. if ($storage && $storage->instanceOfStorage('\OCP\Files\Storage\ILockingStorage')) {
  1826. $storage->releaseLock(
  1827. $mount->getInternalPath($absolutePath),
  1828. $type,
  1829. $this->lockingProvider
  1830. );
  1831. }
  1832. }
  1833. return true;
  1834. }
  1835. /**
  1836. * Lock a path and all its parents up to the root of the view
  1837. *
  1838. * @param string $path the path of the file to lock relative to the view
  1839. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1840. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1841. *
  1842. * @return bool False if the path is excluded from locking, true otherwise
  1843. */
  1844. public function lockFile($path, $type, $lockMountPoint = false) {
  1845. $absolutePath = $this->getAbsolutePath($path);
  1846. $absolutePath = Filesystem::normalizePath($absolutePath);
  1847. if (!$this->shouldLockFile($absolutePath)) {
  1848. return false;
  1849. }
  1850. $this->lockPath($path, $type, $lockMountPoint);
  1851. $parents = $this->getParents($path);
  1852. foreach ($parents as $parent) {
  1853. $this->lockPath($parent, ILockingProvider::LOCK_SHARED);
  1854. }
  1855. return true;
  1856. }
  1857. /**
  1858. * Unlock a path and all its parents up to the root of the view
  1859. *
  1860. * @param string $path the path of the file to lock relative to the view
  1861. * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE
  1862. * @param bool $lockMountPoint true to lock the mount point, false to lock the attached mount/storage
  1863. *
  1864. * @return bool False if the path is excluded from locking, true otherwise
  1865. */
  1866. public function unlockFile($path, $type, $lockMountPoint = false) {
  1867. $absolutePath = $this->getAbsolutePath($path);
  1868. $absolutePath = Filesystem::normalizePath($absolutePath);
  1869. if (!$this->shouldLockFile($absolutePath)) {
  1870. return false;
  1871. }
  1872. $this->unlockPath($path, $type, $lockMountPoint);
  1873. $parents = $this->getParents($path);
  1874. foreach ($parents as $parent) {
  1875. $this->unlockPath($parent, ILockingProvider::LOCK_SHARED);
  1876. }
  1877. return true;
  1878. }
  1879. /**
  1880. * Only lock files in data/user/files/
  1881. *
  1882. * @param string $path Absolute path to the file/folder we try to (un)lock
  1883. * @return bool
  1884. */
  1885. protected function shouldLockFile($path) {
  1886. $path = Filesystem::normalizePath($path);
  1887. $pathSegments = explode('/', $path);
  1888. if (isset($pathSegments[2])) {
  1889. // E.g.: /username/files/path-to-file
  1890. return ($pathSegments[2] === 'files') && (count($pathSegments) > 3);
  1891. }
  1892. return strpos($path, '/appdata_') !== 0;
  1893. }
  1894. /**
  1895. * Shortens the given absolute path to be relative to
  1896. * "$user/files".
  1897. *
  1898. * @param string $absolutePath absolute path which is under "files"
  1899. *
  1900. * @return string path relative to "files" with trimmed slashes or null
  1901. * if the path was NOT relative to files
  1902. *
  1903. * @throws \InvalidArgumentException if the given path was not under "files"
  1904. * @since 8.1.0
  1905. */
  1906. public function getPathRelativeToFiles($absolutePath) {
  1907. $path = Filesystem::normalizePath($absolutePath);
  1908. $parts = explode('/', trim($path, '/'), 3);
  1909. // "$user", "files", "path/to/dir"
  1910. if (!isset($parts[1]) || $parts[1] !== 'files') {
  1911. $this->logger->error(
  1912. '$absolutePath must be relative to "files", value is "%s"',
  1913. [
  1914. $absolutePath
  1915. ]
  1916. );
  1917. throw new \InvalidArgumentException('$absolutePath must be relative to "files"');
  1918. }
  1919. if (isset($parts[2])) {
  1920. return $parts[2];
  1921. }
  1922. return '';
  1923. }
  1924. /**
  1925. * @param string $filename
  1926. * @return array
  1927. * @throws \OC\User\NoUserException
  1928. * @throws NotFoundException
  1929. */
  1930. public function getUidAndFilename($filename) {
  1931. $info = $this->getFileInfo($filename);
  1932. if (!$info instanceof \OCP\Files\FileInfo) {
  1933. throw new NotFoundException($this->getAbsolutePath($filename) . ' not found');
  1934. }
  1935. $uid = $info->getOwner()->getUID();
  1936. if ($uid != \OCP\User::getUser()) {
  1937. Filesystem::initMountPoints($uid);
  1938. $ownerView = new View('/' . $uid . '/files');
  1939. try {
  1940. $filename = $ownerView->getPath($info['fileid']);
  1941. } catch (NotFoundException $e) {
  1942. throw new NotFoundException('File with id ' . $info['fileid'] . ' not found for user ' . $uid);
  1943. }
  1944. }
  1945. return [$uid, $filename];
  1946. }
  1947. /**
  1948. * Creates parent non-existing folders
  1949. *
  1950. * @param string $filePath
  1951. * @return bool
  1952. */
  1953. private function createParentDirectories($filePath) {
  1954. $directoryParts = explode('/', $filePath);
  1955. $directoryParts = array_filter($directoryParts);
  1956. foreach ($directoryParts as $key => $part) {
  1957. $currentPathElements = array_slice($directoryParts, 0, $key);
  1958. $currentPath = '/' . implode('/', $currentPathElements);
  1959. if ($this->is_file($currentPath)) {
  1960. return false;
  1961. }
  1962. if (!$this->file_exists($currentPath)) {
  1963. $this->mkdir($currentPath);
  1964. }
  1965. }
  1966. return true;
  1967. }
  1968. }