ViewTest.php 85 KB

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