ViewTest.php 85 KB

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