ViewTest.php 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712
  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\Mount\MountPoint;
  12. use OC\Files\Storage\Common;
  13. use OC\Files\Storage\Temporary;
  14. use OC\Files\View;
  15. use OCP\Constants;
  16. use OCP\Files\Config\IMountProvider;
  17. use OCP\Files\FileInfo;
  18. use OCP\Files\GenericFileException;
  19. use OCP\Files\Storage\IStorage;
  20. use OCP\Lock\ILockingProvider;
  21. use OCP\Lock\LockedException;
  22. use OCP\Share\IShare;
  23. use OCP\Util;
  24. use Test\HookHelper;
  25. use Test\TestMoveableMountPoint;
  26. use Test\Traits\UserTrait;
  27. class TemporaryNoTouch extends Temporary {
  28. public function touch($path, $mtime = null) {
  29. return false;
  30. }
  31. }
  32. class TemporaryNoCross extends Temporary {
  33. public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime = null) {
  34. return Common::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath, $preserveMtime);
  35. }
  36. public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) {
  37. return Common::moveFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  38. }
  39. }
  40. class TemporaryNoLocal extends Temporary {
  41. public function instanceOfStorage($className) {
  42. if ($className === '\OC\Files\Storage\Local') {
  43. return false;
  44. } else {
  45. return parent::instanceOfStorage($className);
  46. }
  47. }
  48. }
  49. /**
  50. * Class ViewTest
  51. *
  52. * @group DB
  53. *
  54. * @package Test\Files
  55. */
  56. class ViewTest extends \Test\TestCase {
  57. use UserTrait;
  58. /**
  59. * @var \OC\Files\Storage\Storage[] $storages
  60. */
  61. private $storages = [];
  62. /**
  63. * @var string
  64. */
  65. private $user;
  66. /**
  67. * @var \OCP\IUser
  68. */
  69. private $userObject;
  70. /**
  71. * @var \OCP\IGroup
  72. */
  73. private $groupObject;
  74. /** @var \OC\Files\Storage\Storage */
  75. private $tempStorage;
  76. protected function setUp(): void {
  77. parent::setUp();
  78. \OC_Hook::clear();
  79. \OC_User::clearBackends();
  80. \OC_User::useBackend(new \Test\Util\User\Dummy());
  81. //login
  82. $userManager = \OC::$server->getUserManager();
  83. $groupManager = \OC::$server->getGroupManager();
  84. $this->user = 'test';
  85. $this->userObject = $userManager->createUser('test', 'test');
  86. $this->groupObject = $groupManager->createGroup('group1');
  87. $this->groupObject->addUser($this->userObject);
  88. self::loginAsUser($this->user);
  89. // clear mounts but somehow keep the root storage
  90. // that was initialized above...
  91. Filesystem::clearMounts();
  92. $this->tempStorage = null;
  93. }
  94. protected function tearDown(): void {
  95. \OC_User::setUserId($this->user);
  96. foreach ($this->storages as $storage) {
  97. $cache = $storage->getCache();
  98. $ids = $cache->getAll();
  99. $cache->clear();
  100. }
  101. if ($this->tempStorage) {
  102. system('rm -rf ' . escapeshellarg($this->tempStorage->getDataDir()));
  103. }
  104. self::logout();
  105. $this->userObject->delete();
  106. $this->groupObject->delete();
  107. $mountProviderCollection = \OC::$server->getMountProviderCollection();
  108. self::invokePrivate($mountProviderCollection, 'providers', [[]]);
  109. parent::tearDown();
  110. }
  111. /**
  112. * @medium
  113. */
  114. public function testCacheAPI() {
  115. $storage1 = $this->getTestStorage();
  116. $storage2 = $this->getTestStorage();
  117. $storage3 = $this->getTestStorage();
  118. $root = self::getUniqueID('/');
  119. Filesystem::mount($storage1, [], $root . '/');
  120. Filesystem::mount($storage2, [], $root . '/substorage');
  121. Filesystem::mount($storage3, [], $root . '/folder/anotherstorage');
  122. $textSize = strlen("dummy file data\n");
  123. $imageSize = filesize(\OC::$SERVERROOT . '/core/img/logo/logo.png');
  124. $storageSize = $textSize * 2 + $imageSize;
  125. $storageInfo = $storage3->getCache()->get('');
  126. $this->assertEquals($storageSize, $storageInfo['size']);
  127. $rootView = new View($root);
  128. $cachedData = $rootView->getFileInfo('/foo.txt');
  129. $this->assertEquals($textSize, $cachedData['size']);
  130. $this->assertEquals('text/plain', $cachedData['mimetype']);
  131. $this->assertNotEquals(-1, $cachedData['permissions']);
  132. $cachedData = $rootView->getFileInfo('/');
  133. $this->assertEquals($storageSize * 3, $cachedData['size']);
  134. $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
  135. // get cached data excluding mount points
  136. $cachedData = $rootView->getFileInfo('/', false);
  137. $this->assertEquals($storageSize, $cachedData['size']);
  138. $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
  139. $cachedData = $rootView->getFileInfo('/folder');
  140. $this->assertEquals($storageSize + $textSize, $cachedData['size']);
  141. $this->assertEquals('httpd/unix-directory', $cachedData['mimetype']);
  142. $folderData = $rootView->getDirectoryContent('/');
  143. /**
  144. * expected entries:
  145. * folder
  146. * foo.png
  147. * foo.txt
  148. * substorage
  149. */
  150. $this->assertCount(4, $folderData);
  151. $this->assertEquals('folder', $folderData[0]['name']);
  152. $this->assertEquals('foo.png', $folderData[1]['name']);
  153. $this->assertEquals('foo.txt', $folderData[2]['name']);
  154. $this->assertEquals('substorage', $folderData[3]['name']);
  155. $this->assertEquals($storageSize + $textSize, $folderData[0]['size']);
  156. $this->assertEquals($imageSize, $folderData[1]['size']);
  157. $this->assertEquals($textSize, $folderData[2]['size']);
  158. $this->assertEquals($storageSize, $folderData[3]['size']);
  159. $folderData = $rootView->getDirectoryContent('/substorage');
  160. /**
  161. * expected entries:
  162. * folder
  163. * foo.png
  164. * foo.txt
  165. */
  166. $this->assertCount(3, $folderData);
  167. $this->assertEquals('folder', $folderData[0]['name']);
  168. $this->assertEquals('foo.png', $folderData[1]['name']);
  169. $this->assertEquals('foo.txt', $folderData[2]['name']);
  170. $folderView = new View($root . '/folder');
  171. $this->assertEquals($rootView->getFileInfo('/folder'), $folderView->getFileInfo('/'));
  172. $cachedData = $rootView->getFileInfo('/foo.txt');
  173. $this->assertFalse($cachedData['encrypted']);
  174. $id = $rootView->putFileInfo('/foo.txt', ['encrypted' => true]);
  175. $cachedData = $rootView->getFileInfo('/foo.txt');
  176. $this->assertTrue($cachedData['encrypted']);
  177. $this->assertEquals($cachedData['fileid'], $id);
  178. $this->assertFalse($rootView->getFileInfo('/non/existing'));
  179. $this->assertEquals([], $rootView->getDirectoryContent('/non/existing'));
  180. }
  181. /**
  182. * @medium
  183. */
  184. public function testGetPath() {
  185. $storage1 = $this->getTestStorage();
  186. $storage2 = $this->getTestStorage();
  187. $storage3 = $this->getTestStorage();
  188. Filesystem::mount($storage1, [], '/');
  189. Filesystem::mount($storage2, [], '/substorage');
  190. Filesystem::mount($storage3, [], '/folder/anotherstorage');
  191. $rootView = new View('');
  192. $cachedData = $rootView->getFileInfo('/foo.txt');
  193. /** @var int $id1 */
  194. $id1 = $cachedData['fileid'];
  195. $this->assertEquals('/foo.txt', $rootView->getPath($id1));
  196. $cachedData = $rootView->getFileInfo('/substorage/foo.txt');
  197. /** @var int $id2 */
  198. $id2 = $cachedData['fileid'];
  199. $this->assertEquals('/substorage/foo.txt', $rootView->getPath($id2));
  200. $folderView = new View('/substorage');
  201. $this->assertEquals('/foo.txt', $folderView->getPath($id2));
  202. }
  203. public function testGetPathNotExisting() {
  204. $this->expectException(\OCP\Files\NotFoundException::class);
  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, [], '/');
  222. Filesystem::mount($storage2, [], '/substorage');
  223. $rootView = new View('');
  224. $folderContent = $rootView->getDirectoryContent('/');
  225. $this->assertCount(4, $folderContent);
  226. }
  227. public function sharingDisabledPermissionProvider() {
  228. return [
  229. ['no', '', true],
  230. ['yes', 'group1', false],
  231. ];
  232. }
  233. /**
  234. * @dataProvider sharingDisabledPermissionProvider
  235. */
  236. public function testRemoveSharePermissionWhenSharingDisabledForUser($excludeGroups, $excludeGroupsList, $expectedShareable) {
  237. // Reset sharing disabled for users cache
  238. self::invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
  239. $config = \OC::$server->getConfig();
  240. $oldExcludeGroupsFlag = $config->getAppValue('core', 'shareapi_exclude_groups', 'no');
  241. $oldExcludeGroupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
  242. $config->setAppValue('core', 'shareapi_exclude_groups', $excludeGroups);
  243. $config->setAppValue('core', 'shareapi_exclude_groups_list', $excludeGroupsList);
  244. $storage1 = $this->getTestStorage();
  245. $storage2 = $this->getTestStorage();
  246. Filesystem::mount($storage1, [], '/');
  247. Filesystem::mount($storage2, [], '/mount');
  248. $view = new View('/');
  249. $folderContent = $view->getDirectoryContent('');
  250. $this->assertEquals($expectedShareable, $folderContent[0]->isShareable());
  251. $folderContent = $view->getDirectoryContent('mount');
  252. $this->assertEquals($expectedShareable, $folderContent[0]->isShareable());
  253. $config->setAppValue('core', 'shareapi_exclude_groups', $oldExcludeGroupsFlag);
  254. $config->setAppValue('core', 'shareapi_exclude_groups_list', $oldExcludeGroupsList);
  255. // Reset sharing disabled for users cache
  256. self::invokePrivate(\OC::$server->getShareManager(), 'sharingDisabledForUsersCache', [new CappedMemoryCache()]);
  257. }
  258. public function testCacheIncompleteFolder() {
  259. $storage1 = $this->getTestStorage(false);
  260. Filesystem::clearMounts();
  261. Filesystem::mount($storage1, [], '/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, [], '/');
  273. Filesystem::mount($storage2, [], '/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, [], '/');
  291. Filesystem::mount($storage2, [], '/substorage');
  292. Filesystem::mount($storage3, [], '/folder/anotherstorage');
  293. $rootView = new View('');
  294. $results = $rootView->search('foo');
  295. $this->assertCount(6, $results);
  296. $paths = [];
  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 = [];
  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 = [];
  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, [], '/');
  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', ['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, [], '/');
  369. Filesystem::mount($storage2, [], '/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, [], '/');
  410. Filesystem::mount($storage2, [], '/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, [], '/');
  427. Filesystem::mount($storage2, [], '/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, [], '/');
  462. Filesystem::mount($storage2, [], '/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, [], '/');
  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', ['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, [], '/');
  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, [], '/');
  509. Filesystem::mount($storage2, [], $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, [], '/');
  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([]);
  543. $textData = "dummy file data\n";
  544. $imgData = file_get_contents(\OC::$SERVERROOT . '/core/img/logo/logo.png');
  545. $storage->mkdir('folder');
  546. $storage->file_put_contents('foo.txt', $textData);
  547. $storage->file_put_contents('foo.png', $imgData);
  548. $storage->file_put_contents('folder/bar.txt', $textData);
  549. if ($scan) {
  550. $scanner = $storage->getScanner();
  551. $scanner->scan('');
  552. }
  553. $this->storages[] = $storage;
  554. return $storage;
  555. }
  556. /**
  557. * @medium
  558. */
  559. public function testViewHooksIfRootStartsTheSame() {
  560. $storage1 = $this->getTestStorage();
  561. $storage2 = $this->getTestStorage();
  562. $defaultRoot = Filesystem::getRoot();
  563. Filesystem::mount($storage1, [], '/');
  564. Filesystem::mount($storage2, [], $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, [], '/');
  588. Filesystem::mount($storage2, [], $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, [], '/');
  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 [
  623. ['foo.txt', 'foo.txt'],
  624. ['foo.txt', '/foo.txt'],
  625. ['folder', 'folder'],
  626. ['folder', '/folder'],
  627. ['folder', 'folder/'],
  628. ['folder', '/folder/'],
  629. ['folder/bar.txt', 'folder/bar.txt'],
  630. ['folder/bar.txt', '/folder/bar.txt'],
  631. ['', ''],
  632. ['', '/'],
  633. ];
  634. }
  635. public function testUTF8Names() {
  636. $names = ['虚', '和知しゃ和で', 'regular ascii', 'sɨˈrɪlɪk', 'ѨѬ', 'أنا أحب القراءة كثيرا'];
  637. $storage = new Temporary([]);
  638. Filesystem::mount($storage, [], '/');
  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([]);
  659. Filesystem::mount($storage, [], '/');
  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([]);
  699. $scanner = $storage->getScanner();
  700. Filesystem::mount($storage, [], '/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([]);
  713. $storage2 = new Temporary([]);
  714. $scanner1 = $storage1->getScanner();
  715. $scanner2 = $storage2->getScanner();
  716. $storage1->mkdir('sub');
  717. Filesystem::mount($storage1, [], '/test/');
  718. Filesystem::mount($storage2, [], '/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(), [
  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([]);
  744. $scanner = $storage->getScanner();
  745. Filesystem::mount($storage, [], '/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 [
  756. ['/files/', ''],
  757. ['/files/0', '0'],
  758. ['/files/false', 'false'],
  759. ['/files/true', 'true'],
  760. ['/files/', '/'],
  761. ['/files/test', 'test'],
  762. ['/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 [
  788. // No root - returns the path
  789. ['', '/files', '/files'],
  790. ['', '/files/', '/files/'],
  791. // Root equals path - /
  792. ['/files/', '/files/', '/'],
  793. ['/files/', '/files', '/'],
  794. ['/files', '/files/', '/'],
  795. ['/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. ['files/', '/files/', $missingRootExpectedPath],
  801. ['files', '/files/', $missingRootExpectedPath],
  802. ['files/', '/files', $missingRootExpectedPath],
  803. ['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. ['/files/', 'files/', null],
  807. ['/files', 'files/', null],
  808. ['/files/', 'files', null],
  809. ['/files', 'files', null],
  810. // with trailing slashes
  811. ['/files/', '/files/0', '0'],
  812. ['/files/', '/files/false', 'false'],
  813. ['/files/', '/files/true', 'true'],
  814. ['/files/', '/files/test', 'test'],
  815. ['/files/', '/files/test/foo', 'test/foo'],
  816. // without trailing slashes
  817. // TODO false expectation: Should match "with trailing slashes"
  818. ['/files', '/files/0', '/0'],
  819. ['/files', '/files/false', '/false'],
  820. ['/files', '/files/true', '/true'],
  821. ['/files', '/files/test', '/test'],
  822. ['/files', '/files/test/foo', '/test/foo'],
  823. // leading slashes
  824. ['/files/', '/files_trashbin/', null],
  825. ['/files', '/files_trashbin/', null],
  826. ['/files/', '/files_trashbin', null],
  827. ['/files', '/files_trashbin', null],
  828. // no leading slashes
  829. ['files/', 'files_trashbin/', null],
  830. ['files', 'files_trashbin/', null],
  831. ['files/', 'files_trashbin', null],
  832. ['files', 'files_trashbin', null],
  833. // mixed leading slashes
  834. ['files/', '/files_trashbin/', null],
  835. ['/files/', 'files_trashbin/', null],
  836. ['files', '/files_trashbin/', null],
  837. ['/files', 'files_trashbin/', null],
  838. ['files/', '/files_trashbin', null],
  839. ['/files/', 'files_trashbin', null],
  840. ['files', '/files_trashbin', null],
  841. ['/files', 'files_trashbin', null],
  842. ['files', 'files_trashbin/test', null],
  843. ['/files', '/files_trashbin/test', null],
  844. ['/files', 'files_trashbin/test', null],
  845. ];
  846. }
  847. public function testFileView() {
  848. $storage = new Temporary([]);
  849. $scanner = $storage->getScanner();
  850. $storage->file_put_contents('foo.txt', 'bar');
  851. Filesystem::mount($storage, [], '/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. */
  864. public function testTooLongPath($operation, $param0 = null) {
  865. $this->expectException(\OCP\Files\InvalidPathException::class);
  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([]);
  874. $this->tempStorage = $storage; // for later hard cleanup
  875. Filesystem::mount($storage, [], '/');
  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([$rootView, $operation], $longPath, $param0);
  885. }
  886. public function tooLongPathDataProvider() {
  887. return [
  888. ['getAbsolutePath'],
  889. ['getRelativePath'],
  890. ['getMountPoint'],
  891. ['resolvePath'],
  892. ['getLocalFile'],
  893. ['getLocalFolder'],
  894. ['mkdir'],
  895. ['rmdir'],
  896. ['opendir'],
  897. ['is_dir'],
  898. ['is_file'],
  899. ['stat'],
  900. ['filetype'],
  901. ['filesize'],
  902. ['readfile'],
  903. ['isCreatable'],
  904. ['isReadable'],
  905. ['isUpdatable'],
  906. ['isDeletable'],
  907. ['isSharable'],
  908. ['file_exists'],
  909. ['filemtime'],
  910. ['touch'],
  911. ['file_get_contents'],
  912. ['unlink'],
  913. ['deleteAll'],
  914. ['toTmpFile'],
  915. ['getMimeType'],
  916. ['free_space'],
  917. ['getFileInfo'],
  918. ['getDirectoryContent'],
  919. ['getOwner'],
  920. ['getETag'],
  921. ['file_put_contents', 'ipsum'],
  922. ['rename', '@0'],
  923. ['copy', '@0'],
  924. ['fopen', 'r'],
  925. ['fromTmpFile', '@0'],
  926. ['hash'],
  927. ['hasUpdated', 0],
  928. ['putFileInfo', []],
  929. ];
  930. }
  931. public function testRenameCrossStoragePreserveMtime() {
  932. $storage1 = new Temporary([]);
  933. $storage2 = new Temporary([]);
  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, [], '/test/');
  939. Filesystem::mount($storage2, [], '/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([]);
  958. /** @var \PHPUnit\Framework\MockObject\MockObject|Temporary $storage2 */
  959. $storage2 = $this->getMockBuilder(TemporaryNoCross::class)
  960. ->setConstructorArgs([[]])
  961. ->setMethods(['fopen', 'writeStream'])
  962. ->getMock();
  963. $storage2->method('writeStream')
  964. ->willThrowException(new GenericFileException("Failed to copy stream"));
  965. $storage1->mkdir('sub');
  966. $storage1->file_put_contents('foo.txt', '0123456789ABCDEFGH');
  967. $storage1->mkdir('dirtomove');
  968. $storage1->file_put_contents('dirtomove/indir1.txt', '0123456'); // fits
  969. $storage1->file_put_contents('dirtomove/indir2.txt', '0123456789ABCDEFGH'); // doesn't fit
  970. $storage2->file_put_contents('existing.txt', '0123');
  971. $storage1->getScanner()->scan('');
  972. $storage2->getScanner()->scan('');
  973. Filesystem::mount($storage1, [], '/test/');
  974. Filesystem::mount($storage2, [], '/test/sub/storage');
  975. // move file
  976. $view = new View('');
  977. $this->assertTrue($storage1->file_exists('foo.txt'));
  978. $this->assertFalse($storage2->file_exists('foo.txt'));
  979. $this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/foo.txt'));
  980. $this->assertFalse($storage2->file_exists('foo.txt'));
  981. $this->assertFalse($storage2->getCache()->get('foo.txt'));
  982. $this->assertTrue($storage1->file_exists('foo.txt'));
  983. // if target exists, it will be deleted too
  984. $this->assertFalse($view->$operation('/test/foo.txt', '/test/sub/storage/existing.txt'));
  985. $this->assertFalse($storage2->file_exists('existing.txt'));
  986. $this->assertFalse($storage2->getCache()->get('existing.txt'));
  987. $this->assertTrue($storage1->file_exists('foo.txt'));
  988. // move folder
  989. $this->assertFalse($view->$operation('/test/dirtomove/', '/test/sub/storage/dirtomove/'));
  990. // since the move failed, the full source tree is kept
  991. $this->assertTrue($storage1->file_exists('dirtomove/indir1.txt'));
  992. $this->assertTrue($storage1->file_exists('dirtomove/indir2.txt'));
  993. // second file not moved/copied
  994. $this->assertFalse($storage2->file_exists('dirtomove/indir2.txt'));
  995. $this->assertFalse($storage2->getCache()->get('dirtomove/indir2.txt'));
  996. }
  997. public function testDeleteFailKeepCache() {
  998. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  999. $storage = $this->getMockBuilder(Temporary::class)
  1000. ->setConstructorArgs([[]])
  1001. ->setMethods(['unlink'])
  1002. ->getMock();
  1003. $storage->expects($this->once())
  1004. ->method('unlink')
  1005. ->willReturn(false);
  1006. $scanner = $storage->getScanner();
  1007. $cache = $storage->getCache();
  1008. $storage->file_put_contents('foo.txt', 'asd');
  1009. $scanner->scan('');
  1010. Filesystem::mount($storage, [], '/test/');
  1011. $view = new View('/test');
  1012. $this->assertFalse($view->unlink('foo.txt'));
  1013. $this->assertTrue($cache->inCache('foo.txt'));
  1014. }
  1015. public function directoryTraversalProvider() {
  1016. return [
  1017. ['../test/'],
  1018. ['..\\test\\my/../folder'],
  1019. ['/test/my/../foo\\'],
  1020. ];
  1021. }
  1022. /**
  1023. * @dataProvider directoryTraversalProvider
  1024. * @param string $root
  1025. */
  1026. public function testConstructDirectoryTraversalException($root) {
  1027. $this->expectException(\Exception::class);
  1028. new View($root);
  1029. }
  1030. public function testRenameOverWrite() {
  1031. $storage = new Temporary([]);
  1032. $scanner = $storage->getScanner();
  1033. $storage->mkdir('sub');
  1034. $storage->mkdir('foo');
  1035. $storage->file_put_contents('foo.txt', 'asd');
  1036. $storage->file_put_contents('foo/bar.txt', 'asd');
  1037. $scanner->scan('');
  1038. Filesystem::mount($storage, [], '/test/');
  1039. $view = new View('');
  1040. $this->assertTrue($view->rename('/test/foo.txt', '/test/foo/bar.txt'));
  1041. }
  1042. public function testSetMountOptionsInStorage() {
  1043. $mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['foo' => 'bar']);
  1044. Filesystem::getMountManager()->addMount($mount);
  1045. /** @var \OC\Files\Storage\Common $storage */
  1046. $storage = $mount->getStorage();
  1047. $this->assertEquals($storage->getMountOption('foo'), 'bar');
  1048. }
  1049. public function testSetMountOptionsWatcherPolicy() {
  1050. $mount = new MountPoint(Temporary::class, '/asd/', [[]], Filesystem::getLoader(), ['filesystem_check_changes' => Watcher::CHECK_NEVER]);
  1051. Filesystem::getMountManager()->addMount($mount);
  1052. /** @var \OC\Files\Storage\Common $storage */
  1053. $storage = $mount->getStorage();
  1054. $watcher = $storage->getWatcher();
  1055. $this->assertEquals(Watcher::CHECK_NEVER, $watcher->getPolicy());
  1056. }
  1057. public function testGetAbsolutePathOnNull() {
  1058. $view = new View();
  1059. $this->assertNull($view->getAbsolutePath(null));
  1060. }
  1061. public function testGetRelativePathOnNull() {
  1062. $view = new View();
  1063. $this->assertNull($view->getRelativePath(null));
  1064. }
  1065. public function testNullAsRoot() {
  1066. $this->expectException(\InvalidArgumentException::class);
  1067. new View(null);
  1068. }
  1069. /**
  1070. * e.g. reading from a folder that's being renamed
  1071. *
  1072. *
  1073. * @dataProvider dataLockPaths
  1074. *
  1075. * @param string $rootPath
  1076. * @param string $pathPrefix
  1077. */
  1078. public function testReadFromWriteLockedPath($rootPath, $pathPrefix) {
  1079. $this->expectException(\OCP\Lock\LockedException::class);
  1080. $rootPath = str_replace('{folder}', 'files', $rootPath);
  1081. $pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
  1082. $view = new View($rootPath);
  1083. $storage = new Temporary([]);
  1084. Filesystem::mount($storage, [], '/');
  1085. $this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
  1086. $view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED);
  1087. }
  1088. /**
  1089. * Reading from a files_encryption folder that's being renamed
  1090. *
  1091. * @dataProvider dataLockPaths
  1092. *
  1093. * @param string $rootPath
  1094. * @param string $pathPrefix
  1095. */
  1096. public function testReadFromWriteUnlockablePath($rootPath, $pathPrefix) {
  1097. $rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
  1098. $pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
  1099. $view = new View($rootPath);
  1100. $storage = new Temporary([]);
  1101. Filesystem::mount($storage, [], '/');
  1102. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
  1103. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar/asd', ILockingProvider::LOCK_SHARED));
  1104. }
  1105. /**
  1106. * e.g. writing a file that's being downloaded
  1107. *
  1108. *
  1109. * @dataProvider dataLockPaths
  1110. *
  1111. * @param string $rootPath
  1112. * @param string $pathPrefix
  1113. */
  1114. public function testWriteToReadLockedFile($rootPath, $pathPrefix) {
  1115. $this->expectException(\OCP\Lock\LockedException::class);
  1116. $rootPath = str_replace('{folder}', 'files', $rootPath);
  1117. $pathPrefix = str_replace('{folder}', 'files', $pathPrefix);
  1118. $view = new View($rootPath);
  1119. $storage = new Temporary([]);
  1120. Filesystem::mount($storage, [], '/');
  1121. $this->assertTrue($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
  1122. $view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE);
  1123. }
  1124. /**
  1125. * Writing a file that's being downloaded
  1126. *
  1127. * @dataProvider dataLockPaths
  1128. *
  1129. * @param string $rootPath
  1130. * @param string $pathPrefix
  1131. */
  1132. public function testWriteToReadUnlockableFile($rootPath, $pathPrefix) {
  1133. $rootPath = str_replace('{folder}', 'files_encryption', $rootPath);
  1134. $pathPrefix = str_replace('{folder}', 'files_encryption', $pathPrefix);
  1135. $view = new View($rootPath);
  1136. $storage = new Temporary([]);
  1137. Filesystem::mount($storage, [], '/');
  1138. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_SHARED));
  1139. $this->assertFalse($view->lockFile($pathPrefix . '/foo/bar', ILockingProvider::LOCK_EXCLUSIVE));
  1140. }
  1141. /**
  1142. * Test that locks are on mount point paths instead of mount root
  1143. */
  1144. public function testLockLocalMountPointPathInsteadOfStorageRoot() {
  1145. $lockingProvider = \OC::$server->getLockingProvider();
  1146. $view = new View('/testuser/files/');
  1147. $storage = new Temporary([]);
  1148. Filesystem::mount($storage, [], '/');
  1149. $mountedStorage = new Temporary([]);
  1150. Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');
  1151. $this->assertTrue(
  1152. $view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, true),
  1153. 'Can lock mount point'
  1154. );
  1155. // no exception here because storage root was not locked
  1156. $mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1157. $thrown = false;
  1158. try {
  1159. $storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1160. } catch (LockedException $e) {
  1161. $thrown = true;
  1162. }
  1163. $this->assertTrue($thrown, 'Mount point path was locked on root storage');
  1164. $lockingProvider->releaseAll();
  1165. }
  1166. /**
  1167. * Test that locks are on mount point paths and also mount root when requested
  1168. */
  1169. public function testLockStorageRootButNotLocalMountPoint() {
  1170. $lockingProvider = \OC::$server->getLockingProvider();
  1171. $view = new View('/testuser/files/');
  1172. $storage = new Temporary([]);
  1173. Filesystem::mount($storage, [], '/');
  1174. $mountedStorage = new Temporary([]);
  1175. Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint');
  1176. $this->assertTrue(
  1177. $view->lockFile('/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, false),
  1178. 'Can lock mount point'
  1179. );
  1180. $thrown = false;
  1181. try {
  1182. $mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1183. } catch (LockedException $e) {
  1184. $thrown = true;
  1185. }
  1186. $this->assertTrue($thrown, 'Mount point storage root was locked on original storage');
  1187. // local mount point was not locked
  1188. $storage->acquireLock('/testuser/files/mountpoint', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1189. $lockingProvider->releaseAll();
  1190. }
  1191. /**
  1192. * Test that locks are on mount point paths and also mount root when requested
  1193. */
  1194. public function testLockMountPointPathFailReleasesBoth() {
  1195. $lockingProvider = \OC::$server->getLockingProvider();
  1196. $view = new View('/testuser/files/');
  1197. $storage = new Temporary([]);
  1198. Filesystem::mount($storage, [], '/');
  1199. $mountedStorage = new Temporary([]);
  1200. Filesystem::mount($mountedStorage, [], '/testuser/files/mountpoint.txt');
  1201. // this would happen if someone is writing on the mount point
  1202. $mountedStorage->acquireLock('', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1203. $thrown = false;
  1204. try {
  1205. // this actually acquires two locks, one on the mount point and one on the storage root,
  1206. // but the one on the storage root will fail
  1207. $view->lockFile('/mountpoint.txt', ILockingProvider::LOCK_SHARED);
  1208. } catch (LockedException $e) {
  1209. $thrown = true;
  1210. }
  1211. $this->assertTrue($thrown, 'Cannot acquire shared lock because storage root is already locked');
  1212. // from here we expect that the lock on the local mount point was released properly
  1213. // so acquiring an exclusive lock will succeed
  1214. $storage->acquireLock('/testuser/files/mountpoint.txt', ILockingProvider::LOCK_EXCLUSIVE, $lockingProvider);
  1215. $lockingProvider->releaseAll();
  1216. }
  1217. public function dataLockPaths() {
  1218. return [
  1219. ['/testuser/{folder}', ''],
  1220. ['/testuser', '/{folder}'],
  1221. ['', '/testuser/{folder}'],
  1222. ];
  1223. }
  1224. public function pathRelativeToFilesProvider() {
  1225. return [
  1226. ['admin/files', ''],
  1227. ['admin/files/x', 'x'],
  1228. ['/admin/files', ''],
  1229. ['/admin/files/sub', 'sub'],
  1230. ['/admin/files/sub/', 'sub'],
  1231. ['/admin/files/sub/sub2', 'sub/sub2'],
  1232. ['//admin//files/sub//sub2', 'sub/sub2'],
  1233. ];
  1234. }
  1235. /**
  1236. * @dataProvider pathRelativeToFilesProvider
  1237. */
  1238. public function testGetPathRelativeToFiles($path, $expectedPath) {
  1239. $view = new View();
  1240. $this->assertEquals($expectedPath, $view->getPathRelativeToFiles($path));
  1241. }
  1242. public function pathRelativeToFilesProviderExceptionCases() {
  1243. return [
  1244. [''],
  1245. ['x'],
  1246. ['files'],
  1247. ['/files'],
  1248. ['/admin/files_versions/abc'],
  1249. ];
  1250. }
  1251. /**
  1252. * @dataProvider pathRelativeToFilesProviderExceptionCases
  1253. * @param string $path
  1254. */
  1255. public function testGetPathRelativeToFilesWithInvalidArgument($path) {
  1256. $this->expectException(\InvalidArgumentException::class);
  1257. $this->expectExceptionMessage('$absolutePath must be relative to "files"');
  1258. $view = new View();
  1259. $view->getPathRelativeToFiles($path);
  1260. }
  1261. public function testChangeLock() {
  1262. $view = new View('/testuser/files/');
  1263. $storage = new Temporary([]);
  1264. Filesystem::mount($storage, [], '/');
  1265. $view->lockFile('/test/sub', ILockingProvider::LOCK_SHARED);
  1266. $this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
  1267. $this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
  1268. $view->changeLock('//test/sub', ILockingProvider::LOCK_EXCLUSIVE);
  1269. $this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
  1270. $view->changeLock('test/sub', ILockingProvider::LOCK_SHARED);
  1271. $this->assertTrue($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
  1272. $view->unlockFile('/test/sub/', ILockingProvider::LOCK_SHARED);
  1273. $this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_SHARED));
  1274. $this->assertFalse($this->isFileLocked($view, '/test//sub', ILockingProvider::LOCK_EXCLUSIVE));
  1275. }
  1276. public function hookPathProvider() {
  1277. return [
  1278. ['/foo/files', '/foo', true],
  1279. ['/foo/files/bar', '/foo', true],
  1280. ['/foo', '/foo', false],
  1281. ['/foo', '/files/foo', true],
  1282. ['/foo', 'filesfoo', false],
  1283. ['', '/foo/files', true],
  1284. ['', '/foo/files/bar.txt', true],
  1285. ];
  1286. }
  1287. /**
  1288. * @dataProvider hookPathProvider
  1289. * @param $root
  1290. * @param $path
  1291. * @param $shouldEmit
  1292. */
  1293. public function testHookPaths($root, $path, $shouldEmit) {
  1294. $filesystemReflection = new \ReflectionClass(Filesystem::class);
  1295. $defaultRootValue = $filesystemReflection->getProperty('defaultInstance');
  1296. $defaultRootValue->setAccessible(true);
  1297. $oldRoot = $defaultRootValue->getValue();
  1298. $defaultView = new View('/foo/files');
  1299. $defaultRootValue->setValue($defaultView);
  1300. $view = new View($root);
  1301. $result = self::invokePrivate($view, 'shouldEmitHooks', [$path]);
  1302. $defaultRootValue->setValue($oldRoot);
  1303. $this->assertEquals($shouldEmit, $result);
  1304. }
  1305. /**
  1306. * Create test movable mount points
  1307. *
  1308. * @param array $mountPoints array of mount point locations
  1309. * @return array array of MountPoint objects
  1310. */
  1311. private function createTestMovableMountPoints($mountPoints) {
  1312. $mounts = [];
  1313. foreach ($mountPoints as $mountPoint) {
  1314. $storage = $this->getMockBuilder(Temporary::class)
  1315. ->setMethods([])
  1316. ->getMock();
  1317. $mounts[] = $this->getMockBuilder(TestMoveableMountPoint::class)
  1318. ->setMethods(['moveMount'])
  1319. ->setConstructorArgs([$storage, $mountPoint])
  1320. ->getMock();
  1321. }
  1322. /** @var IMountProvider|\PHPUnit\Framework\MockObject\MockObject $mountProvider */
  1323. $mountProvider = $this->createMock(IMountProvider::class);
  1324. $mountProvider->expects($this->any())
  1325. ->method('getMountsForUser')
  1326. ->willReturn($mounts);
  1327. $mountProviderCollection = \OC::$server->getMountProviderCollection();
  1328. $mountProviderCollection->registerProvider($mountProvider);
  1329. return $mounts;
  1330. }
  1331. /**
  1332. * Test mount point move
  1333. */
  1334. public function testMountPointMove() {
  1335. self::loginAsUser($this->user);
  1336. [$mount1, $mount2] = $this->createTestMovableMountPoints([
  1337. $this->user . '/files/mount1',
  1338. $this->user . '/files/mount2',
  1339. ]);
  1340. $mount1->expects($this->once())
  1341. ->method('moveMount')
  1342. ->willReturn(true);
  1343. $mount2->expects($this->once())
  1344. ->method('moveMount')
  1345. ->willReturn(true);
  1346. $view = new View('/' . $this->user . '/files/');
  1347. $view->mkdir('sub');
  1348. $this->assertTrue($view->rename('mount1', 'renamed_mount'), 'Can rename mount point');
  1349. $this->assertTrue($view->rename('mount2', 'sub/moved_mount'), 'Can move a mount point into a subdirectory');
  1350. }
  1351. /**
  1352. * Test that moving a mount point into another is forbidden
  1353. */
  1354. public function testMoveMountPointIntoAnother() {
  1355. self::loginAsUser($this->user);
  1356. [$mount1, $mount2] = $this->createTestMovableMountPoints([
  1357. $this->user . '/files/mount1',
  1358. $this->user . '/files/mount2',
  1359. ]);
  1360. $mount1->expects($this->never())
  1361. ->method('moveMount');
  1362. $mount2->expects($this->never())
  1363. ->method('moveMount');
  1364. $view = new View('/' . $this->user . '/files/');
  1365. $this->assertFalse($view->rename('mount1', 'mount2'), 'Cannot overwrite another mount point');
  1366. $this->assertFalse($view->rename('mount1', 'mount2/sub'), 'Cannot move a mount point into another');
  1367. }
  1368. /**
  1369. * Test that moving a mount point into a shared folder is forbidden
  1370. */
  1371. public function testMoveMountPointIntoSharedFolder() {
  1372. self::loginAsUser($this->user);
  1373. [$mount1] = $this->createTestMovableMountPoints([
  1374. $this->user . '/files/mount1',
  1375. ]);
  1376. $mount1->expects($this->never())
  1377. ->method('moveMount');
  1378. $view = new View('/' . $this->user . '/files/');
  1379. $view->mkdir('shareddir');
  1380. $view->mkdir('shareddir/sub');
  1381. $view->mkdir('shareddir/sub2');
  1382. $fileId = $view->getFileInfo('shareddir')->getId();
  1383. $userObject = \OC::$server->getUserManager()->createUser('test2', 'IHateNonMockableStaticClasses');
  1384. $userFolder = \OC::$server->getUserFolder($this->user);
  1385. $shareDir = $userFolder->get('shareddir');
  1386. $shareManager = \OC::$server->getShareManager();
  1387. $share = $shareManager->newShare();
  1388. $share->setSharedWith('test2')
  1389. ->setSharedBy($this->user)
  1390. ->setShareType(IShare::TYPE_USER)
  1391. ->setPermissions(\OCP\Constants::PERMISSION_READ)
  1392. ->setNode($shareDir);
  1393. $shareManager->createShare($share);
  1394. $this->assertFalse($view->rename('mount1', 'shareddir'), 'Cannot overwrite shared folder');
  1395. $this->assertFalse($view->rename('mount1', 'shareddir/sub'), 'Cannot move mount point into shared folder');
  1396. $this->assertFalse($view->rename('mount1', 'shareddir/sub/sub2'), 'Cannot move mount point into shared subfolder');
  1397. $this->assertTrue(\OC\Share\Share::unshare('folder', $fileId, IShare::TYPE_USER, 'test2'));
  1398. $userObject->delete();
  1399. }
  1400. public function basicOperationProviderForLocks() {
  1401. return [
  1402. // --- write hook ----
  1403. [
  1404. 'touch',
  1405. ['touch-create.txt'],
  1406. 'touch-create.txt',
  1407. 'create',
  1408. ILockingProvider::LOCK_SHARED,
  1409. ILockingProvider::LOCK_EXCLUSIVE,
  1410. ILockingProvider::LOCK_SHARED,
  1411. ],
  1412. [
  1413. 'fopen',
  1414. ['test-write.txt', 'w'],
  1415. 'test-write.txt',
  1416. 'write',
  1417. ILockingProvider::LOCK_SHARED,
  1418. ILockingProvider::LOCK_EXCLUSIVE,
  1419. null,
  1420. // exclusive lock stays until fclose
  1421. ILockingProvider::LOCK_EXCLUSIVE,
  1422. ],
  1423. [
  1424. 'mkdir',
  1425. ['newdir'],
  1426. 'newdir',
  1427. 'write',
  1428. ILockingProvider::LOCK_SHARED,
  1429. ILockingProvider::LOCK_EXCLUSIVE,
  1430. ILockingProvider::LOCK_SHARED,
  1431. ],
  1432. [
  1433. 'file_put_contents',
  1434. ['file_put_contents.txt', 'blah'],
  1435. 'file_put_contents.txt',
  1436. 'write',
  1437. ILockingProvider::LOCK_SHARED,
  1438. ILockingProvider::LOCK_EXCLUSIVE,
  1439. ILockingProvider::LOCK_SHARED,
  1440. ],
  1441. // ---- delete hook ----
  1442. [
  1443. 'rmdir',
  1444. ['dir'],
  1445. 'dir',
  1446. 'delete',
  1447. ILockingProvider::LOCK_SHARED,
  1448. ILockingProvider::LOCK_EXCLUSIVE,
  1449. ILockingProvider::LOCK_SHARED,
  1450. ],
  1451. [
  1452. 'unlink',
  1453. ['test.txt'],
  1454. 'test.txt',
  1455. 'delete',
  1456. ILockingProvider::LOCK_SHARED,
  1457. ILockingProvider::LOCK_EXCLUSIVE,
  1458. ILockingProvider::LOCK_SHARED,
  1459. ],
  1460. // ---- read hook (no post hooks) ----
  1461. [
  1462. 'file_get_contents',
  1463. ['test.txt'],
  1464. 'test.txt',
  1465. 'read',
  1466. ILockingProvider::LOCK_SHARED,
  1467. ILockingProvider::LOCK_SHARED,
  1468. null,
  1469. ],
  1470. [
  1471. 'fopen',
  1472. ['test.txt', 'r'],
  1473. 'test.txt',
  1474. 'read',
  1475. ILockingProvider::LOCK_SHARED,
  1476. ILockingProvider::LOCK_SHARED,
  1477. null,
  1478. ],
  1479. [
  1480. 'opendir',
  1481. ['dir'],
  1482. 'dir',
  1483. 'read',
  1484. ILockingProvider::LOCK_SHARED,
  1485. ILockingProvider::LOCK_SHARED,
  1486. null,
  1487. ],
  1488. // ---- no lock, touch hook ---
  1489. ['touch', ['test.txt'], 'test.txt', 'touch', null, null, null],
  1490. // ---- no hooks, no locks ---
  1491. ['is_dir', ['dir'], 'dir', null],
  1492. ['is_file', ['dir'], 'dir', null],
  1493. ['stat', ['dir'], 'dir', null],
  1494. ['filetype', ['dir'], 'dir', null],
  1495. ['filesize', ['dir'], 'dir', null],
  1496. ['isCreatable', ['dir'], 'dir', null],
  1497. ['isReadable', ['dir'], 'dir', null],
  1498. ['isUpdatable', ['dir'], 'dir', null],
  1499. ['isDeletable', ['dir'], 'dir', null],
  1500. ['isSharable', ['dir'], 'dir', null],
  1501. ['file_exists', ['dir'], 'dir', null],
  1502. ['filemtime', ['dir'], 'dir', null],
  1503. ];
  1504. }
  1505. /**
  1506. * Test whether locks are set before and after the operation
  1507. *
  1508. * @dataProvider basicOperationProviderForLocks
  1509. *
  1510. * @param string $operation operation name on the view
  1511. * @param array $operationArgs arguments for the operation
  1512. * @param string $lockedPath path of the locked item to check
  1513. * @param string $hookType hook type
  1514. * @param int $expectedLockBefore expected lock during pre hooks
  1515. * @param int $expectedLockDuring expected lock during operation
  1516. * @param int $expectedLockAfter expected lock during post hooks
  1517. * @param int $expectedStrayLock expected lock after returning, should
  1518. * be null (unlock) for most operations
  1519. */
  1520. public function testLockBasicOperation(
  1521. $operation,
  1522. $operationArgs,
  1523. $lockedPath,
  1524. $hookType,
  1525. $expectedLockBefore = ILockingProvider::LOCK_SHARED,
  1526. $expectedLockDuring = ILockingProvider::LOCK_SHARED,
  1527. $expectedLockAfter = ILockingProvider::LOCK_SHARED,
  1528. $expectedStrayLock = null
  1529. ) {
  1530. $view = new View('/' . $this->user . '/files/');
  1531. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1532. $storage = $this->getMockBuilder(Temporary::class)
  1533. ->setMethods([$operation])
  1534. ->getMock();
  1535. Filesystem::mount($storage, [], $this->user . '/');
  1536. // work directly on disk because mkdir might be mocked
  1537. $realPath = $storage->getSourcePath('');
  1538. mkdir($realPath . '/files');
  1539. mkdir($realPath . '/files/dir');
  1540. file_put_contents($realPath . '/files/test.txt', 'blah');
  1541. $storage->getScanner()->scan('files');
  1542. $storage->expects($this->once())
  1543. ->method($operation)
  1544. ->willReturnCallback(
  1545. function () use ($view, $lockedPath, &$lockTypeDuring) {
  1546. $lockTypeDuring = $this->getFileLockType($view, $lockedPath);
  1547. return true;
  1548. }
  1549. );
  1550. $this->assertNull($this->getFileLockType($view, $lockedPath), 'File not locked before operation');
  1551. $this->connectMockHooks($hookType, $view, $lockedPath, $lockTypePre, $lockTypePost);
  1552. // do operation
  1553. call_user_func_array([$view, $operation], $operationArgs);
  1554. if ($hookType !== null) {
  1555. $this->assertEquals($expectedLockBefore, $lockTypePre, 'File locked properly during pre-hook');
  1556. $this->assertEquals($expectedLockAfter, $lockTypePost, 'File locked properly during post-hook');
  1557. $this->assertEquals($expectedLockDuring, $lockTypeDuring, 'File locked properly during operation');
  1558. } else {
  1559. $this->assertNull($lockTypeDuring, 'File not locked during operation');
  1560. }
  1561. $this->assertEquals($expectedStrayLock, $this->getFileLockType($view, $lockedPath));
  1562. }
  1563. /**
  1564. * Test locks for file_put_content with stream.
  1565. * This code path uses $storage->fopen instead
  1566. */
  1567. public function testLockFilePutContentWithStream() {
  1568. $view = new View('/' . $this->user . '/files/');
  1569. $path = 'test_file_put_contents.txt';
  1570. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1571. $storage = $this->getMockBuilder(Temporary::class)
  1572. ->setMethods(['fopen'])
  1573. ->getMock();
  1574. Filesystem::mount($storage, [], $this->user . '/');
  1575. $storage->mkdir('files');
  1576. $storage->expects($this->once())
  1577. ->method('fopen')
  1578. ->willReturnCallback(
  1579. function () use ($view, $path, &$lockTypeDuring) {
  1580. $lockTypeDuring = $this->getFileLockType($view, $path);
  1581. return fopen('php://temp', 'r+');
  1582. }
  1583. );
  1584. $this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);
  1585. $this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');
  1586. // do operation
  1587. $view->file_put_contents($path, fopen('php://temp', 'r+'));
  1588. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
  1589. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePost, 'File locked properly during post-hook');
  1590. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');
  1591. $this->assertNull($this->getFileLockType($view, $path));
  1592. }
  1593. /**
  1594. * Test locks for fopen with fclose at the end
  1595. */
  1596. public function testLockFopen() {
  1597. $view = new View('/' . $this->user . '/files/');
  1598. $path = 'test_file_put_contents.txt';
  1599. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1600. $storage = $this->getMockBuilder(Temporary::class)
  1601. ->setMethods(['fopen'])
  1602. ->getMock();
  1603. Filesystem::mount($storage, [], $this->user . '/');
  1604. $storage->mkdir('files');
  1605. $storage->expects($this->once())
  1606. ->method('fopen')
  1607. ->willReturnCallback(
  1608. function () use ($view, $path, &$lockTypeDuring) {
  1609. $lockTypeDuring = $this->getFileLockType($view, $path);
  1610. return fopen('php://temp', 'r+');
  1611. }
  1612. );
  1613. $this->connectMockHooks('write', $view, $path, $lockTypePre, $lockTypePost);
  1614. $this->assertNull($this->getFileLockType($view, $path), 'File not locked before operation');
  1615. // do operation
  1616. $res = $view->fopen($path, 'w');
  1617. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypePre, 'File locked properly during pre-hook');
  1618. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File locked properly during operation');
  1619. $this->assertNull($lockTypePost, 'No post hook, no lock check possible');
  1620. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeDuring, 'File still locked after fopen');
  1621. fclose($res);
  1622. $this->assertNull($this->getFileLockType($view, $path), 'File unlocked after fclose');
  1623. }
  1624. /**
  1625. * Test locks for fopen with fclose at the end
  1626. *
  1627. * @dataProvider basicOperationProviderForLocks
  1628. *
  1629. * @param string $operation operation name on the view
  1630. * @param array $operationArgs arguments for the operation
  1631. * @param string $path path of the locked item to check
  1632. */
  1633. public function testLockBasicOperationUnlocksAfterException(
  1634. $operation,
  1635. $operationArgs,
  1636. $path
  1637. ) {
  1638. if ($operation === 'touch') {
  1639. $this->markTestSkipped("touch handles storage exceptions internally");
  1640. }
  1641. $view = new View('/' . $this->user . '/files/');
  1642. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1643. $storage = $this->getMockBuilder(Temporary::class)
  1644. ->setMethods([$operation])
  1645. ->getMock();
  1646. Filesystem::mount($storage, [], $this->user . '/');
  1647. // work directly on disk because mkdir might be mocked
  1648. $realPath = $storage->getSourcePath('');
  1649. mkdir($realPath . '/files');
  1650. mkdir($realPath . '/files/dir');
  1651. file_put_contents($realPath . '/files/test.txt', 'blah');
  1652. $storage->getScanner()->scan('files');
  1653. $storage->expects($this->once())
  1654. ->method($operation)
  1655. ->willReturnCallback(
  1656. function () {
  1657. throw new \Exception('Simulated exception');
  1658. }
  1659. );
  1660. $thrown = false;
  1661. try {
  1662. call_user_func_array([$view, $operation], $operationArgs);
  1663. } catch (\Exception $e) {
  1664. $thrown = true;
  1665. $this->assertEquals('Simulated exception', $e->getMessage());
  1666. }
  1667. $this->assertTrue($thrown, 'Exception was rethrown');
  1668. $this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
  1669. }
  1670. public function testLockBasicOperationUnlocksAfterLockException() {
  1671. $view = new View('/' . $this->user . '/files/');
  1672. $storage = new Temporary([]);
  1673. Filesystem::mount($storage, [], $this->user . '/');
  1674. $storage->mkdir('files');
  1675. $storage->mkdir('files/dir');
  1676. $storage->file_put_contents('files/test.txt', 'blah');
  1677. $storage->getScanner()->scan('files');
  1678. // get a shared lock
  1679. $handle = $view->fopen('test.txt', 'r');
  1680. $thrown = false;
  1681. try {
  1682. // try (and fail) to get a write lock
  1683. $view->unlink('test.txt');
  1684. } catch (\Exception $e) {
  1685. $thrown = true;
  1686. $this->assertInstanceOf(LockedException::class, $e);
  1687. }
  1688. $this->assertTrue($thrown, 'Exception was rethrown');
  1689. // clean shared lock
  1690. fclose($handle);
  1691. $this->assertNull($this->getFileLockType($view, 'test.txt'), 'File got unlocked');
  1692. }
  1693. /**
  1694. * Test locks for fopen with fclose at the end
  1695. *
  1696. * @dataProvider basicOperationProviderForLocks
  1697. *
  1698. * @param string $operation operation name on the view
  1699. * @param array $operationArgs arguments for the operation
  1700. * @param string $path path of the locked item to check
  1701. * @param string $hookType hook type
  1702. */
  1703. public function testLockBasicOperationUnlocksAfterCancelledHook(
  1704. $operation,
  1705. $operationArgs,
  1706. $path,
  1707. $hookType
  1708. ) {
  1709. $view = new View('/' . $this->user . '/files/');
  1710. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1711. $storage = $this->getMockBuilder(Temporary::class)
  1712. ->setMethods([$operation])
  1713. ->getMock();
  1714. Filesystem::mount($storage, [], $this->user . '/');
  1715. $storage->mkdir('files');
  1716. Util::connectHook(
  1717. Filesystem::CLASSNAME,
  1718. $hookType,
  1719. HookHelper::class,
  1720. 'cancellingCallback'
  1721. );
  1722. call_user_func_array([$view, $operation], $operationArgs);
  1723. $this->assertNull($this->getFileLockType($view, $path), 'File got unlocked after exception');
  1724. }
  1725. public function lockFileRenameOrCopyDataProvider() {
  1726. return [
  1727. ['rename', ILockingProvider::LOCK_EXCLUSIVE],
  1728. ['copy', ILockingProvider::LOCK_SHARED],
  1729. ];
  1730. }
  1731. /**
  1732. * Test locks for rename or copy operation
  1733. *
  1734. * @dataProvider lockFileRenameOrCopyDataProvider
  1735. *
  1736. * @param string $operation operation to be done on the view
  1737. * @param int $expectedLockTypeSourceDuring expected lock type on source file during
  1738. * the operation
  1739. */
  1740. public function testLockFileRename($operation, $expectedLockTypeSourceDuring) {
  1741. $view = new View('/' . $this->user . '/files/');
  1742. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1743. $storage = $this->getMockBuilder(Temporary::class)
  1744. ->setMethods([$operation, 'getMetaData', 'filemtime'])
  1745. ->getMock();
  1746. $storage->expects($this->any())
  1747. ->method('getMetaData')
  1748. ->will($this->returnValue([
  1749. 'mtime' => 1885434487,
  1750. 'etag' => '',
  1751. 'mimetype' => 'text/plain',
  1752. 'permissions' => Constants::PERMISSION_ALL,
  1753. 'size' => 3
  1754. ]));
  1755. $storage->expects($this->any())
  1756. ->method('filemtime')
  1757. ->willReturn(123456789);
  1758. $sourcePath = 'original.txt';
  1759. $targetPath = 'target.txt';
  1760. Filesystem::mount($storage, [], $this->user . '/');
  1761. $storage->mkdir('files');
  1762. $view->file_put_contents($sourcePath, 'meh');
  1763. $storage->expects($this->once())
  1764. ->method($operation)
  1765. ->willReturnCallback(
  1766. function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
  1767. $lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
  1768. $lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);
  1769. return true;
  1770. }
  1771. );
  1772. $this->connectMockHooks($operation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
  1773. $this->connectMockHooks($operation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
  1774. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1775. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
  1776. $view->$operation($sourcePath, $targetPath);
  1777. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
  1778. $this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
  1779. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');
  1780. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
  1781. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
  1782. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');
  1783. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1784. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
  1785. }
  1786. /**
  1787. * simulate a failed copy operation.
  1788. * We expect that we catch the exception, free the lock and re-throw it.
  1789. *
  1790. */
  1791. public function testLockFileCopyException() {
  1792. $this->expectException(\Exception::class);
  1793. $view = new View('/' . $this->user . '/files/');
  1794. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1795. $storage = $this->getMockBuilder(Temporary::class)
  1796. ->setMethods(['copy'])
  1797. ->getMock();
  1798. $sourcePath = 'original.txt';
  1799. $targetPath = 'target.txt';
  1800. Filesystem::mount($storage, [], $this->user . '/');
  1801. $storage->mkdir('files');
  1802. $view->file_put_contents($sourcePath, 'meh');
  1803. $storage->expects($this->once())
  1804. ->method('copy')
  1805. ->willReturnCallback(
  1806. function () {
  1807. throw new \Exception();
  1808. }
  1809. );
  1810. $this->connectMockHooks('copy', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
  1811. $this->connectMockHooks('copy', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
  1812. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1813. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
  1814. try {
  1815. $view->copy($sourcePath, $targetPath);
  1816. } catch (\Exception $e) {
  1817. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1818. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
  1819. throw $e;
  1820. }
  1821. }
  1822. /**
  1823. * Test rename operation: unlock first path when second path was locked
  1824. */
  1825. public function testLockFileRenameUnlockOnException() {
  1826. self::loginAsUser('test');
  1827. $view = new View('/' . $this->user . '/files/');
  1828. $sourcePath = 'original.txt';
  1829. $targetPath = 'target.txt';
  1830. $view->file_put_contents($sourcePath, 'meh');
  1831. // simulate that the target path is already locked
  1832. $view->lockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
  1833. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1834. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file is locked before operation');
  1835. $thrown = false;
  1836. try {
  1837. $view->rename($sourcePath, $targetPath);
  1838. } catch (LockedException $e) {
  1839. $thrown = true;
  1840. }
  1841. $this->assertTrue($thrown, 'LockedException thrown');
  1842. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1843. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $this->getFileLockType($view, $targetPath), 'Target file still locked after operation');
  1844. $view->unlockFile($targetPath, ILockingProvider::LOCK_EXCLUSIVE);
  1845. }
  1846. /**
  1847. * Test rename operation: unlock first path when second path was locked
  1848. */
  1849. public function testGetOwner() {
  1850. self::loginAsUser('test');
  1851. $view = new View('/test/files/');
  1852. $path = 'foo.txt';
  1853. $view->file_put_contents($path, 'meh');
  1854. $this->assertEquals('test', $view->getFileInfo($path)->getOwner()->getUID());
  1855. $folderInfo = $view->getDirectoryContent('');
  1856. $folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
  1857. return $info->getName() === 'foo.txt';
  1858. }));
  1859. $this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());
  1860. $subStorage = new Temporary();
  1861. Filesystem::mount($subStorage, [], '/test/files/asd');
  1862. $folderInfo = $view->getDirectoryContent('');
  1863. $folderInfo = array_values(array_filter($folderInfo, function (FileInfo $info) {
  1864. return $info->getName() === 'asd';
  1865. }));
  1866. $this->assertEquals('test', $folderInfo[0]->getOwner()->getUID());
  1867. }
  1868. public function lockFileRenameOrCopyCrossStorageDataProvider() {
  1869. return [
  1870. ['rename', 'moveFromStorage', ILockingProvider::LOCK_EXCLUSIVE],
  1871. ['copy', 'copyFromStorage', ILockingProvider::LOCK_SHARED],
  1872. ];
  1873. }
  1874. /**
  1875. * Test locks for rename or copy operation cross-storage
  1876. *
  1877. * @dataProvider lockFileRenameOrCopyCrossStorageDataProvider
  1878. *
  1879. * @param string $viewOperation operation to be done on the view
  1880. * @param string $storageOperation operation to be mocked on the storage
  1881. * @param int $expectedLockTypeSourceDuring expected lock type on source file during
  1882. * the operation
  1883. */
  1884. public function testLockFileRenameCrossStorage($viewOperation, $storageOperation, $expectedLockTypeSourceDuring) {
  1885. $view = new View('/' . $this->user . '/files/');
  1886. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage */
  1887. $storage = $this->getMockBuilder(Temporary::class)
  1888. ->setMethods([$storageOperation])
  1889. ->getMock();
  1890. /** @var Temporary|\PHPUnit\Framework\MockObject\MockObject $storage2 */
  1891. $storage2 = $this->getMockBuilder(Temporary::class)
  1892. ->setMethods([$storageOperation, 'getMetaData', 'filemtime'])
  1893. ->getMock();
  1894. $storage2->expects($this->any())
  1895. ->method('getMetaData')
  1896. ->will($this->returnValue([
  1897. 'mtime' => 1885434487,
  1898. 'etag' => '',
  1899. 'mimetype' => 'text/plain',
  1900. 'permissions' => Constants::PERMISSION_ALL,
  1901. 'size' => 3
  1902. ]));
  1903. $storage2->expects($this->any())
  1904. ->method('filemtime')
  1905. ->willReturn(123456789);
  1906. $sourcePath = 'original.txt';
  1907. $targetPath = 'substorage/target.txt';
  1908. Filesystem::mount($storage, [], $this->user . '/');
  1909. Filesystem::mount($storage2, [], $this->user . '/files/substorage');
  1910. $storage->mkdir('files');
  1911. $view->file_put_contents($sourcePath, 'meh');
  1912. $storage->expects($this->never())
  1913. ->method($storageOperation);
  1914. $storage2->expects($this->once())
  1915. ->method($storageOperation)
  1916. ->willReturnCallback(
  1917. function () use ($view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring) {
  1918. $lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath);
  1919. $lockTypeTargetDuring = $this->getFileLockType($view, $targetPath);
  1920. return true;
  1921. }
  1922. );
  1923. $this->connectMockHooks($viewOperation, $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost);
  1924. $this->connectMockHooks($viewOperation, $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost);
  1925. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked before operation');
  1926. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked before operation');
  1927. $view->$viewOperation($sourcePath, $targetPath);
  1928. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source file locked properly during pre-hook');
  1929. $this->assertEquals($expectedLockTypeSourceDuring, $lockTypeSourceDuring, 'Source file locked properly during operation');
  1930. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source file locked properly during post-hook');
  1931. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target file locked properly during pre-hook');
  1932. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target file locked properly during operation');
  1933. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target file locked properly during post-hook');
  1934. $this->assertNull($this->getFileLockType($view, $sourcePath), 'Source file not locked after operation');
  1935. $this->assertNull($this->getFileLockType($view, $targetPath), 'Target file not locked after operation');
  1936. }
  1937. /**
  1938. * Test locks when moving a mount point
  1939. */
  1940. public function testLockMoveMountPoint() {
  1941. self::loginAsUser('test');
  1942. [$mount] = $this->createTestMovableMountPoints([
  1943. $this->user . '/files/substorage',
  1944. ]);
  1945. $view = new View('/' . $this->user . '/files/');
  1946. $view->mkdir('subdir');
  1947. $sourcePath = 'substorage';
  1948. $targetPath = 'subdir/substorage_moved';
  1949. $mount->expects($this->once())
  1950. ->method('moveMount')
  1951. ->willReturnCallback(
  1952. function ($target) use ($mount, $view, $sourcePath, $targetPath, &$lockTypeSourceDuring, &$lockTypeTargetDuring, &$lockTypeSharedRootDuring) {
  1953. $lockTypeSourceDuring = $this->getFileLockType($view, $sourcePath, true);
  1954. $lockTypeTargetDuring = $this->getFileLockType($view, $targetPath, true);
  1955. $lockTypeSharedRootDuring = $this->getFileLockType($view, $sourcePath, false);
  1956. $mount->setMountPoint($target);
  1957. return true;
  1958. }
  1959. );
  1960. $this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSourcePre, $lockTypeSourcePost, true);
  1961. $this->connectMockHooks('rename', $view, $targetPath, $lockTypeTargetPre, $lockTypeTargetPost, true);
  1962. // in pre-hook, mount point is still on $sourcePath
  1963. $this->connectMockHooks('rename', $view, $sourcePath, $lockTypeSharedRootPre, $dummy, false);
  1964. // in post-hook, mount point is now on $targetPath
  1965. $this->connectMockHooks('rename', $view, $targetPath, $dummy, $lockTypeSharedRootPost, false);
  1966. $this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked before operation');
  1967. $this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked before operation');
  1968. $this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked before operation');
  1969. $view->rename($sourcePath, $targetPath);
  1970. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePre, 'Source path locked properly during pre-hook');
  1971. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeSourceDuring, 'Source path locked properly during operation');
  1972. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeSourcePost, 'Source path locked properly during post-hook');
  1973. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPre, 'Target path locked properly during pre-hook');
  1974. $this->assertEquals(ILockingProvider::LOCK_EXCLUSIVE, $lockTypeTargetDuring, 'Target path locked properly during operation');
  1975. $this->assertEquals(ILockingProvider::LOCK_SHARED, $lockTypeTargetPost, 'Target path locked properly during post-hook');
  1976. $this->assertNull($lockTypeSharedRootPre, 'Shared storage root not locked during pre-hook');
  1977. $this->assertNull($lockTypeSharedRootDuring, 'Shared storage root not locked during move');
  1978. $this->assertNull($lockTypeSharedRootPost, 'Shared storage root not locked during post-hook');
  1979. $this->assertNull($this->getFileLockType($view, $sourcePath, false), 'Shared storage root not locked after operation');
  1980. $this->assertNull($this->getFileLockType($view, $sourcePath, true), 'Source path not locked after operation');
  1981. $this->assertNull($this->getFileLockType($view, $targetPath, true), 'Target path not locked after operation');
  1982. }
  1983. /**
  1984. * Connect hook callbacks for hook type
  1985. *
  1986. * @param string $hookType hook type or null for none
  1987. * @param View $view view to check the lock on
  1988. * @param string $path path for which to check the lock
  1989. * @param int $lockTypePre variable to receive lock type that was active in the pre-hook
  1990. * @param int $lockTypePost variable to receive lock type that was active in the post-hook
  1991. * @param bool $onMountPoint true to check the mount point instead of the
  1992. * mounted storage
  1993. */
  1994. private function connectMockHooks($hookType, $view, $path, &$lockTypePre, &$lockTypePost, $onMountPoint = false) {
  1995. if ($hookType === null) {
  1996. return;
  1997. }
  1998. $eventHandler = $this->getMockBuilder(\stdclass::class)
  1999. ->setMethods(['preCallback', 'postCallback'])
  2000. ->getMock();
  2001. $eventHandler->expects($this->any())
  2002. ->method('preCallback')
  2003. ->willReturnCallback(
  2004. function () use ($view, $path, $onMountPoint, &$lockTypePre) {
  2005. $lockTypePre = $this->getFileLockType($view, $path, $onMountPoint);
  2006. }
  2007. );
  2008. $eventHandler->expects($this->any())
  2009. ->method('postCallback')
  2010. ->willReturnCallback(
  2011. function () use ($view, $path, $onMountPoint, &$lockTypePost) {
  2012. $lockTypePost = $this->getFileLockType($view, $path, $onMountPoint);
  2013. }
  2014. );
  2015. if ($hookType !== null) {
  2016. Util::connectHook(
  2017. Filesystem::CLASSNAME,
  2018. $hookType,
  2019. $eventHandler,
  2020. 'preCallback'
  2021. );
  2022. Util::connectHook(
  2023. Filesystem::CLASSNAME,
  2024. 'post_' . $hookType,
  2025. $eventHandler,
  2026. 'postCallback'
  2027. );
  2028. }
  2029. }
  2030. /**
  2031. * Returns the file lock type
  2032. *
  2033. * @param View $view view
  2034. * @param string $path path
  2035. * @param bool $onMountPoint true to check the mount point instead of the
  2036. * mounted storage
  2037. *
  2038. * @return int lock type or null if file was not locked
  2039. */
  2040. private function getFileLockType(View $view, $path, $onMountPoint = false) {
  2041. if ($this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE, $onMountPoint)) {
  2042. return ILockingProvider::LOCK_EXCLUSIVE;
  2043. } elseif ($this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED, $onMountPoint)) {
  2044. return ILockingProvider::LOCK_SHARED;
  2045. }
  2046. return null;
  2047. }
  2048. public function testRemoveMoveableMountPoint() {
  2049. $mountPoint = '/' . $this->user . '/files/mount/';
  2050. // Mock the mount point
  2051. /** @var TestMoveableMountPoint|\PHPUnit\Framework\MockObject\MockObject $mount */
  2052. $mount = $this->createMock(TestMoveableMountPoint::class);
  2053. $mount->expects($this->once())
  2054. ->method('getMountPoint')
  2055. ->willReturn($mountPoint);
  2056. $mount->expects($this->once())
  2057. ->method('removeMount')
  2058. ->willReturn('foo');
  2059. $mount->expects($this->any())
  2060. ->method('getInternalPath')
  2061. ->willReturn('');
  2062. // Register mount
  2063. Filesystem::getMountManager()->addMount($mount);
  2064. // Listen for events
  2065. $eventHandler = $this->getMockBuilder(\stdclass::class)
  2066. ->setMethods(['umount', 'post_umount'])
  2067. ->getMock();
  2068. $eventHandler->expects($this->once())
  2069. ->method('umount')
  2070. ->with([Filesystem::signal_param_path => '/mount']);
  2071. $eventHandler->expects($this->once())
  2072. ->method('post_umount')
  2073. ->with([Filesystem::signal_param_path => '/mount']);
  2074. Util::connectHook(
  2075. Filesystem::CLASSNAME,
  2076. 'umount',
  2077. $eventHandler,
  2078. 'umount'
  2079. );
  2080. Util::connectHook(
  2081. Filesystem::CLASSNAME,
  2082. 'post_umount',
  2083. $eventHandler,
  2084. 'post_umount'
  2085. );
  2086. //Delete the mountpoint
  2087. $view = new View('/' . $this->user . '/files');
  2088. $this->assertEquals('foo', $view->rmdir('mount'));
  2089. }
  2090. public function mimeFilterProvider() {
  2091. return [
  2092. [null, ['test1.txt', 'test2.txt', 'test3.md', 'test4.png']],
  2093. ['text/plain', ['test1.txt', 'test2.txt']],
  2094. ['text/markdown', ['test3.md']],
  2095. ['text', ['test1.txt', 'test2.txt', 'test3.md']],
  2096. ];
  2097. }
  2098. /**
  2099. * @param string $filter
  2100. * @param string[] $expected
  2101. * @dataProvider mimeFilterProvider
  2102. */
  2103. public function testGetDirectoryContentMimeFilter($filter, $expected) {
  2104. $storage1 = new Temporary();
  2105. $root = self::getUniqueID('/');
  2106. Filesystem::mount($storage1, [], $root . '/');
  2107. $view = new View($root);
  2108. $view->file_put_contents('test1.txt', 'asd');
  2109. $view->file_put_contents('test2.txt', 'asd');
  2110. $view->file_put_contents('test3.md', 'asd');
  2111. $view->file_put_contents('test4.png', '');
  2112. $content = $view->getDirectoryContent('', $filter);
  2113. $files = array_map(function (FileInfo $info) {
  2114. return $info->getName();
  2115. }, $content);
  2116. sort($files);
  2117. $this->assertEquals($expected, $files);
  2118. }
  2119. public function testFilePutContentsClearsChecksum() {
  2120. $storage = new Temporary([]);
  2121. $scanner = $storage->getScanner();
  2122. $storage->file_put_contents('foo.txt', 'bar');
  2123. Filesystem::mount($storage, [], '/test/');
  2124. $scanner->scan('');
  2125. $view = new View('/test/foo.txt');
  2126. $view->putFileInfo('.', ['checksum' => '42']);
  2127. $this->assertEquals('bar', $view->file_get_contents(''));
  2128. $fh = tmpfile();
  2129. fwrite($fh, 'fooo');
  2130. rewind($fh);
  2131. clearstatcache();
  2132. $view->file_put_contents('', $fh);
  2133. $this->assertEquals('fooo', $view->file_get_contents(''));
  2134. $data = $view->getFileInfo('.');
  2135. $this->assertEquals('', $data->getChecksum());
  2136. }
  2137. public function testDeleteGhostFile() {
  2138. $storage = new Temporary([]);
  2139. $scanner = $storage->getScanner();
  2140. $cache = $storage->getCache();
  2141. $storage->file_put_contents('foo.txt', 'bar');
  2142. Filesystem::mount($storage, [], '/test/');
  2143. $scanner->scan('');
  2144. $storage->unlink('foo.txt');
  2145. $this->assertTrue($cache->inCache('foo.txt'));
  2146. $view = new View('/test');
  2147. $rootInfo = $view->getFileInfo('');
  2148. $this->assertEquals(3, $rootInfo->getSize());
  2149. $view->unlink('foo.txt');
  2150. $newInfo = $view->getFileInfo('');
  2151. $this->assertFalse($cache->inCache('foo.txt'));
  2152. $this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
  2153. $this->assertEquals(0, $newInfo->getSize());
  2154. }
  2155. public function testDeleteGhostFolder() {
  2156. $storage = new Temporary([]);
  2157. $scanner = $storage->getScanner();
  2158. $cache = $storage->getCache();
  2159. $storage->mkdir('foo');
  2160. $storage->file_put_contents('foo/foo.txt', 'bar');
  2161. Filesystem::mount($storage, [], '/test/');
  2162. $scanner->scan('');
  2163. $storage->rmdir('foo');
  2164. $this->assertTrue($cache->inCache('foo'));
  2165. $this->assertTrue($cache->inCache('foo/foo.txt'));
  2166. $view = new View('/test');
  2167. $rootInfo = $view->getFileInfo('');
  2168. $this->assertEquals(3, $rootInfo->getSize());
  2169. $view->rmdir('foo');
  2170. $newInfo = $view->getFileInfo('');
  2171. $this->assertFalse($cache->inCache('foo'));
  2172. $this->assertFalse($cache->inCache('foo/foo.txt'));
  2173. $this->assertNotEquals($rootInfo->getEtag(), $newInfo->getEtag());
  2174. $this->assertEquals(0, $newInfo->getSize());
  2175. }
  2176. public function testCreateParentDirectories() {
  2177. $view = $this->getMockBuilder(View::class)
  2178. ->disableOriginalConstructor()
  2179. ->setMethods([
  2180. 'is_file',
  2181. 'file_exists',
  2182. 'mkdir',
  2183. ])
  2184. ->getMock();
  2185. $view
  2186. ->expects($this->at(0))
  2187. ->method('is_file')
  2188. ->with('/new')
  2189. ->willReturn(false);
  2190. $view
  2191. ->expects($this->at(1))
  2192. ->method('file_exists')
  2193. ->with('/new')
  2194. ->willReturn(true);
  2195. $view
  2196. ->expects($this->at(2))
  2197. ->method('is_file')
  2198. ->with('/new/folder')
  2199. ->willReturn(false);
  2200. $view
  2201. ->expects($this->at(3))
  2202. ->method('file_exists')
  2203. ->with('/new/folder')
  2204. ->willReturn(false);
  2205. $view
  2206. ->expects($this->at(4))
  2207. ->method('mkdir')
  2208. ->with('/new/folder');
  2209. $view
  2210. ->expects($this->at(5))
  2211. ->method('is_file')
  2212. ->with('/new/folder/structure')
  2213. ->willReturn(false);
  2214. $view
  2215. ->expects($this->at(6))
  2216. ->method('file_exists')
  2217. ->with('/new/folder/structure')
  2218. ->willReturn(false);
  2219. $view
  2220. ->expects($this->at(7))
  2221. ->method('mkdir')
  2222. ->with('/new/folder/structure');
  2223. $this->assertTrue(self::invokePrivate($view, 'createParentDirectories', ['/new/folder/structure']));
  2224. }
  2225. public function testCreateParentDirectoriesWithExistingFile() {
  2226. $view = $this->getMockBuilder(View::class)
  2227. ->disableOriginalConstructor()
  2228. ->setMethods([
  2229. 'is_file',
  2230. 'file_exists',
  2231. 'mkdir',
  2232. ])
  2233. ->getMock();
  2234. $view
  2235. ->expects($this->once())
  2236. ->method('is_file')
  2237. ->with('/file.txt')
  2238. ->willReturn(true);
  2239. $this->assertFalse(self::invokePrivate($view, 'createParentDirectories', ['/file.txt/folder/structure']));
  2240. }
  2241. public function testCacheExtension() {
  2242. $storage = new Temporary([]);
  2243. $scanner = $storage->getScanner();
  2244. $storage->file_put_contents('foo.txt', 'bar');
  2245. $scanner->scan('');
  2246. Filesystem::mount($storage, [], '/test/');
  2247. $view = new View('/test');
  2248. $info = $view->getFileInfo('/foo.txt');
  2249. $this->assertEquals(0, $info->getUploadTime());
  2250. $this->assertEquals(0, $info->getCreationTime());
  2251. $view->putFileInfo('/foo.txt', ['upload_time' => 25]);
  2252. $info = $view->getFileInfo('/foo.txt');
  2253. $this->assertEquals(25, $info->getUploadTime());
  2254. $this->assertEquals(0, $info->getCreationTime());
  2255. }
  2256. }