ViewTest.php 84 KB

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