ViewTest.php 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace Test\Files;
  8. use OC\Files\Cache\Watcher;
  9. use OC\Files\Filesystem;
  10. use OC\Files\Mount\MountPoint;
  11. use OC\Files\SetupManager;
  12. use OC\Files\Storage\Common;
  13. use OC\Files\Storage\Storage;
  14. use OC\Files\Storage\Temporary;
  15. use OC\Files\View;
  16. use OC\Share20\ShareDisableChecker;
  17. use OCP\Cache\CappedMemoryCache;
  18. use OCP\Constants;
  19. use OCP\Files\Config\IMountProvider;
  20. use OCP\Files\FileInfo;
  21. use OCP\Files\GenericFileException;
  22. use OCP\Files\Mount\IMountManager;
  23. use OCP\Files\Storage\IStorage;
  24. use OCP\IDBConnection;
  25. use OCP\Lock\ILockingProvider;
  26. use OCP\Lock\LockedException;
  27. use OCP\Share\IManager as IShareManager;
  28. use OCP\Share\IShare;
  29. use OCP\Util;
  30. use Test\HookHelper;
  31. use Test\TestMoveableMountPoint;
  32. use Test\Traits\UserTrait;
  33. class TemporaryNoTouch extends Temporary {
  34. public function touch($path, $mtime = null) {
  35. return false;
  36. }
  37. }
  38. class TemporaryNoCross extends Temporary {
  39. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = null) {
  40. return Common::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime);
  41. }
  42. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  43. return Common::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  44. }
  45. }
  46. class TemporaryNoLocal extends Temporary {
  47. public function instanceOfStorage($className) {
  48. if ($className === '\OC\Files\Storage\Local') {
  49. return false;
  50. } else {
  51. return parent::instanceOfStorage($className);
  52. }
  53. }
  54. }
  55. /**
  56. * Class ViewTest
  57. *
  58. * @group DB
  59. *
  60. * @package Test\Files
  61. */
  62. class ViewTest extends \Test\TestCase {
  63. use UserTrait;
  64. /**
  65. * @var \OC\Files\Storage\Storage[] $storages
  66. */
  67. private $storages = [];
  68. /**
  69. * @var string
  70. */
  71. private $user;
  72. /**
  73. * @var \OCP\IUser
  74. */
  75. private $userObject;
  76. /**
  77. * @var \OCP\IGroup
  78. */
  79. private $groupObject;
  80. /** @var \OC\Files\Storage\Storage */
  81. private $tempStorage;
  82. protected function setUp(): void {
  83. parent::setUp();
  84. \OC_Hook::clear();
  85. \OC_User::clearBackends();
  86. \OC_User::useBackend(new \Test\Util\User\Dummy());
  87. //login
  88. $userManager = \OC::$server->getUserManager();
  89. $groupManager = \OC::$server->getGroupManager();
  90. $this->user = 'test';
  91. $this->userObject = $userManager->createUser('test', 'test');
  92. $this->groupObject = $groupManager->createGroup('group1');
  93. $this->groupObject->addUser($this->userObject);
  94. self::loginAsUser($this->user);
  95. /** @var IMountManager $manager */
  96. $manager = \OC::$server->get(IMountManager::class);
  97. $manager->removeMount('/test');
  98. $this->tempStorage = null;
  99. }
  100. protected function tearDown(): void {
  101. \OC_User::setUserId($this->user);
  102. foreach ($this->storages as $storage) {
  103. $cache = $storage->getCache();
  104. $ids = $cache->getAll();
  105. $cache->clear();
  106. }
  107. if ($this->tempStorage) {
  108. system('rm -rf ' . escapeshellarg($this->tempStorage->getDataDir()));
  109. }
  110. self::logout();
  111. /** @var SetupManager $setupManager */
  112. $setupManager = \OC::$server->get(SetupManager::class);
  113. $setupManager->setupRoot();
  114. $this->userObject->delete();
  115. $this->groupObject->delete();
  116. $mountProviderCollection = \OC::$server->getMountProviderCollection();
  117. self::invokePrivate($mountProviderCollection, 'providers', [[]]);
  118. parent::tearDown();
  119. }
  120. /**
  121. * @medium
  122. */
  123. public function testCacheAPI() {
  124. $storage1 = $this->getTestStorage();
  125. $storage2 = $this->getTestStorage();
  126. $storage3 = $this->getTestStorage();
  127. $root = self::getUniqueID('/');
  128. Filesystem::mount($storage1, [], $root . '/');
  129. Filesystem::mount($storage2, [], $root . '/substorage');
  130. Filesystem::mount($storage3, [], $root . '/folder/anotherstorage');
  131. $textSize = strlen("dummy file data\n");
  132. $imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo/logo.png');
  133. $storageSize = $textSize * 2 + $imageSize;
  134. $storageInfo = $storage3->getCache()->get('');
  135. $this->assertEquals($storageSize, $storageInfo['size']);
  136. $rootView = new View($root);
  137. $cachedData = $rootView->getFileInfo('/foo.txt');
  138. $this->assertEquals($textSize, $cachedData['size']);
  139. $this->assertEquals('text/plain', $cachedData['mimetype']);
  140. $this->assertNotEquals(-1, $cachedData['permissions']);
  141. $cachedData = $rootView->getFileInfo('/');
  142. $this->assertEquals($storageSize * 3, $cachedData['size']);
  143. $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
  144. // get cached data excluding mount points
  145. $cachedData = $rootView->getFileInfo('/', false);
  146. $this->assertEquals($storageSize, $cachedData['size']);
  147. $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
  148. $cachedData = $rootView->getFileInfo('/folder');
  149. $this->assertEquals($storageSize + $textSize, $cachedData['size']);
  150. $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
  151. $folderData = $rootView->getDirectoryContent('/');
  152. /**
  153. * expected entries:
  154. * folder
  155. * foo.png
  156. * foo.txt
  157. * substorage
  158. */
  159. $this->assertCount(4, $folderData);
  160. $this->assertEquals('folder', $folderData[0]['name']);
  161. $this->assertEquals('foo.png', $folderData[1]['name']);
  162. $this->assertEquals('foo.txt', $folderData[2]['name']);
  163. $this->assertEquals('substorage', $folderData[3]['name']);
  164. $this->assertEquals($storageSize + $textSize, $folderData[0]['size']);
  165. $this->assertEquals($imageSize, $folderData[1]['size']);
  166. $this->assertEquals($textSize, $folderData[2]['size']);
  167. $this->assertEquals($storageSize, $folderData[3]['size']);
  168. $folderData = $rootView->getDirectoryContent('/substorage');
  169. /**
  170. * expected entries:
  171. * folder
  172. * foo.png
  173. * foo.txt
  174. */
  175. $this->assertCount(3, $folderData);
  176. $this->assertEquals('folder', $folderData[0]['name']);
  177. $this->assertEquals('foo.png', $folderData[1]['name']);
  178. $this->assertEquals('foo.txt', $folderData[2]['name']);
  179. $folderView = new View($root . '/folder');
  180. $this->assertEquals($rootView->getFileInfo('/folder'), $folderView->getFileInfo('/'));
  181. $cachedData = $rootView->getFileInfo('/foo.txt');
  182. $this->assertFalse($cachedData['encrypted']);
  183. $id = $rootView->putFileInfo('/foo.txt', ['encrypted' => true]);
  184. $cachedData = $rootView->getFileInfo('/foo.txt');
  185. $this->assertTrue($cachedData['encrypted']);
  186. $this->assertEquals($cachedData['fileid'], $id);
  187. $this->assertFalse($rootView->getFileInfo('/non/existing'));
  188. $this->assertEquals([], $rootView->getDirectoryContent('/non/existing'));
  189. }
  190. /**
  191. * @medium
  192. */
  193. public function testGetPath() {
  194. $storage1 = $this->getTestStorage();
  195. $storage2 = $this->getTestStorage();
  196. $storage3 = $this->getTestStorage();
  197. Filesystem::mount($storage1, [], '/');
  198. Filesystem::mount($storage2, [], '/substorage');
  199. Filesystem::mount($storage3, [], '/folder/anotherstorage');
  200. $rootView = new View('');
  201. $cachedData = $rootView->getFileInfo('/foo.txt');
  202. /** @var int $id1 */
  203. $id1 = $cachedData['fileid'];
  204. $this->assertEquals('/foo.txt', $rootView->getPath($id1));
  205. $cachedData = $rootView->getFileInfo('/substorage/foo.txt');
  206. /** @var int $id2 */
  207. $id2 = $cachedData['fileid'];
  208. $this->assertEquals('/substorage/foo.txt', $rootView->getPath($id2));
  209. $folderView = new View('/substorage');
  210. $this->assertEquals('/foo.txt', $folderView->getPath($id2));
  211. }
  212. public function testGetPathNotExisting() {
  213. $this->expectException(\OCP\Files\NotFoundException::class);
  214. $storage1 = $this->getTestStorage();
  215. Filesystem::mount($storage1, [], '/');
  216. $rootView = new View('');
  217. $cachedData = $rootView->getFileInfo('/foo.txt');
  218. /** @var int $id1 */
  219. $id1 = $cachedData['fileid'];
  220. $folderView = new View('/substorage');
  221. $this->assertNull($folderView->getPath($id1));
  222. }
  223. /**
  224. * @medium
  225. */
  226. public function testMountPointOverwrite() {
  227. $storage1 = $this->getTestStorage(false);
  228. $storage2 = $this->getTestStorage();
  229. $storage1->mkdir('substorage');
  230. Filesystem::mount($storage1, [], '/');
  231. Filesystem::mount($storage2, [], '/substorage');
  232. $rootView = new View('');
  233. $folderContent = $rootView->getDirectoryContent('/');
  234. $this->assertCount(4, $folderContent);
  235. }
  236. public function sharingDisabledPermissionProvider() {
  237. return [
  238. ['no', '', true],
  239. ['yes', 'group1', false],
  240. ];
  241. }
  242. /**
  243. * @dataProvider sharingDisabledPermissionProvider
  244. */
  245. public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable) {
  246. // Reset sharing disabled for users cache
  247. self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
  248. $config = \OC::$server->getConfig();
  249. $oldExcludeGroupsFlag = $config->getAppValue('core', 'shareapi_exclude_groups', 'no');
  250. $oldExcludeGroupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  251. $config->setAppValue('core', 'shareapi_exclude_groups', $excludeGroups);
  252. $config->setAppValue('core', 'shareapi_exclude_groups_list', $excludeGroupsList);
  253. $storage1 = $this->getTestStorage();
  254. $storage2 = $this->getTestStorage();
  255. Filesystem::mount($storage1, [], '/');
  256. Filesystem::mount($storage2, [], '/mount');
  257. $view = new View('/');
  258. $folderContent = $view->getDirectoryContent('');
  259. $this->assertEquals($expectedShareable, $folderContent[0]->isShareable());
  260. $folderContent = $view->getDirectoryContent('mount');
  261. $this->assertEquals($expectedShareable, $folderContent[0]->isShareable());
  262. $config->setAppValue('core', 'shareapi_exclude_groups', $oldExcludeGroupsFlag);
  263. $config->setAppValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList);
  264. // Reset sharing disabled for users cache
  265. self::invokePrivate(\OC::$server->get(ShareDisableChecker::class), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
  266. }
  267. public function testCacheIncompleteFolder() {
  268. $storage1 = $this->getTestStorage(false);
  269. Filesystem::mount($storage1, [], '/incomplete');
  270. $rootView = new View('/incomplete');
  271. $entries = $rootView->getDirectoryContent('/');
  272. $this->assertCount(3, $entries);
  273. // /folder will already be in the cache but not scanned
  274. $entries = $rootView->getDirectoryContent('/folder');
  275. $this->assertCount(1, $entries);
  276. }
  277. public function testAutoScan() {
  278. $storage1 = $this->getTestStorage(false);
  279. $storage2 = $this->getTestStorage(false);
  280. Filesystem::mount($storage1, [], '/');
  281. Filesystem::mount($storage2, [], '/substorage');
  282. $textSize = strlen("dummy file data\n");
  283. $rootView = new View('');
  284. $cachedData = $rootView->getFileInfo('/');
  285. $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
  286. $this->assertEquals(-1, $cachedData['size']);
  287. $folderData = $rootView->getDirectoryContent('/substorage/folder');
  288. $this->assertEquals('text/plain', $folderData[0]['mimetype']);
  289. $this->assertEquals($textSize, $folderData[0]['size']);
  290. }
  291. /**
  292. * @medium
  293. */
  294. public function testSearch() {
  295. $storage1 = $this->getTestStorage();
  296. $storage2 = $this->getTestStorage();
  297. $storage3 = $this->getTestStorage();
  298. Filesystem::mount($storage1, [], '/');
  299. Filesystem::mount($storage2, [], '/substorage');
  300. Filesystem::mount($storage3, [], '/folder/anotherstorage');
  301. $rootView = new View('');
  302. $results = $rootView->search('foo');
  303. $this->assertCount(6, $results);
  304. $paths = [];
  305. foreach ($results as $result) {
  306. $this->assertEquals($result['path'], Filesystem::normalizePath($result['path']));
  307. $paths[] = $result['path'];
  308. }
  309. $this->assertContains('/foo.txt', $paths);
  310. $this->assertContains('/foo.png', $paths);
  311. $this->assertContains('/substorage/foo.txt', $paths);
  312. $this->assertContains('/substorage/foo.png', $paths);
  313. $this->assertContains('/folder/anotherstorage/foo.txt', $paths);
  314. $this->assertContains('/folder/anotherstorage/foo.png', $paths);
  315. $folderView = new View('/folder');
  316. $results = $folderView->search('bar');
  317. $this->assertCount(2, $results);
  318. $paths = [];
  319. foreach ($results as $result) {
  320. $paths[] = $result['path'];
  321. }
  322. $this->assertContains('/anotherstorage/folder/bar.txt', $paths);
  323. $this->assertContains('/bar.txt', $paths);
  324. $results = $folderView->search('foo');
  325. $this->assertCount(2, $results);
  326. $paths = [];
  327. foreach ($results as $result) {
  328. $paths[] = $result['path'];
  329. }
  330. $this->assertContains('/anotherstorage/foo.txt', $paths);
  331. $this->assertContains('/anotherstorage/foo.png', $paths);
  332. $this->assertCount(6, $rootView->searchByMime('text'));
  333. $this->assertCount(3, $folderView->searchByMime('text'));
  334. }
  335. /**
  336. * @medium
  337. */
  338. public function testWatcher() {
  339. $storage1 = $this->getTestStorage();
  340. Filesystem::mount($storage1, [], '/');
  341. $storage1->getWatcher()->setPolicy(Watcher::CHECK_ALWAYS);
  342. $rootView = new View('');
  343. $cachedData = $rootView->getFileInfo('foo.txt');
  344. $this->assertEquals(16, $cachedData['size']);
  345. $rootView->putFileInfo('foo.txt', ['storage_mtime' => 10]);
  346. $storage1->file_put_contents('foo.txt', 'foo');
  347. clearstatcache();
  348. $cachedData = $rootView->getFileInfo('foo.txt');
  349. $this->assertEquals(3, $cachedData['size']);
  350. }
  351. /**
  352. * @medium
  353. */
  354. public function testCopyBetweenStorageNoCross() {
  355. $storage1 = $this->getTestStorage(true, TemporaryNoCross::class);
  356. $storage2 = $this->getTestStorage(true, TemporaryNoCross::class);
  357. $this->copyBetweenStorages($storage1, $storage2);
  358. }
  359. /**
  360. * @medium
  361. */
  362. public function testCopyBetweenStorageCross() {
  363. $storage1 = $this->getTestStorage();
  364. $storage2 = $this->getTestStorage();
  365. $this->copyBetweenStorages($storage1, $storage2);
  366. }
  367. /**
  368. * @medium
  369. */
  370. public function testCopyBetweenStorageCrossNonLocal() {
  371. $storage1 = $this->getTestStorage(true, TemporaryNoLocal::class);
  372. $storage2 = $this->getTestStorage(true, TemporaryNoLocal::class);
  373. $this->copyBetweenStorages($storage1, $storage2);
  374. }
  375. public function copyBetweenStorages($storage1, $storage2) {
  376. Filesystem::mount($storage1, [], '/');
  377. Filesystem::mount($storage2, [], '/substorage');
  378. $rootView = new View('');
  379. $rootView->mkdir('substorage/emptyfolder');
  380. $rootView->copy('substorage', 'anotherfolder');
  381. $this->assertTrue($rootView->is_dir('/anotherfolder'));
  382. $this->assertTrue($rootView->is_dir('/substorage'));
  383. $this->assertTrue($rootView->is_dir('/anotherfolder/emptyfolder'));
  384. $this->assertTrue($rootView->is_dir('/substorage/emptyfolder'));
  385. $this->assertTrue($rootView->file_exists('/anotherfolder/foo.txt'));
  386. $this->assertTrue($rootView->file_exists('/anotherfolder/foo.png'));
  387. $this->assertTrue($rootView->file_exists('/anotherfolder/folder/bar.txt'));
  388. $this->assertTrue($rootView->file_exists('/substorage/foo.txt'));
  389. $this->assertTrue($rootView->file_exists('/substorage/foo.png'));
  390. $this->assertTrue($rootView->file_exists('/substorage/folder/bar.txt'));
  391. }
  392. /**
  393. * @medium
  394. */
  395. public function testMoveBetweenStorageNoCross() {
  396. $storage1 = $this->getTestStorage(true, TemporaryNoCross::class);
  397. $storage2 = $this->getTestStorage(true, TemporaryNoCross::class);
  398. $this->moveBetweenStorages($storage1, $storage2);
  399. }
  400. /**
  401. * @medium
  402. */
  403. public function testMoveBetweenStorageCross() {
  404. $storage1 = $this->getTestStorage();
  405. $storage2 = $this->getTestStorage();
  406. $this->moveBetweenStorages($storage1, $storage2);
  407. }
  408. /**
  409. * @medium
  410. */
  411. public function testMoveBetweenStorageCrossNonLocal() {
  412. $storage1 = $this->getTestStorage(true, TemporaryNoLocal::class);
  413. $storage2 = $this->getTestStorage(true, TemporaryNoLocal::class);
  414. $this->moveBetweenStorages($storage1, $storage2);
  415. }
  416. public function moveBetweenStorages($storage1, $storage2) {
  417. Filesystem::mount($storage1, [], '/');
  418. Filesystem::mount($storage2, [], '/substorage');
  419. $rootView = new View('');
  420. $rootView->rename('foo.txt', 'substorage/folder/foo.txt');
  421. $this->assertFalse($rootView->file_exists('foo.txt'));
  422. $this->assertTrue($rootView->file_exists('substorage/folder/foo.txt'));
  423. $rootView->rename('substorage/folder', 'anotherfolder');
  424. $this->assertFalse($rootView->is_dir('substorage/folder'));
  425. $this->assertTrue($rootView->file_exists('anotherfolder/foo.txt'));
  426. $this->assertTrue($rootView->file_exists('anotherfolder/bar.txt'));
  427. }
  428. /**
  429. * @medium
  430. */
  431. public function testUnlink() {
  432. $storage1 = $this->getTestStorage();
  433. $storage2 = $this->getTestStorage();
  434. Filesystem::mount($storage1, [], '/');
  435. Filesystem::mount($storage2, [], '/substorage');
  436. $rootView = new View('');
  437. $rootView->file_put_contents('/foo.txt', 'asd');
  438. $rootView->file_put_contents('/substorage/bar.txt', 'asd');
  439. $this->assertTrue($rootView->file_exists('foo.txt'));
  440. $this->assertTrue($rootView->file_exists('substorage/bar.txt'));
  441. $this->assertTrue($rootView->unlink('foo.txt'));
  442. $this->assertTrue($rootView->unlink('substorage/bar.txt'));
  443. $this->assertFalse($rootView->file_exists('foo.txt'));
  444. $this->assertFalse($rootView->file_exists('substorage/bar.txt'));
  445. }
  446. public function rmdirOrUnlinkDataProvider() {
  447. return [['rmdir'], ['unlink']];
  448. }
  449. /**
  450. * @dataProvider rmdirOrUnlinkDataProvider
  451. */
  452. public function testRmdir($method) {
  453. $storage1 = $this->getTestStorage();
  454. Filesystem::mount($storage1, [], '/');
  455. $rootView = new View('');
  456. $rootView->mkdir('sub');
  457. $rootView->mkdir('sub/deep');
  458. $rootView->file_put_contents('/sub/deep/foo.txt', 'asd');
  459. $this->assertTrue($rootView->file_exists('sub/deep/foo.txt'));
  460. $this->assertTrue($rootView->$method('sub'));
  461. $this->assertFalse($rootView->file_exists('sub'));
  462. }
  463. /**
  464. * @medium
  465. */
  466. public function testUnlinkRootMustFail() {
  467. $storage1 = $this->getTestStorage();
  468. $storage2 = $this->getTestStorage();
  469. Filesystem::mount($storage1, [], '/');
  470. Filesystem::mount($storage2, [], '/substorage');
  471. $rootView = new View('');
  472. $rootView->file_put_contents('/foo.txt', 'asd');
  473. $rootView->file_put_contents('/substorage/bar.txt', 'asd');
  474. $this->assertFalse($rootView->unlink(''));
  475. $this->assertFalse($rootView->unlink('/'));
  476. $this->assertFalse($rootView->unlink('substorage'));
  477. $this->assertFalse($rootView->unlink('/substorage'));
  478. }
  479. /**
  480. * @medium
  481. */
  482. public function testTouch() {
  483. $storage = $this->getTestStorage(true, TemporaryNoTouch::class);
  484. Filesystem::mount($storage, [], '/');
  485. $rootView = new View('');
  486. $oldCachedData = $rootView->getFileInfo('foo.txt');
  487. $rootView->touch('foo.txt', 500);
  488. $cachedData = $rootView->getFileInfo('foo.txt');
  489. $this->assertEquals(500, $cachedData['mtime']);
  490. $this->assertEquals($oldCachedData['storage_mtime'], $cachedData['storage_mtime']);
  491. $rootView->putFileInfo('foo.txt', ['storage_mtime' => 1000]); //make sure the watcher detects the change
  492. $rootView->file_put_contents('foo.txt', 'asd');
  493. $cachedData = $rootView->getFileInfo('foo.txt');
  494. $this->assertGreaterThanOrEqual($oldCachedData['mtime'], $cachedData['mtime']);
  495. $this->assertEquals($cachedData['storage_mtime'], $cachedData['mtime']);
  496. }
  497. /**
  498. * @medium
  499. */
  500. public function testTouchFloat() {
  501. $storage = $this->getTestStorage(true, TemporaryNoTouch::class);
  502. Filesystem::mount($storage, [], '/');
  503. $rootView = new View('');
  504. $oldCachedData = $rootView->getFileInfo('foo.txt');
  505. $rootView->touch('foo.txt', 500.5);
  506. $cachedData = $rootView->getFileInfo('foo.txt');
  507. $this->assertEquals(500, $cachedData['mtime']);
  508. }
  509. /**
  510. * @medium
  511. */
  512. public function testViewHooks() {
  513. $storage1 = $this->getTestStorage();
  514. $storage2 = $this->getTestStorage();
  515. $defaultRoot = Filesystem::getRoot();
  516. Filesystem::mount($storage1, [], '/');
  517. Filesystem::mount($storage2, [], $defaultRoot . '/substorage');
  518. \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');
  519. $rootView = new View('');
  520. $subView = new View($defaultRoot . '/substorage');
  521. $this->hookPath = null;
  522. $rootView->file_put_contents('/foo.txt', 'asd');
  523. $this->assertNull($this->hookPath);
  524. $subView->file_put_contents('/foo.txt', 'asd');
  525. $this->assertEquals('/substorage/foo.txt', $this->hookPath);
  526. }
  527. private $hookPath;
  528. public function dummyHook($params) {
  529. $this->hookPath = $params['path'];
  530. }
  531. public function testSearchNotOutsideView() {
  532. $storage1 = $this->getTestStorage();
  533. Filesystem::mount($storage1, [], '/');
  534. $storage1->rename('folder', 'foo');
  535. $scanner = $storage1->getScanner();
  536. $scanner->scan('');
  537. $view = new View('/foo');
  538. $result = $view->search('.txt');
  539. $this->assertCount(1, $result);
  540. }
  541. /**
  542. * @param bool $scan
  543. * @param string $class
  544. * @return \OC\Files\Storage\Storage
  545. */
  546. private function getTestStorage($scan = true, $class = Temporary::class) {
  547. /**
  548. * @var \OC\Files\Storage\Storage $storage
  549. */
  550. $storage = new $class([]);
  551. $textData = "dummy file data\n";
  552. $imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo/logo.png');
  553. $storage->mkdir('folder');
  554. $storage->file_put_contents('foo.txt', $textData);
  555. $storage->file_put_contents('foo.png', $imgData);
  556. $storage->file_put_contents('folder/bar.txt', $textData);
  557. if ($scan) {
  558. $scanner = $storage->getScanner();
  559. $scanner->scan('');
  560. }
  561. $this->storages[] = $storage;
  562. return $storage;
  563. }
  564. /**
  565. * @medium
  566. */
  567. public function testViewHooksIfRootStartsTheSame() {
  568. $storage1 = $this->getTestStorage();
  569. $storage2 = $this->getTestStorage();
  570. $defaultRoot = Filesystem::getRoot();
  571. Filesystem::mount($storage1, [], '/');
  572. Filesystem::mount($storage2, [], $defaultRoot . '_substorage');
  573. \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHook');
  574. $subView = new View($defaultRoot . '_substorage');
  575. $this->hookPath = null;
  576. $subView->file_put_contents('/foo.txt', 'asd');
  577. $this->assertNull($this->hookPath);
  578. }
  579. private $hookWritePath;
  580. private $hookCreatePath;
  581. private $hookUpdatePath;
  582. public function dummyHookWrite($params) {
  583. $this->hookWritePath = $params['path'];
  584. }
  585. public function dummyHookUpdate($params) {
  586. $this->hookUpdatePath = $params['path'];
  587. }
  588. public function dummyHookCreate($params) {
  589. $this->hookCreatePath = $params['path'];
  590. }
  591. public function testEditNoCreateHook() {
  592. $storage1 = $this->getTestStorage();
  593. $storage2 = $this->getTestStorage();
  594. $defaultRoot = Filesystem::getRoot();
  595. Filesystem::mount($storage1, [], '/');
  596. Filesystem::mount($storage2, [], $defaultRoot);
  597. \OC_Hook::connect('OC_Filesystem', 'post_create', $this, 'dummyHookCreate');
  598. \OC_Hook::connect('OC_Filesystem', 'post_update', $this, 'dummyHookUpdate');
  599. \OC_Hook::connect('OC_Filesystem', 'post_write', $this, 'dummyHookWrite');
  600. $view = new View($defaultRoot);
  601. $this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null;
  602. $view->file_put_contents('/asd.txt', 'foo');
  603. $this->assertEquals('/asd.txt', $this->hookCreatePath);
  604. $this->assertNull($this->hookUpdatePath);
  605. $this->assertEquals('/asd.txt', $this->hookWritePath);
  606. $this->hookWritePath = $this->hookUpdatePath = $this->hookCreatePath = null;
  607. $view->file_put_contents('/asd.txt', 'foo');
  608. $this->assertNull($this->hookCreatePath);
  609. $this->assertEquals('/asd.txt', $this->hookUpdatePath);
  610. $this->assertEquals('/asd.txt', $this->hookWritePath);
  611. \OC_Hook::clear('OC_Filesystem', 'post_create');
  612. \OC_Hook::clear('OC_Filesystem', 'post_update');
  613. \OC_Hook::clear('OC_Filesystem', 'post_write');
  614. }
  615. /**
  616. * @dataProvider resolvePathTestProvider
  617. */
  618. public function testResolvePath($expected, $pathToTest) {
  619. $storage1 = $this->getTestStorage();
  620. Filesystem::mount($storage1, [], '/');
  621. $view = new View('');
  622. $result = $view->resolvePath($pathToTest);
  623. $this->assertEquals($expected, $result[1]);
  624. $exists = $view->file_exists($pathToTest);
  625. $this->assertTrue($exists);
  626. $exists = $view->file_exists($result[1]);
  627. $this->assertTrue($exists);
  628. }
  629. public function resolvePathTestProvider() {
  630. return [
  631. ['foo.txt', 'foo.txt'],
  632. ['foo.txt', '/foo.txt'],
  633. ['folder', 'folder'],
  634. ['folder', '/folder'],
  635. ['folder', 'folder/'],
  636. ['folder', '/folder/'],
  637. ['folder/bar.txt', 'folder/bar.txt'],
  638. ['folder/bar.txt', '/folder/bar.txt'],
  639. ['', ''],
  640. ['', '/'],
  641. ];
  642. }
  643. public function testUTF8Names() {
  644. $names = ['虚', '和知しゃ和で', 'regular ascii', 'sɨˈrɪlɪk', 'ѨѬ', 'أنا أحب القراءة كثيرا'];
  645. $storage = new Temporary([]);
  646. Filesystem::mount($storage, [], '/');
  647. $rootView = new View('');
  648. foreach ($names as $name) {
  649. $rootView->file_put_contents('/' . $name, 'dummy content');
  650. }
  651. $list = $rootView->getDirectoryContent('/');
  652. $this->assertCount(count($names), $list);
  653. foreach ($list as $item) {
  654. $this->assertContains($item['name'], $names);
  655. }
  656. $cache = $storage->getCache();
  657. $scanner = $storage->getScanner();
  658. $scanner->scan('');
  659. $list = $cache->getFolderContents('');
  660. $this->assertCount(count($names), $list);
  661. foreach ($list as $item) {
  662. $this->assertContains($item['name'], $names);
  663. }
  664. }
  665. public function xtestLongPath() {
  666. $storage = new Temporary([]);
  667. Filesystem::mount($storage, [], '/');
  668. $rootView = new View('');
  669. $longPath = '';
  670. $ds = DIRECTORY_SEPARATOR;
  671. /*
  672. * 4096 is the maximum path length in file_cache.path in *nix
  673. * 1024 is the max path length in mac
  674. */
  675. $folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
  676. $tmpdirLength = strlen(\OC::$server->getTempManager()->getTemporaryFolder());
  677. if (\OC_Util::runningOnMac()) {
  678. $depth = ((1024 - $tmpdirLength) / 57);
  679. } else {
  680. $depth = ((4000 - $tmpdirLength) / 57);
  681. }
  682. foreach (range(0, $depth - 1) as $i) {
  683. $longPath .= $ds . $folderName;
  684. $result = $rootView->mkdir($longPath);
  685. $this->assertTrue($result, "mkdir failed on $i - path length: " . strlen($longPath));
  686. $result = $rootView->file_put_contents($longPath . "{$ds}test.txt", 'lorem');
  687. $this->assertEquals(5, $result, "file_put_contents failed on $i");
  688. $this->assertTrue($rootView->file_exists($longPath));
  689. $this->assertTrue($rootView->file_exists($longPath . "{$ds}test.txt"));
  690. }
  691. $cache = $storage->getCache();
  692. $scanner = $storage->getScanner();
  693. $scanner->scan('');
  694. $longPath = $folderName;
  695. foreach (range(0, $depth - 1) as $i) {
  696. $cachedFolder = $cache->get($longPath);
  697. $this->assertTrue(is_array($cachedFolder), "No cache entry for folder at $i");
  698. $this->assertEquals($folderName, $cachedFolder['name'], "Wrong cache entry for folder at $i");
  699. $cachedFile = $cache->get($longPath . '/test.txt');
  700. $this->assertTrue(is_array($cachedFile), "No cache entry for file at $i");
  701. $this->assertEquals('test.txt', $cachedFile['name'], "Wrong cache entry for file at $i");
  702. $longPath .= $ds . $folderName;
  703. }
  704. }
  705. public function testTouchNotSupported() {
  706. $storage = new TemporaryNoTouch([]);
  707. $scanner = $storage->getScanner();
  708. Filesystem::mount($storage, [], '/test/');
  709. $past = time() - 100;
  710. $storage->file_put_contents('test', 'foobar');
  711. $scanner->scan('');
  712. $view = new View('');
  713. $info = $view->getFileInfo('/test/test');
  714. $view->touch('/test/test', $past);
  715. $scanner->scanFile('test', \OC\Files\Cache\Scanner::REUSE_ETAG);
  716. $info2 = $view->getFileInfo('/test/test');
  717. $this->assertSame($info['etag'], $info2['etag']);
  718. }
  719. public function testWatcherEtagCrossStorage() {
  720. $storage1 = new Temporary([]);
  721. $storage2 = new Temporary([]);
  722. $scanner1 = $storage1->getScanner();
  723. $scanner2 = $storage2->getScanner();
  724. $storage1->mkdir('sub');
  725. Filesystem::mount($storage1, [], '/test/');
  726. Filesystem::mount($storage2, [], '/test/sub/storage');
  727. $past = time() - 100;
  728. $storage2->file_put_contents('test.txt', 'foobar');
  729. $scanner1->scan('');
  730. $scanner2->scan('');
  731. $view = new View('');
  732. $storage2->getWatcher('')->setPolicy(Watcher::CHECK_ALWAYS);
  733. $oldFileInfo = $view->getFileInfo('/test/sub/storage/test.txt');
  734. $oldFolderInfo = $view->getFileInfo('/test');
  735. $storage2->getCache()->update($oldFileInfo->getId(), [
  736. 'storage_mtime' => $past,
  737. ]);
  738. $oldEtag = $oldFolderInfo->getEtag();
  739. $view->getFileInfo('/test/sub/storage/test.txt');
  740. $newFolderInfo = $view->getFileInfo('/test');
  741. $this->assertNotEquals($newFolderInfo->getEtag(), $oldEtag);
  742. }
  743. /**
  744. * @dataProvider absolutePathProvider
  745. */
  746. public function testGetAbsolutePath($expectedPath, $relativePath) {
  747. $view = new View('/files');
  748. $this->assertEquals($expectedPath, $view->getAbsolutePath($relativePath));
  749. }
  750. public function testPartFileInfo() {
  751. $storage = new Temporary([]);
  752. $scanner = $storage->getScanner();
  753. Filesystem::mount($storage, [], '/test/');
  754. $storage->file_put_contents('test.part', 'foobar');
  755. $scanner->scan('');
  756. $view = new View('/test');
  757. $info = $view->getFileInfo('test.part');
  758. $this->assertInstanceOf('\OCP\Files\FileInfo', $info);
  759. $this->assertNull($info->getId());
  760. $this->assertEquals(6, $info->getSize());
  761. }
  762. public function absolutePathProvider() {
  763. return [
  764. ['/files/', ''],
  765. ['/files/0', '0'],
  766. ['/files/false', 'false'],
  767. ['/files/true', 'true'],
  768. ['/files/', '/'],
  769. ['/files/test', 'test'],
  770. ['/files/test', '/test'],
  771. ];
  772. }
  773. /**
  774. * @dataProvider chrootRelativePathProvider
  775. */
  776. public function testChrootGetRelativePath($root, $absolutePath, $expectedPath) {
  777. $view = new View('/files');
  778. $view->chroot($root);
  779. $this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
  780. }
  781. public function chrootRelativePathProvider() {
  782. return $this->relativePathProvider('/');
  783. }
  784. /**
  785. * @dataProvider initRelativePathProvider
  786. */
  787. public function testInitGetRelativePath($root, $absolutePath, $expectedPath) {
  788. $view = new View($root);
  789. $this->assertEquals($expectedPath, $view->getRelativePath($absolutePath));
  790. }
  791. public function initRelativePathProvider() {
  792. return $this->relativePathProvider(null);
  793. }
  794. public function relativePathProvider($missingRootExpectedPath) {
  795. return [
  796. // No root - returns the path
  797. ['', '/files', '/files'],
  798. ['', '/files/', '/files/'],
  799. // Root equals path - /
  800. ['/files/', '/files/', '/'],
  801. ['/files/', '/files', '/'],
  802. ['/files', '/files/', '/'],
  803. ['/files', '/files', '/'],
  804. // False negatives: chroot fixes those by adding the leading slash.
  805. // But setting them up with this root (instead of chroot($root))
  806. // will fail them, although they should be the same.
  807. // TODO init should be fixed, so it also adds the leading slash
  808. ['files/', '/files/', $missingRootExpectedPath],
  809. ['files', '/files/', $missingRootExpectedPath],
  810. ['files/', '/files', $missingRootExpectedPath],
  811. ['files', '/files', $missingRootExpectedPath],
  812. // False negatives: Paths provided to the method should have a leading slash
  813. // TODO input should be checked to have a leading slash
  814. ['/files/', 'files/', null],
  815. ['/files', 'files/', null],
  816. ['/files/', 'files', null],
  817. ['/files', 'files', null],
  818. // with trailing slashes
  819. ['/files/', '/files/0', '0'],
  820. ['/files/', '/files/false', 'false'],
  821. ['/files/', '/files/true', 'true'],
  822. ['/files/', '/files/test', 'test'],
  823. ['/files/', '/files/test/foo', 'test/foo'],
  824. // without trailing slashes
  825. // TODO false expectation: Should match "with trailing slashes"
  826. ['/files', '/files/0', '/0'],
  827. ['/files', '/files/false', '/false'],
  828. ['/files', '/files/true', '/true'],
  829. ['/files', '/files/test', '/test'],
  830. ['/files', '/files/test/foo', '/test/foo'],
  831. // leading slashes
  832. ['/files/', '/files_trashbin/', null],
  833. ['/files', '/files_trashbin/', null],
  834. ['/files/', '/files_trashbin', null],
  835. ['/files', '/files_trashbin', null],
  836. // no leading slashes
  837. ['files/', 'files_trashbin/', null],
  838. ['files', 'files_trashbin/', null],
  839. ['files/', 'files_trashbin', null],
  840. ['files', 'files_trashbin', null],
  841. // mixed leading slashes
  842. ['files/', '/files_trashbin/', null],
  843. ['/files/', 'files_trashbin/', null],
  844. ['files', '/files_trashbin/', null],
  845. ['/files', 'files_trashbin/', null],
  846. ['files/', '/files_trashbin', null],
  847. ['/files/', 'files_trashbin', null],
  848. ['files', '/files_trashbin', null],
  849. ['/files', 'files_trashbin', null],
  850. ['files', 'files_trashbin/test', null],
  851. ['/files', '/files_trashbin/test', null],
  852. ['/files', 'files_trashbin/test', null],
  853. ];
  854. }
  855. public function testFileView() {
  856. $storage = new Temporary([]);
  857. $scanner = $storage->getScanner();
  858. $storage->file_put_contents('foo.txt', 'bar');
  859. Filesystem::mount($storage, [], '/test/');
  860. $scanner->scan('');
  861. $view = new View('/test/foo.txt');
  862. $this->assertEquals('bar', $view->file_get_contents(''));
  863. $fh = tmpfile();
  864. fwrite($fh, 'foo');
  865. rewind($fh);
  866. $view->file_put_contents('', $fh);
  867. $this->assertEquals('foo', $view->file_get_contents(''));
  868. }
  869. /**
  870. * @dataProvider tooLongPathDataProvider
  871. */
  872. public function testTooLongPath($operation, $param0 = null) {
  873. $this->expectException(\OCP\Files\InvalidPathException::class);
  874. $longPath = '';
  875. // 4000 is the maximum path length in file_cache.path
  876. $folderName = 'abcdefghijklmnopqrstuvwxyz012345678901234567890123456789';
  877. $depth = (4000 / 57);
  878. foreach (range(0, $depth + 1) as $i) {
  879. $longPath .= '/' . $folderName;
  880. }
  881. $storage = new Temporary([]);
  882. $this->tempStorage = $storage; // for later hard cleanup
  883. Filesystem::mount($storage, [], '/');
  884. $rootView = new View('');
  885. if ($param0 === '@0') {
  886. $param0 = $longPath;
  887. }
  888. if ($operation === 'hash') {
  889. $param0 = $longPath;
  890. $longPath = 'md5';
  891. }
  892. call_user_func([$rootView, $operation], $longPath, $param0);
  893. }
  894. public function tooLongPathDataProvider() {
  895. return [
  896. ['getAbsolutePath'],
  897. ['getRelativePath'],
  898. ['getMountPoint'],
  899. ['resolvePath'],
  900. ['getLocalFile'],
  901. ['mkdir'],
  902. ['rmdir'],
  903. ['opendir'],
  904. ['is_dir'],
  905. ['is_file'],
  906. ['stat'],
  907. ['filetype'],
  908. ['filesize'],
  909. ['readfile'],
  910. ['isCreatable'],
  911. ['isReadable'],
  912. ['isUpdatable'],
  913. ['isDeletable'],
  914. ['isSharable'],
  915. ['file_exists'],
  916. ['filemtime'],
  917. ['touch'],
  918. ['file_get_contents'],
  919. ['unlink'],
  920. ['deleteAll'],
  921. ['toTmpFile'],
  922. ['getMimeType'],
  923. ['free_space'],
  924. ['getFileInfo'],
  925. ['getDirectoryContent'],
  926. ['getOwner'],
  927. ['getETag'],
  928. ['file_put_contents', 'ipsum'],
  929. ['rename', '@0'],
  930. ['copy', '@0'],
  931. ['fopen', 'r'],
  932. ['fromTmpFile', '@0'],
  933. ['hash'],
  934. ['hasUpdated', 0],
  935. ['putFileInfo', []],
  936. ];
  937. }
  938. public function testRenameCrossStoragePreserveMtime() {
  939. $storage1 = new Temporary([]);
  940. $storage2 = new Temporary([]);
  941. $storage1->mkdir('sub');
  942. $storage1->mkdir('foo');
  943. $storage1->file_put_contents('foo.txt', 'asd');
  944. $storage1->file_put_contents('foo/bar.txt', 'asd');
  945. Filesystem::mount($storage1, [], '/test/');
  946. Filesystem::mount($storage2, [], '/test/sub/storage');
  947. $view = new View('');
  948. $time = time() - 200;
  949. $view->touch('/test/foo.txt', $time);
  950. $view->touch('/test/foo', $time);
  951. $view->touch('/test/foo/bar.txt', $time);
  952. $view->rename('/test/foo.txt', '/test/sub/storage/foo.txt');
  953. $this->assertEquals($time, $view->filemtime('/test/sub/storage/foo.txt'));
  954. $view->rename('/test/foo', '/test/sub/storage/foo');
  955. $this->assertEquals($time, $view->filemtime('/test/sub/storage/foo/bar.txt'));
  956. }
  957. public function testRenameFailDeleteTargetKeepSource() {
  958. $this->doTestCopyRenameFail('rename');
  959. }
  960. public function testCopyFailDeleteTargetKeepSource() {
  961. $this->doTestCopyRenameFail('copy');
  962. }
  963. private function doTestCopyRenameFail($operation) {
  964. $storage1 = new Temporary([]);
  965. /** @var \PHPUnit\Framework\MockObject\MockObject|Temporary $storage2 */
  966. $storage2 = $this->getMockBuilder(TemporaryNoCross::class)
  967. ->setConstructorArgs([[]])
  968. ->setMethods(['fopen', 'writeStream'])
  969. ->getMock();
  970. $storage2->method('writeStream')
  971. ->willThrowException(new GenericFileException("Failed to copy stream"));
  972. $storage1->mkdir('sub');
  973. $storage1->file_put_contents('foo.txt', '0123456789ABCDEFGH');
  974. $storage1->mkdir('dirtomove');
  975. $storage1->file_put_contents('dirtomove/indir1.txt', '0123456'); // fits
  976. $storage1->file_put_contents('dirtomove/indir2.txt', '0123456789ABCDEFGH'); // doesn't fit
  977. $storage2->file_put_contents('existing.txt', '0123');
  978. $storage1->getScanner()->scan('');
  979. $storage2->getScanner()->scan('');
  980. Filesystem::mount($storage1, [], '/test/');
  981. Filesystem::mount($storage2, [], '/test/sub/storage');
  982. // move file
  983. $view = new View('');
  984. $this->assertTrue($storage1->file_exists('foo.txt'));
  985. $this->assertFalse($storage2->file_exists('foo.txt'));
  986. $this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/foo.txt'));
  987. $this->assertFalse($storage2->file_exists('foo.txt'));
  988. $this->assertFalse($storage2->getCache()->get('foo.txt'));
  989. $this->assertTrue($storage1->file_exists('foo.txt'));
  990. // if target exists, it will be deleted too
  991. $this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/existing.txt'));
  992. $this->assertFalse($storage2->file_exists('existing.txt'));
  993. $this->assertFalse($storage2->getCache()->get('existing.txt'));
  994. $this->assertTrue($storage1->file_exists('foo.txt'));
  995. // move folder
  996. $this->assertFalse($view->$operation('/test/dirtomove/', '/test/sub/storage/dirtomove/'));
  997. // since the move failed, the full source tree is kept
  998. $this->assertTrue($storage1->file_exists('dirtomove/indir1.txt'));
  999. $this->assertTrue($storage1->file_exists('dirtomove/indir2.txt'));
  1000. // second file not moved/copied
  1001. $this->assertFalse($storage2->file_exists('dirtomove/indir2.txt'));
  1002. $this->assertFalse($storage2->getCache()->get('dirtomove/indir2.txt'));
  1003. }
  1004. public function testDeleteFailKeepCache() {
  1005. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1006. $storage = $this->getMockBuilder(Temporary::class)
  1007. ->setConstructorArgs([[]])
  1008. ->setMethods(['unlink'])
  1009. ->getMock();
  1010. $storage->expects($this->once())
  1011. ->method('unlink')
  1012. ->willReturn(false);
  1013. $scanner = $storage->getScanner();
  1014. $cache = $storage->getCache();
  1015. $storage->file_put_contents('foo.txt', 'asd');
  1016. $scanner->scan('');
  1017. Filesystem::mount($storage, [], '/test/');
  1018. $view = new View('/test');
  1019. $this->assertFalse($view->unlink('foo.txt'));
  1020. $this->assertTrue($cache->inCache('foo.txt'));
  1021. }
  1022. public function directoryTraversalProvider() {
  1023. return [
  1024. ['../test/'],
  1025. ['..\\test\\my/../folder'],
  1026. ['/test/my/../foo\\'],
  1027. ];
  1028. }
  1029. /**
  1030. * @dataProvider directoryTraversalProvider
  1031. * @param string $root
  1032. */
  1033. public function testConstructDirectoryTraversalException($root) {
  1034. $this->expectException(\Exception::class);
  1035. new View($root);
  1036. }
  1037. public function testRenameOverWrite() {
  1038. $storage = new Temporary([]);
  1039. $scanner = $storage->getScanner();
  1040. $storage->mkdir('sub');
  1041. $storage->mkdir('foo');
  1042. $storage->file_put_contents('foo.txt', 'asd');
  1043. $storage->file_put_contents('foo/bar.txt', 'asd');
  1044. $scanner->scan('');
  1045. Filesystem::mount($storage, [], '/test/');
  1046. $view = new View('');
  1047. $this->assertTrue($view->rename('/test/foo.txt', '/test/foo/bar.txt'));
  1048. }
  1049. public function testSetMountOptionsInStorage() {
  1050. $mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['foo' => 'bar']);
  1051. Filesystem::getMountManager()->addMount($mount);
  1052. /** @var \OC\Files\Storage\Common $storage */
  1053. $storage = $mount->getStorage();
  1054. $this->assertEquals($storage->getMountOption('foo'), 'bar');
  1055. }
  1056. public function testSetMountOptionsWatcherPolicy() {
  1057. $mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['filesystem_check_changes' => Watcher::CHECK_NEVER]);
  1058. Filesystem::getMountManager()->addMount($mount);
  1059. /** @var \OC\Files\Storage\Common $storage */
  1060. $storage = $mount->getStorage();
  1061. $watcher = $storage->getWatcher();
  1062. $this->assertEquals(Watcher::CHECK_NEVER, $watcher->getPolicy());
  1063. }
  1064. public function testGetAbsolutePathOnNull() {
  1065. $view = new View();
  1066. $this->assertNull($view->getAbsolutePath(null));
  1067. }
  1068. public function testGetRelativePathOnNull() {
  1069. $view = new View();
  1070. $this->assertNull($view->getRelativePath(null));
  1071. }
  1072. public function testNullAsRoot() {
  1073. $this->expectException(\TypeError::class);
  1074. new View(null);
  1075. }
  1076. /**
  1077. * e.g. reading from a folder that's being renamed
  1078. *
  1079. *
  1080. * @dataProvider dataLockPaths
  1081. *
  1082. * @param string $rootPath
  1083. * @param string $pathPrefix
  1084. */
  1085. public function testReadFromWriteLockedPath($rootPath, $pathPrefix) {
  1086. $this->expectException(\OCP\Lock\LockedException::class);
  1087. $rootPath = str_replace('{folder}', 'files', $rootPath);
  1088. $pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
  1089. $view = new View($rootPath);
  1090. $storage = new Temporary([]);
  1091. Filesystem::mount($storage, [], '/');
  1092. $this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
  1093. $view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED);
  1094. }
  1095. /**
  1096. * Reading from a files_encryption folder that's being renamed
  1097. *
  1098. * @dataProvider dataLockPaths
  1099. *
  1100. * @param string $rootPath
  1101. * @param string $pathPrefix
  1102. */
  1103. public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix) {
  1104. $rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
  1105. $pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
  1106. $view = new View($rootPath);
  1107. $storage = new Temporary([]);
  1108. Filesystem::mount($storage, [], '/');
  1109. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
  1110. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED));
  1111. }
  1112. /**
  1113. * e.g. writing a file that's being downloaded
  1114. *
  1115. *
  1116. * @dataProvider dataLockPaths
  1117. *
  1118. * @param string $rootPath
  1119. * @param string $pathPrefix
  1120. */
  1121. public function testWriteToReadLockedFile($rootPath, $pathPrefix) {
  1122. $this->expectException(\OCP\Lock\LockedException::class);
  1123. $rootPath = str_replace('{folder}', 'files', $rootPath);
  1124. $pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
  1125. $view = new View($rootPath);
  1126. $storage = new Temporary([]);
  1127. Filesystem::mount($storage, [], '/');
  1128. $this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
  1129. $view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE);
  1130. }
  1131. /**
  1132. * Writing a file that's being downloaded
  1133. *
  1134. * @dataProvider dataLockPaths
  1135. *
  1136. * @param string $rootPath
  1137. * @param string $pathPrefix
  1138. */
  1139. public function testWriteToReadUnlockableFile($rootPath, $pathPrefix) {
  1140. $rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
  1141. $pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
  1142. $view = new View($rootPath);
  1143. $storage = new Temporary([]);
  1144. Filesystem::mount($storage, [], '/');
  1145. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
  1146. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
  1147. }
  1148. /**
  1149. * Test that locks are on mount point paths instead of mount root
  1150. */
  1151. public function testLockLocalMountPointPathInsteadOfStorageRoot() {
  1152. $lockingProvider = \OC::$server->get(ILockingProvider::class);
  1153. $view = new View('/testuser/files/');
  1154. $storage = new Temporary([]);
  1155. Filesystem::mount($storage, [], '/');
  1156. $mountedStorage = new Temporary([]);
  1157. Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');
  1158. $this->assertTrue(
  1159. $view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, true),
  1160. 'Can lock mount point'
  1161. );
  1162. // no exception here because storage root was not locked
  1163. $mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1164. $thrown = false;
  1165. try {
  1166. $storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1167. } catch (LockedException $e) {
  1168. $thrown = true;
  1169. }
  1170. $this->assertTrue($thrown, 'Mount point path was locked on root storage');
  1171. $lockingProvider->releaseAll();
  1172. }
  1173. /**
  1174. * Test that locks are on mount point paths and also mount root when requested
  1175. */
  1176. public function testLockStorageRootButNotLocalMountPoint() {
  1177. $lockingProvider = \OC::$server->get(ILockingProvider::class);
  1178. $view = new View('/testuser/files/');
  1179. $storage = new Temporary([]);
  1180. Filesystem::mount($storage, [], '/');
  1181. $mountedStorage = new Temporary([]);
  1182. Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');
  1183. $this->assertTrue(
  1184. $view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, false),
  1185. 'Can lock mount point'
  1186. );
  1187. $thrown = false;
  1188. try {
  1189. $mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1190. } catch (LockedException $e) {
  1191. $thrown = true;
  1192. }
  1193. $this->assertTrue($thrown, 'Mount point storage root was locked on original storage');
  1194. // local mount point was not locked
  1195. $storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1196. $lockingProvider->releaseAll();
  1197. }
  1198. /**
  1199. * Test that locks are on mount point paths and also mount root when requested
  1200. */
  1201. public function testLockMountPointPathFailReleasesBoth() {
  1202. $lockingProvider = \OC::$server->get(ILockingProvider::class);
  1203. $view = new View('/testuser/files/');
  1204. $storage = new Temporary([]);
  1205. Filesystem::mount($storage, [], '/');
  1206. $mountedStorage = new Temporary([]);
  1207. Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint.txt');
  1208. // this would happen if someone is writing on the mount point
  1209. $mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1210. $thrown = false;
  1211. try {
  1212. // this actually acquires two locks, one on the mount point and one on the storage root,
  1213. // but the one on the storage root will fail
  1214. $view->lockFile('/mountpoint.txt', ILockingProvider::LOCK_SHARED);
  1215. } catch (LockedException $e) {
  1216. $thrown = true;
  1217. }
  1218. $this->assertTrue($thrown, 'Cannot acquire shared lock because storage root is already locked');
  1219. // from here we expect that the lock on the local mount point was released properly
  1220. // so acquiring an exclusive lock will succeed
  1221. $storage->acquireLock('/testuser/files/mountpoint.txt', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1222. $lockingProvider->releaseAll();
  1223. }
  1224. public function dataLockPaths() {
  1225. return [
  1226. ['/testuser/{folder}', ''],
  1227. ['/testuser', '/{folder}'],
  1228. ['', '/testuser/{folder}'],
  1229. ];
  1230. }
  1231. public function pathRelativeToFilesProvider() {
  1232. return [
  1233. ['admin/files', ''],
  1234. ['admin/files/x', 'x'],
  1235. ['/admin/files', ''],
  1236. ['/admin/files/sub', 'sub'],
  1237. ['/admin/files/sub/', 'sub'],
  1238. ['/admin/files/sub/sub2', 'sub/sub2'],
  1239. ['//admin//files/sub//sub2', 'sub/sub2'],
  1240. ];
  1241. }
  1242. /**
  1243. * @dataProvider pathRelativeToFilesProvider
  1244. */
  1245. public function testGetPathRelativeToFiles($path, $expectedPath) {
  1246. $view = new View();
  1247. $this->assertEquals($expectedPath, $view->getPathRelativeToFiles($path));
  1248. }
  1249. public function pathRelativeToFilesProviderExceptionCases() {
  1250. return [
  1251. [''],
  1252. ['x'],
  1253. ['files'],
  1254. ['/files'],
  1255. ['/admin/files_versions/abc'],
  1256. ];
  1257. }
  1258. /**
  1259. * @dataProvider pathRelativeToFilesProviderExceptionCases
  1260. * @param string $path
  1261. */
  1262. public function testGetPathRelativeToFilesWithInvalidArgument($path) {
  1263. $this->expectException(\InvalidArgumentException::class);
  1264. $this->expectExceptionMessage('$absolutePath must be relative to "files"');
  1265. $view = new View();
  1266. $view->getPathRelativeToFiles($path);
  1267. }
  1268. public function testChangeLock() {
  1269. $view = new View('/testuser/files/');
  1270. $storage = new Temporary([]);
  1271. Filesystem::mount($storage, [], '/');
  1272. $view->lockFile('/test/sub', ILockingProvider::LOCK_SHARED);
  1273. $this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
  1274. $this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
  1275. $view->changeLock('//test/sub', ILockingProvider::LOCK_EXCLUSIVE);
  1276. $this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
  1277. $view->changeLock('test/sub', ILockingProvider::LOCK_SHARED);
  1278. $this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
  1279. $view->unlockFile('/test/sub/', ILockingProvider::LOCK_SHARED);
  1280. $this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
  1281. $this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
  1282. }
  1283. public function hookPathProvider() {
  1284. return [
  1285. ['/foo/files', '/foo', true],
  1286. ['/foo/files/bar', '/foo', true],
  1287. ['/foo', '/foo', false],
  1288. ['/foo', '/files/foo', true],
  1289. ['/foo', 'filesfoo', false],
  1290. ['', '/foo/files', true],
  1291. ['', '/foo/files/bar.txt', true],
  1292. ];
  1293. }
  1294. /**
  1295. * @dataProvider hookPathProvider
  1296. * @param $root
  1297. * @param $path
  1298. * @param $shouldEmit
  1299. */
  1300. public function testHookPaths($root, $path, $shouldEmit) {
  1301. $filesystemReflection = new \ReflectionClass(Filesystem::class);
  1302. $defaultRootValue = $filesystemReflection->getProperty('defaultInstance');
  1303. $defaultRootValue->setAccessible(true);
  1304. $oldRoot = $defaultRootValue->getValue();
  1305. $defaultView = new View('/foo/files');
  1306. $defaultRootValue->setValue(null, $defaultView);
  1307. $view = new View($root);
  1308. $result = self::invokePrivate($view, 'shouldEmitHooks', [$path]);
  1309. $defaultRootValue->setValue(null, $oldRoot);
  1310. $this->assertEquals($shouldEmit, $result);
  1311. }
  1312. /**
  1313. * Create test movable mount points
  1314. *
  1315. * @param array $mountPoints array of mount point locations
  1316. * @return array array of MountPoint objects
  1317. */
  1318. private function createTestMovableMountPoints($mountPoints) {
  1319. $mounts = [];
  1320. foreach ($mountPoints as $mountPoint) {
  1321. $storage = $this->getMockBuilder(Storage::class)
  1322. ->setMethods([])
  1323. ->setConstructorArgs([[]])
  1324. ->getMock();
  1325. $storage->method('getId')->willReturn('non-null-id');
  1326. $storage->method('getStorageCache')->willReturnCallback(function () use ($storage) {
  1327. return new \OC\Files\Cache\Storage($storage, true, \OC::$server->get(IDBConnection::class));
  1328. });
  1329. $mounts[] = $this->getMockBuilder(TestMoveableMountPoint::class)
  1330. ->setMethods(['moveMount'])
  1331. ->setConstructorArgs([$storage, $mountPoint])
  1332. ->getMock();
  1333. }
  1334. /** @var IMountProvider|\PHPUnit\Framework\MockObject\MockObject $mountProvider */
  1335. $mountProvider = $this->createMock(IMountProvider::class);
  1336. $mountProvider->expects($this->any())
  1337. ->method('getMountsForUser')
  1338. ->willReturn($mounts);
  1339. $mountProviderCollection = \OC::$server->getMountProviderCollection();
  1340. $mountProviderCollection->registerProvider($mountProvider);
  1341. return $mounts;
  1342. }
  1343. /**
  1344. * Test mount point move
  1345. */
  1346. public function testMountPointMove() {
  1347. self::loginAsUser($this->user);
  1348. [$mount1, $mount2] = $this->createTestMovableMountPoints([
  1349. $this->user . '/files/mount1',
  1350. $this->user . '/files/mount2',
  1351. ]);
  1352. $mount1->expects($this->once())
  1353. ->method('moveMount')
  1354. ->willReturn(true);
  1355. $mount2->expects($this->once())
  1356. ->method('moveMount')
  1357. ->willReturn(true);
  1358. $view = new View('/' . $this->user . '/files/');
  1359. $view->mkdir('sub');
  1360. $this->assertTrue($view->rename('mount1', 'renamed_mount'), 'Can rename mount point');
  1361. $this->assertTrue($view->rename('mount2', 'sub/moved_mount'), 'Can move a mount point into a subdirectory');
  1362. }
  1363. /**
  1364. * Test that moving a mount point into another is forbidden
  1365. */
  1366. public function testMoveMountPointIntoAnother() {
  1367. self::loginAsUser($this->user);
  1368. [$mount1, $mount2] = $this->createTestMovableMountPoints([
  1369. $this->user . '/files/mount1',
  1370. $this->user . '/files/mount2',
  1371. ]);
  1372. $mount1->expects($this->never())
  1373. ->method('moveMount');
  1374. $mount2->expects($this->never())
  1375. ->method('moveMount');
  1376. $view = new View('/' . $this->user . '/files/');
  1377. $this->assertFalse($view->rename('mount1', 'mount2'), 'Cannot overwrite another mount point');
  1378. $this->assertFalse($view->rename('mount1', 'mount2/sub'), 'Cannot move a mount point into another');
  1379. }
  1380. /**
  1381. * Test that moving a mount point into a shared folder is forbidden
  1382. */
  1383. public function testMoveMountPointIntoSharedFolder() {
  1384. self::loginAsUser($this->user);
  1385. [$mount1] = $this->createTestMovableMountPoints([
  1386. $this->user . '/files/mount1',
  1387. ]);
  1388. $mount1->expects($this->never())
  1389. ->method('moveMount');
  1390. $view = new View('/' . $this->user . '/files/');
  1391. $view->mkdir('shareddir');
  1392. $view->mkdir('shareddir/sub');
  1393. $view->mkdir('shareddir/sub2');
  1394. $fileId = $view->getFileInfo('shareddir')->getId();
  1395. $userObject = \OC::$server->getUserManager()->createUser('test2', 'IHateNonMockableStaticClasses');
  1396. $userFolder = \OC::$server->getUserFolder($this->user);
  1397. $shareDir = $userFolder->get('shareddir');
  1398. $shareManager = \OC::$server->get(IShareManager::class);
  1399. $share = $shareManager->newShare();
  1400. $share->setSharedWith('test2')
  1401. ->setSharedBy($this->user)
  1402. ->setShareType(IShare::TYPE_USER)
  1403. ->setPermissions(\OCP\Constants::PERMISSION_READ)
  1404. ->setNode($shareDir);
  1405. $shareManager->createShare($share);
  1406. $this->assertFalse($view->rename('mount1', 'shareddir'), 'Cannot overwrite shared folder');
  1407. $this->assertFalse($view->rename('mount1', 'shareddir/sub'), 'Cannot move mount point into shared folder');
  1408. $this->assertFalse($view->rename('mount1', 'shareddir/sub/sub2'), 'Cannot move mount point into shared subfolder');
  1409. $shareManager->deleteShare($share);
  1410. $userObject->delete();
  1411. }
  1412. public function basicOperationProviderForLocks() {
  1413. return [
  1414. // --- write hook ----
  1415. [
  1416. 'touch',
  1417. ['touch-create.txt'],
  1418. 'touch-create.txt',
  1419. 'create',
  1420. ILockingProvider::LOCK_SHARED,
  1421. ILockingProvider::LOCK_EXCLUSIVE,
  1422. ILockingProvider::LOCK_SHARED,
  1423. ],
  1424. [
  1425. 'fopen',
  1426. ['test-write.txt', 'w'],
  1427. 'test-write.txt',
  1428. 'write',
  1429. ILockingProvider::LOCK_SHARED,
  1430. ILockingProvider::LOCK_EXCLUSIVE,
  1431. null,
  1432. // exclusive lock stays until fclose
  1433. ILockingProvider::LOCK_EXCLUSIVE,
  1434. ],
  1435. [
  1436. 'mkdir',
  1437. ['newdir'],
  1438. 'newdir',
  1439. 'write',
  1440. ILockingProvider::LOCK_SHARED,
  1441. ILockingProvider::LOCK_EXCLUSIVE,
  1442. ILockingProvider::LOCK_SHARED,
  1443. ],
  1444. [
  1445. 'file_put_contents',
  1446. ['file_put_contents.txt', 'blah'],
  1447. 'file_put_contents.txt',
  1448. 'write',
  1449. ILockingProvider::LOCK_SHARED,
  1450. ILockingProvider::LOCK_EXCLUSIVE,
  1451. ILockingProvider::LOCK_SHARED,
  1452. ],
  1453. // ---- delete hook ----
  1454. [
  1455. 'rmdir',
  1456. ['dir'],
  1457. 'dir',
  1458. 'delete',
  1459. ILockingProvider::LOCK_SHARED,
  1460. ILockingProvider::LOCK_EXCLUSIVE,
  1461. ILockingProvider::LOCK_SHARED,
  1462. ],
  1463. [
  1464. 'unlink',
  1465. ['test.txt'],
  1466. 'test.txt',
  1467. 'delete',
  1468. ILockingProvider::LOCK_SHARED,
  1469. ILockingProvider::LOCK_EXCLUSIVE,
  1470. ILockingProvider::LOCK_SHARED,
  1471. ],
  1472. // ---- read hook (no post hooks) ----
  1473. [
  1474. 'file_get_contents',
  1475. ['test.txt'],
  1476. 'test.txt',
  1477. 'read',
  1478. ILockingProvider::LOCK_SHARED,
  1479. ILockingProvider::LOCK_SHARED,
  1480. null,
  1481. ],
  1482. [
  1483. 'fopen',
  1484. ['test.txt', 'r'],
  1485. 'test.txt',
  1486. 'read',
  1487. ILockingProvider::LOCK_SHARED,
  1488. ILockingProvider::LOCK_SHARED,
  1489. null,
  1490. ],
  1491. [
  1492. 'opendir',
  1493. ['dir'],
  1494. 'dir',
  1495. 'read',
  1496. ILockingProvider::LOCK_SHARED,
  1497. ILockingProvider::LOCK_SHARED,
  1498. null,
  1499. ],
  1500. // ---- no lock, touch hook ---
  1501. ['touch', ['test.txt'], 'test.txt', 'touch', null, null, null],
  1502. // ---- no hooks, no locks ---
  1503. ['is_dir', ['dir'], 'dir', null],
  1504. ['is_file', ['dir'], 'dir', null],
  1505. ['stat', ['dir'], 'dir', null],
  1506. ['filetype', ['dir'], 'dir', null],
  1507. [
  1508. 'filesize',
  1509. ['dir'],
  1510. 'dir',
  1511. null,
  1512. ILockingProvider::LOCK_SHARED,
  1513. ILockingProvider::LOCK_SHARED,
  1514. ILockingProvider::LOCK_SHARED,
  1515. null,
  1516. /* Return an int */
  1517. 100
  1518. ],
  1519. ['isCreatable', ['dir'], 'dir', null],
  1520. ['isReadable', ['dir'], 'dir', null],
  1521. ['isUpdatable', ['dir'], 'dir', null],
  1522. ['isDeletable', ['dir'], 'dir', null],
  1523. ['isSharable', ['dir'], 'dir', null],
  1524. ['file_exists', ['dir'], 'dir', null],
  1525. ['filemtime', ['dir'], 'dir', null],
  1526. ];
  1527. }
  1528. /**
  1529. * Test whether locks are set before and after the operation
  1530. *
  1531. * @dataProvider basicOperationProviderForLocks
  1532. *
  1533. * @param string $operation operation name on the view
  1534. * @param array $operationArgs arguments for the operation
  1535. * @param string $lockedPath path of the locked item to check
  1536. * @param string $hookType hook type
  1537. * @param int $expectedLockBefore expected lock during pre hooks
  1538. * @param int $expectedLockDuring expected lock during operation
  1539. * @param int $expectedLockAfter expected lock during post hooks
  1540. * @param int $expectedStrayLock expected lock after returning, should
  1541. * be null (unlock) for most operations
  1542. */
  1543. public function testLockBasicOperation(
  1544. $operation,
  1545. $operationArgs,
  1546. $lockedPath,
  1547. $hookType,
  1548. $expectedLockBefore = ILockingProvider::LOCK_SHARED,
  1549. $expectedLockDuring = ILockingProvider::LOCK_SHARED,
  1550. $expectedLockAfter = ILockingProvider::LOCK_SHARED,
  1551. $expectedStrayLock = null,
  1552. $returnValue = true,
  1553. ) {
  1554. $view = new View('/' . $this->user . '/files/');
  1555. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1556. $storage = $this->getMockBuilder(Temporary::class)
  1557. ->setMethods([$operation])
  1558. ->getMock();
  1559. Filesystem::mount($storage, [], $this->user . '/');
  1560. // work directly on disk because mkdir might be mocked
  1561. $realPath = $storage->getSourcePath('');
  1562. mkdir($realPath . '/files');
  1563. mkdir($realPath . '/files/dir');
  1564. file_put_contents($realPath . '/files/test.txt', 'blah');
  1565. $storage->getScanner()->scan('files');
  1566. $storage->expects($this->once())
  1567. ->method($operation)
  1568. ->willReturnCallback(
  1569. function () use ($view, $lockedPath, &$lockTypeDuring, $returnValue) {
  1570. $lockTypeDuring = $this->getFileLockType($view, $lockedPath);
  1571. return $returnValue;
  1572. }
  1573. );
  1574. $this->assertNull($this->getFileLockType($view, $lockedPath), 'File not locked before operation');
  1575. $this->connectMockHooks($hookType, $view, $lockedPath, $lockTypePre, $lockTypePost);
  1576. // do operation
  1577. call_user_func_array([$view, $operation], $operationArgs);
  1578. if ($hookType !== null) {
  1579. $this->assertEquals($expectedLockBefore, $lockTypePre, 'File locked properly during pre-hook');
  1580. $this->assertEquals($expectedLockAfter, $lockTypePost, 'File locked properly during post-hook');
  1581. $this->assertEquals($expectedLockDuring, $lockTypeDuring, 'File locked properly during operation');
  1582. } else {
  1583. $this->assertNull($lockTypeDuring, 'File not locked during operation');
  1584. }
  1585. $this->assertEquals($expectedStrayLock, $this->getFileLockType($view, $lockedPath));
  1586. }
  1587. /**
  1588. * Test locks for file_put_content with stream.
  1589. * This code path uses $storage->fopen instead
  1590. */
  1591. public function testLockFilePutContentWithStream() {
  1592. $view = new View('/' . $this->user . '/files/');
  1593. $path = 'test_file_put_contents.txt';
  1594. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1595. $storage = $this->getMockBuilder(Temporary::class)
  1596. ->setMethods(['fopen'])
  1597. ->getMock();
  1598. Filesystem::mount($storage, [], $this->user . '/');
  1599. $storage->mkdir('files');
  1600. $storage->expects($this->once())
  1601. ->method('fopen')
  1602. ->willReturnCallback(
  1603. function () use ($view, $path, &$lockTypeDuring) {
  1604. $lockTypeDuring = $this->getFileLockType($view, $path);
  1605. return fopen('php://temp', 'r+');
  1606. }
  1607. );
  1608. $this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);
  1609. $this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');
  1610. // do operation
  1611. $view->file_put_contents($path, fopen('php://temp', 'r+'));
  1612. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
  1613. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePost, 'File locked properly during post-hook');
  1614. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');
  1615. $this->assertNull($this->getFileLockType($view, $path));
  1616. }
  1617. /**
  1618. * Test locks for fopen with fclose at the end
  1619. */
  1620. public function testLockFopen() {
  1621. $view = new View('/' . $this->user . '/files/');
  1622. $path = 'test_file_put_contents.txt';
  1623. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1624. $storage = $this->getMockBuilder(Temporary::class)
  1625. ->setMethods(['fopen'])
  1626. ->getMock();
  1627. Filesystem::mount($storage, [], $this->user . '/');
  1628. $storage->mkdir('files');
  1629. $storage->expects($this->once())
  1630. ->method('fopen')
  1631. ->willReturnCallback(
  1632. function () use ($view, $path, &$lockTypeDuring) {
  1633. $lockTypeDuring = $this->getFileLockType($view, $path);
  1634. return fopen('php://temp', 'r+');
  1635. }
  1636. );
  1637. $this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);
  1638. $this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');
  1639. // do operation
  1640. $res = $view->fopen($path, 'w');
  1641. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
  1642. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');
  1643. $this->assertNull($lockTypePost, 'No post hook, no lock check possible');
  1644. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File still locked after fopen');
  1645. fclose($res);
  1646. $this->assertNull($this->getFileLockType($view, $path), 'File unlocked after fclose');
  1647. }
  1648. /**
  1649. * Test locks for fopen with fclose at the end
  1650. *
  1651. * @dataProvider basicOperationProviderForLocks
  1652. *
  1653. * @param string $operation operation name on the view
  1654. * @param array $operationArgs arguments for the operation
  1655. * @param string $path path of the locked item to check
  1656. */
  1657. public function testLockBasicOperationUnlocksAfterException(
  1658. $operation,
  1659. $operationArgs,
  1660. $path
  1661. ) {
  1662. if ($operation === 'touch') {
  1663. $this->markTestSkipped("touch handles storage exceptions internally");
  1664. }
  1665. $view = new View('/' . $this->user . '/files/');
  1666. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1667. $storage = $this->getMockBuilder(Temporary::class)
  1668. ->setMethods([$operation])
  1669. ->getMock();
  1670. Filesystem::mount($storage, [], $this->user . '/');
  1671. // work directly on disk because mkdir might be mocked
  1672. $realPath = $storage->getSourcePath('');
  1673. mkdir($realPath . '/files');
  1674. mkdir($realPath . '/files/dir');
  1675. file_put_contents($realPath . '/files/test.txt', 'blah');
  1676. $storage->getScanner()->scan('files');
  1677. $storage->expects($this->once())
  1678. ->method($operation)
  1679. ->willReturnCallback(
  1680. function () {
  1681. throw new \Exception('Simulated exception');
  1682. }
  1683. );
  1684. $thrown = false;
  1685. try {
  1686. call_user_func_array([$view, $operation], $operationArgs);
  1687. } catch (\Exception $e) {
  1688. $thrown = true;
  1689. $this->assertEquals('Simulated exception', $e->getMessage());
  1690. }
  1691. $this->assertTrue($thrown, 'Exception was rethrown');
  1692. $this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
  1693. }
  1694. public function testLockBasicOperationUnlocksAfterLockException() {
  1695. $view = new View('/' . $this->user . '/files/');
  1696. $storage = new Temporary([]);
  1697. Filesystem::mount($storage, [], $this->user . '/');
  1698. $storage->mkdir('files');
  1699. $storage->mkdir('files/dir');
  1700. $storage->file_put_contents('files/test.txt', 'blah');
  1701. $storage->getScanner()->scan('files');
  1702. // get a shared lock
  1703. $handle = $view->fopen('test.txt', 'r');
  1704. $thrown = false;
  1705. try {
  1706. // try (and fail) to get a write lock
  1707. $view->unlink('test.txt');
  1708. } catch (\Exception $e) {
  1709. $thrown = true;
  1710. $this->assertInstanceOf(LockedException::class, $e);
  1711. }
  1712. $this->assertTrue($thrown, 'Exception was rethrown');
  1713. // clean shared lock
  1714. fclose($handle);
  1715. $this->assertNull($this->getFileLockType($view, 'test.txt'), 'File got unlocked');
  1716. }
  1717. /**
  1718. * Test locks for fopen with fclose at the end
  1719. *
  1720. * @dataProvider basicOperationProviderForLocks
  1721. *
  1722. * @param string $operation operation name on the view
  1723. * @param array $operationArgs arguments for the operation
  1724. * @param string $path path of the locked item to check
  1725. * @param string $hookType hook type
  1726. */
  1727. public function testLockBasicOperationUnlocksAfterCancelledHook(
  1728. $operation,
  1729. $operationArgs,
  1730. $path,
  1731. $hookType
  1732. ) {
  1733. $view = new View('/' . $this->user . '/files/');
  1734. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1735. $storage = $this->getMockBuilder(Temporary::class)
  1736. ->setMethods([$operation])
  1737. ->getMock();
  1738. Filesystem::mount($storage, [], $this->user . '/');
  1739. $storage->mkdir('files');
  1740. Util::connectHook(
  1741. Filesystem::CLASSNAME,
  1742. $hookType,
  1743. HookHelper::class,
  1744. 'cancellingCallback'
  1745. );
  1746. call_user_func_array([$view, $operation], $operationArgs);
  1747. $this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
  1748. }
  1749. public function lockFileRenameOrCopyDataProvider() {
  1750. return [
  1751. ['rename', ILockingProvider::LOCK_EXCLUSIVE],
  1752. ['copy', ILockingProvider::LOCK_SHARED],
  1753. ];
  1754. }
  1755. /**
  1756. * Test locks for rename or copy operation
  1757. *
  1758. * @dataProvider lockFileRenameOrCopyDataProvider
  1759. *
  1760. * @param string $operation operation to be done on the view
  1761. * @param int $expectedLockTypeSourceDuring expected lock type on source file during
  1762. * the operation
  1763. */
  1764. public function testLockFileRename($operation, $expectedLockTypeSourceDuring) {
  1765. $view = new View('/' . $this->user . '/files/');
  1766. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1767. $storage = $this->getMockBuilder(Temporary::class)
  1768. ->setMethods([$operation, 'getMetaData', 'filemtime'])
  1769. ->getMock();
  1770. $storage->expects($this->any())
  1771. ->method('getMetaData')
  1772. ->will($this->returnValue([
  1773. 'mtime' => 1885434487,
  1774. 'etag' => '',
  1775. 'mimetype' => 'text/plain',
  1776. 'permissions' => Constants::PERMISSION_ALL,
  1777. 'size' => 3
  1778. ]));
  1779. $storage->expects($this->any())
  1780. ->method('filemtime')
  1781. ->willReturn(123456789);
  1782. $sourcePath = 'original.txt';
  1783. $targetPath = 'target.txt';
  1784. Filesystem::mount($storage, [], $this->user . '/');
  1785. $storage->mkdir('files');
  1786. $view->file_put_contents($sourcePath, 'meh');
  1787. $storage->expects($this->once())
  1788. ->method($operation)
  1789. ->willReturnCallback(
  1790. function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
  1791. $lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
  1792. $lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);
  1793. return true;
  1794. }
  1795. );
  1796. $this->connectMockHooks($operation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
  1797. $this->connectMockHooks($operation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
  1798. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1799. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
  1800. $view->$operation($sourcePath, $targetPath);
  1801. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
  1802. $this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
  1803. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');
  1804. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
  1805. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
  1806. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');
  1807. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1808. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
  1809. }
  1810. /**
  1811. * simulate a failed copy operation.
  1812. * We expect that we catch the exception, free the lock and re-throw it.
  1813. *
  1814. */
  1815. public function testLockFileCopyException() {
  1816. $this->expectException(\Exception::class);
  1817. $view = new View('/' . $this->user . '/files/');
  1818. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1819. $storage = $this->getMockBuilder(Temporary::class)
  1820. ->setMethods(['copy'])
  1821. ->getMock();
  1822. $sourcePath = 'original.txt';
  1823. $targetPath = 'target.txt';
  1824. Filesystem::mount($storage, [], $this->user . '/');
  1825. $storage->mkdir('files');
  1826. $view->file_put_contents($sourcePath, 'meh');
  1827. $storage->expects($this->once())
  1828. ->method('copy')
  1829. ->willReturnCallback(
  1830. function () {
  1831. throw new \Exception();
  1832. }
  1833. );
  1834. $this->connectMockHooks('copy', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
  1835. $this->connectMockHooks('copy', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
  1836. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1837. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
  1838. try {
  1839. $view->copy($sourcePath, $targetPath);
  1840. } catch (\Exception $e) {
  1841. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1842. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
  1843. throw $e;
  1844. }
  1845. }
  1846. /**
  1847. * Test rename operation: unlock first path when second path was locked
  1848. */
  1849. public function testLockFileRenameUnlockOnException() {
  1850. self::loginAsUser('test');
  1851. $view = new View('/' . $this->user . '/files/');
  1852. $sourcePath = 'original.txt';
  1853. $targetPath = 'target.txt';
  1854. $view->file_put_contents($sourcePath, 'meh');
  1855. // simulate that the target path is already locked
  1856. $view->lockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
  1857. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1858. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file is locked before operation');
  1859. $thrown = false;
  1860. try {
  1861. $view->rename($sourcePath, $targetPath);
  1862. } catch (LockedException $e) {
  1863. $thrown = true;
  1864. }
  1865. $this->assertTrue($thrown, 'LockedException thrown');
  1866. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1867. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file still locked after operation');
  1868. $view->unlockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
  1869. }
  1870. /**
  1871. * Test rename operation: unlock first path when second path was locked
  1872. */
  1873. public function testGetOwner() {
  1874. self::loginAsUser('test');
  1875. $view = new View('/test/files/');
  1876. $path = 'foo.txt';
  1877. $view->file_put_contents($path, 'meh');
  1878. $this->assertEquals('test', $view->getFileInfo($path)->getOwner()->getUID());
  1879. $folderInfo = $view->getDirectoryContent('');
  1880. $folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
  1881. return $info->getName() === 'foo.txt';
  1882. }));
  1883. $this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());
  1884. $subStorage = new Temporary();
  1885. Filesystem::mount($subStorage, [], '/test/files/asd');
  1886. $folderInfo = $view->getDirectoryContent('');
  1887. $folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
  1888. return $info->getName() === 'asd';
  1889. }));
  1890. $this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());
  1891. }
  1892. public function lockFileRenameOrCopyCrossStorageDataProvider() {
  1893. return [
  1894. ['rename', 'moveFromStorage', ILockingProvider::LOCK_EXCLUSIVE],
  1895. ['copy', 'copyFromStorage', ILockingProvider::LOCK_SHARED],
  1896. ];
  1897. }
  1898. /**
  1899. * Test locks for rename or copy operation cross-storage
  1900. *
  1901. * @dataProvider lockFileRenameOrCopyCrossStorageDataProvider
  1902. *
  1903. * @param string $viewOperation operation to be done on the view
  1904. * @param string $storageOperation operation to be mocked on the storage
  1905. * @param int $expectedLockTypeSourceDuring expected lock type on source file during
  1906. * the operation
  1907. */
  1908. public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring) {
  1909. $view = new View('/' . $this->user . '/files/');
  1910. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1911. $storage = $this->getMockBuilder(Temporary::class)
  1912. ->setMethods([$storageOperation])
  1913. ->getMock();
  1914. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage2 */
  1915. $storage2 = $this->getMockBuilder(Temporary::class)
  1916. ->setMethods([$storageOperation, 'getMetaData', 'filemtime'])
  1917. ->getMock();
  1918. $storage2->expects($this->any())
  1919. ->method('getMetaData')
  1920. ->will($this->returnValue([
  1921. 'mtime' => 1885434487,
  1922. 'etag' => '',
  1923. 'mimetype' => 'text/plain',
  1924. 'permissions' => Constants::PERMISSION_ALL,
  1925. 'size' => 3
  1926. ]));
  1927. $storage2->expects($this->any())
  1928. ->method('filemtime')
  1929. ->willReturn(123456789);
  1930. $sourcePath = 'original.txt';
  1931. $targetPath = 'substorage/target.txt';
  1932. Filesystem::mount($storage, [], $this->user . '/');
  1933. Filesystem::mount($storage2, [], $this->user . '/files/substorage');
  1934. $storage->mkdir('files');
  1935. $view->file_put_contents($sourcePath, 'meh');
  1936. $storage->expects($this->never())
  1937. ->method($storageOperation);
  1938. $storage2->expects($this->once())
  1939. ->method($storageOperation)
  1940. ->willReturnCallback(
  1941. function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
  1942. $lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
  1943. $lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);
  1944. return true;
  1945. }
  1946. );
  1947. $this->connectMockHooks($viewOperation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
  1948. $this->connectMockHooks($viewOperation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
  1949. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1950. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
  1951. $view->$viewOperation($sourcePath, $targetPath);
  1952. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
  1953. $this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
  1954. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');
  1955. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
  1956. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
  1957. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');
  1958. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1959. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
  1960. }
  1961. /**
  1962. * Test locks when moving a mount point
  1963. */
  1964. public function testLockMoveMountPoint() {
  1965. self::loginAsUser('test');
  1966. [$mount] = $this->createTestMovableMountPoints([
  1967. $this->user . '/files/substorage',
  1968. ]);
  1969. $view = new View('/' . $this->user . '/files/');
  1970. $view->mkdir('subdir');
  1971. $sourcePath = 'substorage';
  1972. $targetPath = 'subdir/substorage_moved';
  1973. $mount->expects($this->once())
  1974. ->method('moveMount')
  1975. ->willReturnCallback(
  1976. function ($target) use ($mount, $view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring, &$lockTypeSharedRootDuring) {
  1977. $lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath, true);
  1978. $lockTypeTargetDuring = $this->getFileLockType($view, $targetPath, true);
  1979. $lockTypeSharedRootDuring = $this->getFileLockType($view, $sourcePath, false);
  1980. $mount->setMountPoint($target);
  1981. return true;
  1982. }
  1983. );
  1984. $this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost, true);
  1985. $this->connectMockHooks('rename', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost, true);
  1986. // in pre-hook, mount point is still on $sourcePath
  1987. $this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSharedRootPre, $dummy, false);
  1988. // in post-hook, mount point is now on $targetPath
  1989. $this->connectMockHooks('rename', $view, $targetPath, $dummy, $lockTypeSharedRootPost, false);
  1990. $this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked before operation');
  1991. $this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked before operation');
  1992. $this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked before operation');
  1993. $view->rename($sourcePath, $targetPath);
  1994. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source path locked properly during pre-hook');
  1995. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeSourceDuring, 'Source path locked properly during operation');
  1996. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source path locked properly during post-hook');
  1997. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target path locked properly during pre-hook');
  1998. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target path locked properly during operation');
  1999. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target path locked properly during post-hook');
  2000. $this->assertNull($lockTypeSharedRootPre, 'Shared storage root not locked during pre-hook');
  2001. $this->assertNull($lockTypeSharedRootDuring, 'Shared storage root not locked during move');
  2002. $this->assertNull($lockTypeSharedRootPost, 'Shared storage root not locked during post-hook');
  2003. $this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked after operation');
  2004. $this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked after operation');
  2005. $this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked after operation');
  2006. }
  2007. /**
  2008. * Connect hook callbacks for hook type
  2009. *
  2010. * @param string $hookType hook type or null for none
  2011. * @param View $view view to check the lock on
  2012. * @param string $path path for which to check the lock
  2013. * @param int $lockTypePre variable to receive lock type that was active in the pre-hook
  2014. * @param int $lockTypePost variable to receive lock type that was active in the post-hook
  2015. * @param bool $onMountPoint true to check the mount point instead of the
  2016. * mounted storage
  2017. */
  2018. private function connectMockHooks($hookType, $view, $path, &$lockTypePre, &$lockTypePost, $onMountPoint = false) {
  2019. if ($hookType === null) {
  2020. return;
  2021. }
  2022. $eventHandler = $this->getMockBuilder(\stdclass::class)
  2023. ->setMethods(['preCallback', 'postCallback'])
  2024. ->getMock();
  2025. $eventHandler->expects($this->any())
  2026. ->method('preCallback')
  2027. ->willReturnCallback(
  2028. function () use ($view, $path, $onMountPoint, &$lockTypePre) {
  2029. $lockTypePre = $this->getFileLockType($view, $path, $onMountPoint);
  2030. }
  2031. );
  2032. $eventHandler->expects($this->any())
  2033. ->method('postCallback')
  2034. ->willReturnCallback(
  2035. function () use ($view, $path, $onMountPoint, &$lockTypePost) {
  2036. $lockTypePost = $this->getFileLockType($view, $path, $onMountPoint);
  2037. }
  2038. );
  2039. if ($hookType !== null) {
  2040. Util::connectHook(
  2041. Filesystem::CLASSNAME,
  2042. $hookType,
  2043. $eventHandler,
  2044. 'preCallback'
  2045. );
  2046. Util::connectHook(
  2047. Filesystem::CLASSNAME,
  2048. 'post_' . $hookType,
  2049. $eventHandler,
  2050. 'postCallback'
  2051. );
  2052. }
  2053. }
  2054. /**
  2055. * Returns the file lock type
  2056. *
  2057. * @param View $view view
  2058. * @param string $path path
  2059. * @param bool $onMountPoint true to check the mount point instead of the
  2060. * mounted storage
  2061. *
  2062. * @return int lock type or null if file was not locked
  2063. */
  2064. private function getFileLockType(View $view, $path, $onMountPoint = false) {
  2065. if ($this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE, $onMountPoint)) {
  2066. return ILockingProvider::LOCK_EXCLUSIVE;
  2067. } elseif ($this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED, $onMountPoint)) {
  2068. return ILockingProvider::LOCK_SHARED;
  2069. }
  2070. return null;
  2071. }
  2072. public function testRemoveMoveableMountPoint() {
  2073. $mountPoint = '/' . $this->user . '/files/mount/';
  2074. // Mock the mount point
  2075. /** @var TestMoveableMountPoint|\PHPUnit\Framework\MockObject\MockObject $mount */
  2076. $mount = $this->createMock(TestMoveableMountPoint::class);
  2077. $mount->expects($this->once())
  2078. ->method('getMountPoint')
  2079. ->willReturn($mountPoint);
  2080. $mount->expects($this->once())
  2081. ->method('removeMount')
  2082. ->willReturn('foo');
  2083. $mount->expects($this->any())
  2084. ->method('getInternalPath')
  2085. ->willReturn('');
  2086. // Register mount
  2087. Filesystem::getMountManager()->addMount($mount);
  2088. // Listen for events
  2089. $eventHandler = $this->getMockBuilder(\stdclass::class)
  2090. ->setMethods(['umount', 'post_umount'])
  2091. ->getMock();
  2092. $eventHandler->expects($this->once())
  2093. ->method('umount')
  2094. ->with([Filesystem::signal_param_path => '/mount']);
  2095. $eventHandler->expects($this->once())
  2096. ->method('post_umount')
  2097. ->with([Filesystem::signal_param_path => '/mount']);
  2098. Util::connectHook(
  2099. Filesystem::CLASSNAME,
  2100. 'umount',
  2101. $eventHandler,
  2102. 'umount'
  2103. );
  2104. Util::connectHook(
  2105. Filesystem::CLASSNAME,
  2106. 'post_umount',
  2107. $eventHandler,
  2108. 'post_umount'
  2109. );
  2110. //Delete the mountpoint
  2111. $view = new View('/' . $this->user . '/files');
  2112. $this->assertEquals('foo', $view->rmdir('mount'));
  2113. }
  2114. public function mimeFilterProvider() {
  2115. return [
  2116. [null, ['test1.txt', 'test2.txt', 'test3.md', 'test4.png']],
  2117. ['text/plain', ['test1.txt', 'test2.txt']],
  2118. ['text/markdown', ['test3.md']],
  2119. ['text', ['test1.txt', 'test2.txt', 'test3.md']],
  2120. ];
  2121. }
  2122. /**
  2123. * @param string $filter
  2124. * @param string[] $expected
  2125. * @dataProvider mimeFilterProvider
  2126. */
  2127. public function testGetDirectoryContentMimeFilter($filter, $expected) {
  2128. $storage1 = new Temporary();
  2129. $root = self::getUniqueID('/');
  2130. Filesystem::mount($storage1, [], $root . '/');
  2131. $view = new View($root);
  2132. $view->file_put_contents('test1.txt', 'asd');
  2133. $view->file_put_contents('test2.txt', 'asd');
  2134. $view->file_put_contents('test3.md', 'asd');
  2135. $view->file_put_contents('test4.png', '');
  2136. $content = $view->getDirectoryContent('', $filter);
  2137. $files = array_map(function (FileInfo $info) {
  2138. return $info->getName();
  2139. }, $content);
  2140. sort($files);
  2141. $this->assertEquals($expected, $files);
  2142. }
  2143. public function testFilePutContentsClearsChecksum() {
  2144. $storage = new Temporary([]);
  2145. $scanner = $storage->getScanner();
  2146. $storage->file_put_contents('foo.txt', 'bar');
  2147. Filesystem::mount($storage, [], '/test/');
  2148. $scanner->scan('');
  2149. $view = new View('/test/foo.txt');
  2150. $view->putFileInfo('.', ['checksum' => '42']);
  2151. $this->assertEquals('bar', $view->file_get_contents(''));
  2152. $fh = tmpfile();
  2153. fwrite($fh, 'fooo');
  2154. rewind($fh);
  2155. clearstatcache();
  2156. $view->file_put_contents('', $fh);
  2157. $this->assertEquals('fooo', $view->file_get_contents(''));
  2158. $data = $view->getFileInfo('.');
  2159. $this->assertEquals('', $data->getChecksum());
  2160. }
  2161. public function testDeleteGhostFile() {
  2162. $storage = new Temporary([]);
  2163. $scanner = $storage->getScanner();
  2164. $cache = $storage->getCache();
  2165. $storage->file_put_contents('foo.txt', 'bar');
  2166. Filesystem::mount($storage, [], '/test/');
  2167. $scanner->scan('');
  2168. $storage->unlink('foo.txt');
  2169. $this->assertTrue($cache->inCache('foo.txt'));
  2170. $view = new View('/test');
  2171. $rootInfo = $view->getFileInfo('');
  2172. $this->assertEquals(3, $rootInfo->getSize());
  2173. $view->unlink('foo.txt');
  2174. $newInfo = $view->getFileInfo('');
  2175. $this->assertFalse($cache->inCache('foo.txt'));
  2176. $this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
  2177. $this->assertEquals(0, $newInfo->getSize());
  2178. }
  2179. public function testDeleteGhostFolder() {
  2180. $storage = new Temporary([]);
  2181. $scanner = $storage->getScanner();
  2182. $cache = $storage->getCache();
  2183. $storage->mkdir('foo');
  2184. $storage->file_put_contents('foo/foo.txt', 'bar');
  2185. Filesystem::mount($storage, [], '/test/');
  2186. $scanner->scan('');
  2187. $storage->rmdir('foo');
  2188. $this->assertTrue($cache->inCache('foo'));
  2189. $this->assertTrue($cache->inCache('foo/foo.txt'));
  2190. $view = new View('/test');
  2191. $rootInfo = $view->getFileInfo('');
  2192. $this->assertEquals(3, $rootInfo->getSize());
  2193. $view->rmdir('foo');
  2194. $newInfo = $view->getFileInfo('');
  2195. $this->assertFalse($cache->inCache('foo'));
  2196. $this->assertFalse($cache->inCache('foo/foo.txt'));
  2197. $this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
  2198. $this->assertEquals(0, $newInfo->getSize());
  2199. }
  2200. public function testCreateParentDirectories() {
  2201. $view = $this->getMockBuilder(View::class)
  2202. ->disableOriginalConstructor()
  2203. ->setMethods([
  2204. 'is_file',
  2205. 'file_exists',
  2206. 'mkdir',
  2207. ])
  2208. ->getMock();
  2209. $view->expects($this->exactly(3))
  2210. ->method('is_file')
  2211. ->withConsecutive(
  2212. ['/new'],
  2213. ['/new/folder'],
  2214. ['/new/folder/structure'],
  2215. )
  2216. ->willReturn(false);
  2217. $view->expects($this->exactly(3))
  2218. ->method('file_exists')
  2219. ->withConsecutive(
  2220. ['/new'],
  2221. ['/new/folder'],
  2222. ['/new/folder/structure'],
  2223. )->willReturnOnConsecutiveCalls(
  2224. true,
  2225. false,
  2226. false,
  2227. );
  2228. $view->expects($this->exactly(2))
  2229. ->method('mkdir')
  2230. ->withConsecutive(
  2231. ['/new/folder'],
  2232. ['/new/folder/structure'],
  2233. );
  2234. $this->assertTrue(self::invokePrivate($view, 'createParentDirectories', ['/new/folder/structure']));
  2235. }
  2236. public function testCreateParentDirectoriesWithExistingFile() {
  2237. $view = $this->getMockBuilder(View::class)
  2238. ->disableOriginalConstructor()
  2239. ->setMethods([
  2240. 'is_file',
  2241. 'file_exists',
  2242. 'mkdir',
  2243. ])
  2244. ->getMock();
  2245. $view
  2246. ->expects($this->once())
  2247. ->method('is_file')
  2248. ->with('/file.txt')
  2249. ->willReturn(true);
  2250. $this->assertFalse(self::invokePrivate($view, 'createParentDirectories', ['/file.txt/folder/structure']));
  2251. }
  2252. public function testCacheExtension() {
  2253. $storage = new Temporary([]);
  2254. $scanner = $storage->getScanner();
  2255. $storage->file_put_contents('foo.txt', 'bar');
  2256. $scanner->scan('');
  2257. Filesystem::mount($storage, [], '/test/');
  2258. $view = new View('/test');
  2259. $info = $view->getFileInfo('/foo.txt');
  2260. $this->assertEquals(0, $info->getUploadTime());
  2261. $this->assertEquals(0, $info->getCreationTime());
  2262. $view->putFileInfo('/foo.txt', ['upload_time' => 25]);
  2263. $info = $view->getFileInfo('/foo.txt');
  2264. $this->assertEquals(25, $info->getUploadTime());
  2265. $this->assertEquals(0, $info->getCreationTime());
  2266. }
  2267. public function testFopenGone() {
  2268. $storage = new Temporary([]);
  2269. $scanner = $storage->getScanner();
  2270. $storage->file_put_contents('foo.txt', 'bar');
  2271. $scanner->scan('');
  2272. $cache = $storage->getCache();
  2273. Filesystem::mount($storage, [], '/test/');
  2274. $view = new View('/test');
  2275. $storage->unlink('foo.txt');
  2276. $this->assertTrue($cache->inCache('foo.txt'));
  2277. $this->assertFalse($view->fopen('foo.txt', 'r'));
  2278. $this->assertFalse($cache->inCache('foo.txt'));
  2279. }
  2280. }