ViewTest.php 84 KB

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