ViewTest.php 85 KB

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