ViewTest.php 84 KB

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