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

ViewTest.php 85KB

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