ViewTest.php 83 KB

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