View.php 65 KB

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