You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

View.php 64KB

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